The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Audit existing unit tests + Remove redundant ones (#52215)
Joshen Lim60b51d74d53c
diff --git a/.github/workflows/studio-unit-tests.yml b/.github/workflows/studio-unit-tests.ymlindex db87050763f..e8fb190b37d 100644--- a/.github/workflows/studio-unit-tests.yml+++ b/.github/workflows/studio-unit-tests.yml@@ -25,12 +25,15 @@ permissions:contents: readjobs:- test:+ test-shard:+ name: 'Unit tests (shard ${{ matrix.shard }}/${{ strategy.job-total }})'# Uses larger hosted runner as it significantly decreases build timesruns-on: blacksmith-4vcpu-ubuntu-2404strategy:+ # Let every shard report its failures instead of cancelling the others+ fail-fast: falsematrix:- test_number: [1]+ shard: [1, 2, 3, 4]outputs:tests_ran: ${{ steps.filter.outputs.relevant }}@@ -78,16 +81,40 @@ jobs:env:# Default is 2 GB, increase to have less frequent OOM errorsNODE_OPTIONS: '--max_old_space_size=3072'- run: pnpm run test:ci+ SHARD: ${{ matrix.shard }}+ SHARD_TOTAL: ${{ strategy.job-total }}+ run: pnpm run test:ci --shard="$SHARD/$SHARD_TOTAL"working-directory: ./apps/studio- name: Upload coverage artifactif: steps.filter.outputs.relevant == 'true'uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2with:- name: studio-coverage+ name: studio-coverage-${{ matrix.shard }}path: ./apps/studio/coverage/lcov.inforetention-days: 1+ # Single pass/fail result across all shards. Keeps the `test (1)` check name that+ # branch protection requires, so changing the shard count doesn't touch protection rules.+ test:+ needs: test-shard+ if: ${{ !cancelled() }}+ runs-on: ubuntu-latest+ permissions: {}+ strategy:+ matrix:+ test_number: [1]+ outputs:+ tests_ran: ${{ needs.test-shard.outputs.tests_ran }}+ steps:+ - name: Check all shards passed+ env:+ SHARDS_RESULT: ${{ needs.test-shard.result }}+ run: |+ if [ "$SHARDS_RESULT" != "success" ]; then+ echo "One or more unit test shards did not pass (result: $SHARDS_RESULT)"+ exit 1+ fi+coveralls:needs: testif: ${{ always() && needs.test.result == 'success' && needs.test.outputs.tests_ran == 'true' }}@@ -100,17 +127,21 @@ jobs:sparse-checkout: |apps/studiopatches- - name: Download coverage artifact+ - name: Download coverage artifactsuses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0with:- name: studio-coverage+ pattern: studio-coverage-*path: ./coverage+ - name: List shard coverage files+ id: coverage+ run: echo "files=$(ls ./coverage/*/lcov.info | tr '\n' ' ')" >> "$GITHUB_OUTPUT"- name: Upload coverage results to Coverallsuses: coverallsapp/github-action@648a8eb78e6d50909eff900e4ec85cab4524a45b # v2.3.6continue-on-error: truewith:flag-name: studio-testsgithub-token: ${{ secrets.GITHUB_TOKEN }}- path-to-lcov: ./coverage/lcov.info+ # Coveralls merges the per-shard reports into one result+ files: ${{ steps.coverage.outputs.files }}base-path: './apps/studio'fail-on-error: falsediff --git a/apps/studio/components/grid/components/footer/pagination/Pagination.utils.test.ts b/apps/studio/components/grid/components/footer/pagination/Pagination.utils.test.tsindex 56afb597a51..e33fa99822b 100644--- a/apps/studio/components/grid/components/footer/pagination/Pagination.utils.test.ts+++ b/apps/studio/components/grid/components/footer/pagination/Pagination.utils.test.ts@@ -3,48 +3,16 @@ import { describe, expect, test } from 'vitest'import { formatEstimatedCount } from './Pagination.utils'describe('formatEstimatedCount', () => {- test('Should estimate thousands correctly (I)', () => {- const output = formatEstimatedCount(1530)- expect(output).toStrictEqual('1.5K')- })- test('Should estimate thousands correctly (II)', () => {- const output = formatEstimatedCount(15310)- expect(output).toStrictEqual('15.3K')- })- test('Should estimate thousands correctly (III)', () => {- const output = formatEstimatedCount(153122)- expect(output).toStrictEqual('153.1K')- })- test('Should estimate millions correctly (I)', () => {- const output = formatEstimatedCount(1531021)- expect(output).toStrictEqual('1.5M')- })- test('Should estimate millions correctly (II)', () => {- const output = formatEstimatedCount(15310212)- expect(output).toStrictEqual('15.3M')- })- test('Should estimate millions correctly (III)', () => {- const output = formatEstimatedCount(153102121)- expect(output).toStrictEqual('153.1M')- })- test('Should estimate billions correctly (I)', () => {- const output = formatEstimatedCount(1531021211)- expect(output).toStrictEqual('1.5B')- })- test('Should estimate billions correctly (II)', () => {- const output = formatEstimatedCount(15310212112)- expect(output).toStrictEqual('15.3B')- })- test('Should estimate billions correctly (III)', () => {- const output = formatEstimatedCount(153102121123)- expect(output).toStrictEqual('153.1B')- })- test('Should estimate trillions correctly (I)', () => {- const output = formatEstimatedCount(1531021211232)- expect(output).toStrictEqual('1.5T')- })- test('Should estimate trillions correctly (II) and max out at trillions', () => {- const output = formatEstimatedCount(1531021211232222)- expect(output).toStrictEqual('1531.0T')+ test.each([+ [1530, '1.5K'],+ [153122, '153.1K'],+ [1531021, '1.5M'],+ [15310212, '15.3M'],+ [1531021211, '1.5B'],+ [1531021211232, '1.5T'],+ // Maxes out at trillions+ [1531021211232222, '1531.0T'],+ ])('formats %d as %s', (count, expected) => {+ expect(formatEstimatedCount(count)).toBe(expected)})})diff --git a/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.utils.test.ts b/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.utils.test.tsindex f130654d834..e77abf648a6 100644--- a/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.utils.test.ts+++ b/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.utils.test.ts@@ -53,7 +53,7 @@ describe('findColumnForeignKeyConstraint', () => {table: 'machine_storage_usage_buckets',columnName: 'org_metering_bucket_id',})- ).toBe(compositeForeignKey)+ ).toEqual(compositeForeignKey)})test('finds the constraint for any column of a composite key', () => {@@ -64,7 +64,7 @@ describe('findColumnForeignKeyConstraint', () => {table: 'machine_storage_usage_buckets',columnName: 'org_id',})- ).toBe(compositeForeignKey)+ ).toEqual(compositeForeignKey)})test('ignores constraints from other tables with the same column name', () => {@@ -126,20 +126,6 @@ describe('getReferencingRecordFilters', () => {])})- test('builds the same filters regardless of which source column was clicked', () => {- const row = { idx: 0, org_id: 1, org_metering_bucket_id: 901 }- const filters = getReferencingRecordFilters({- foreignKey: compositeForeignKey,- row,- columns: bigintColumns,- })-- expect(filters).toStrictEqual([- { column: 'org_id', operator: '=', value: 1 },- { column: 'bucket_id', operator: '=', value: 901 },- ])- })-test('builds a single filter for a single-column foreign key', () => {expect(getReferencingRecordFilters({diff --git a/apps/studio/components/grid/components/header/filter/FilterPopoverNew.utils.test.ts b/apps/studio/components/grid/components/header/filter/FilterPopoverNew.utils.test.tsindex 72f2f964261..f14f871f4d9 100644--- a/apps/studio/components/grid/components/header/filter/FilterPopoverNew.utils.test.ts+++ b/apps/studio/components/grid/components/header/filter/FilterPopoverNew.utils.test.ts@@ -3,148 +3,44 @@ import { describe, expect, test } from 'vitest'import { buildFilterFromCellValue, isComplexValue } from './FilterPopoverNew.utils'describe('isComplexValue', () => {- test('returns false for null', () => {- expect(isComplexValue(null)).toBe(false)- })-- test('returns false for undefined', () => {- expect(isComplexValue(undefined)).toBe(false)- })-- test('returns false for strings', () => {- expect(isComplexValue('hello')).toBe(false)- expect(isComplexValue('')).toBe(false)- })-- test('returns false for numbers', () => {- expect(isComplexValue(42)).toBe(false)- expect(isComplexValue(0)).toBe(false)- expect(isComplexValue(-1)).toBe(false)- expect(isComplexValue(3.14)).toBe(false)- })-- test('returns false for booleans', () => {- expect(isComplexValue(true)).toBe(false)- expect(isComplexValue(false)).toBe(false)- })-- test('returns true for empty objects', () => {- expect(isComplexValue({})).toBe(true)- })-- test('returns true for objects with properties', () => {- expect(isComplexValue({ key: 'value' })).toBe(true)- expect(isComplexValue({ nested: { key: 'value' } })).toBe(true)- })-- test('returns true for empty arrays', () => {- expect(isComplexValue([])).toBe(true)- })-- test('returns true for arrays with items', () => {- expect(isComplexValue([1, 2, 3])).toBe(true)- expect(isComplexValue(['a', 'b'])).toBe(true)- expect(isComplexValue([{ key: 'value' }])).toBe(true)- })+ test.each([null, undefined, 'hello', '', 42, 0, -1, 3.14, true, false])(+ 'returns false for primitive %j',+ (value) => {+ expect(isComplexValue(value)).toBe(false)+ }+ )++ test.each([{}, { nested: { key: 'value' } }, [], [1, 2, 3], [{ key: 'value' }]])(+ 'returns true for object or array %j',+ (value) => {+ expect(isComplexValue(value)).toBe(true)+ }+ )})describe('buildFilterFromCellValue', () => {- test('creates filter with equals operator for string values', () => {- const filter = buildFilterFromCellValue('name', 'Alice')- expect(filter).toEqual({- column: 'name',- operator: '=',- value: 'Alice',- })- })-- test('creates filter with equals operator for empty string', () => {- const filter = buildFilterFromCellValue('label', '')- expect(filter).toEqual({- column: 'label',- operator: '=',- value: '',- })- })-- test('creates filter with equals operator for numbers', () => {- const filter = buildFilterFromCellValue('age', 42)- expect(filter).toEqual({- column: 'age',- operator: '=',- value: '42',- })- })-- test('creates filter with equals operator for zero', () => {- const filter = buildFilterFromCellValue('count', 0)- expect(filter).toEqual({- column: 'count',- operator: '=',- value: '0',- })- })-- test('creates filter with equals operator for negative numbers', () => {- const filter = buildFilterFromCellValue('balance', -100)- expect(filter).toEqual({- column: 'balance',- operator: '=',- value: '-100',- })- })-- test('creates filter with equals operator for boolean true', () => {- const filter = buildFilterFromCellValue('active', true)- expect(filter).toEqual({- column: 'active',- operator: '=',- value: 'true',- })- })-- test('creates filter with equals operator for boolean false', () => {- const filter = buildFilterFromCellValue('active', false)- expect(filter).toEqual({- column: 'active',- operator: '=',- value: 'false',- })- })-- test('creates filter with is operator for null', () => {- const filter = buildFilterFromCellValue('name', null)- expect(filter).toEqual({- column: 'name',+ test.each([+ ['Alice', 'Alice'],+ ['', ''],+ ['2024-01-01T12:00:00Z', '2024-01-01T12:00:00Z'],+ [42, '42'],+ [0, '0'],+ [-100, '-100'],+ [true, 'true'],+ [false, 'false'],+ ])('uses the equals operator for %j', (cellValue, expected) => {+ expect(buildFilterFromCellValue('col', cellValue)).toEqual({+ column: 'col',+ operator: '=',+ value: expected,+ })+ })++ test.each([null, undefined])('uses the is operator for %j', (cellValue) => {+ expect(buildFilterFromCellValue('col', cellValue)).toEqual({+ column: 'col',operator: 'is',value: 'null',})})-- test('creates filter with is operator for undefined', () => {- const filter = buildFilterFromCellValue('name', undefined)- expect(filter).toEqual({- column: 'name',- operator: 'is',- value: 'null',- })- })-- test('creates filter for date strings', () => {- const filter = buildFilterFromCellValue('created_at', '2024-01-01')- expect(filter).toEqual({- column: 'created_at',- operator: '=',- value: '2024-01-01',- })- })-- test('creates filter for datetime strings', () => {- const filter = buildFilterFromCellValue('updated_at', '2024-01-01T12:00:00Z')- expect(filter).toEqual({- column: 'updated_at',- operator: '=',- value: '2024-01-01T12:00:00Z',- })- })})diff --git a/apps/studio/components/grid/hooks/useFilterLifeCycle.navigation.test.tsx b/apps/studio/components/grid/hooks/useFilterLifeCycle.navigation.test.tsxindex d2492cbac45..31309cea69e 100644--- a/apps/studio/components/grid/hooks/useFilterLifeCycle.navigation.test.tsx+++ b/apps/studio/components/grid/hooks/useFilterLifeCycle.navigation.test.tsx@@ -8,7 +8,7 @@ import {} from '@tanstack/react-router'import { act, render, screen, waitFor } from '@testing-library/react'import { flushSync } from 'react-dom'-import { describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { useInitializeFiltersFromUrl, useSyncFiltersToUrl } from './useFilterLifeCycle'import { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'@@ -94,17 +94,26 @@ async function renderTableAt(url: string) {}// Outlasts the 500ms state → URL debounce, so any sync push would have landed.-const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 700)))+const settle = () => act(() => vi.advanceTimersByTimeAsync(700))const red = { column: 'name', operator: '=' as const, value: 'Red' }const filteredByRed = `${unfiltered}&filter=name%3Aeq%3ARed`describe('useSyncFiltersToUrl', () => {+ // Fake clock (still ticking for waitFor) so the debounce can be skipped instead of waited out.+ beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+ })+ afterEach(() => {+ vi.useRealTimers()+ })+it('follows Back/Forward between entries of the same table without adding entries', async () => {const { history, cleanup } = await renderTableAt(unfiltered)try {await act(async () => snap.setFilters([{ column: 'name', operator: '=', value: 'Red' }]))+ await settle()await waitFor(() => expect(window.location.search).toContain('filter=name%3Aeq%3ARed'))const filteredIndex = getHistoryIndex()@@ -151,8 +160,8 @@ describe('useSyncFiltersToUrl', () => {try {await act(async () => snap.setFilters([red]))- await waitFor(() => expect(window.location.search).toContain('filter=name%3Aeq%3ARed'))await settle()+ await waitFor(() => expect(window.location.search).toContain('filter=name%3Aeq%3ARed'))await act(async () => sortParams.setParams((prev) => ({ ...prev, sort: ['name:asc'] })))await waitFor(() => expect(window.location.search).toContain('sort=name%3Aasc'))@@ -176,6 +185,7 @@ describe('useSyncFiltersToUrl', () => {const loadedIndex = getHistoryIndex()await act(async () => snap.setFilters([]))+ await settle()await waitFor(() => expect(window.location.search).not.toContain('filter'))expect(getHistoryIndex()).toBe(loadedIndex! + 1)diff --git a/apps/studio/components/grid/utils/queueOperationUtils.test.ts b/apps/studio/components/grid/utils/queueOperationUtils.test.tsindex 325bd18a413..660f83f5ef4 100644--- a/apps/studio/components/grid/utils/queueOperationUtils.test.ts+++ b/apps/studio/components/grid/utils/queueOperationUtils.test.ts@@ -111,47 +111,38 @@ describe('generateTableChangeKey', () => {})describe('rowMatchesIdentifiers', () => {- test('should return false for empty row identifiers', () => {- const result = rowMatchesIdentifiers({ id: 1 }, {})- expect(result).toBe(false)- })-- test('should match row with single identifier', () => {- const result = rowMatchesIdentifiers({ id: 1 }, { id: 1 })- expect(result).toBe(true)- })-- test('should match row with multiple identifiers', () => {- const result = rowMatchesIdentifiers(- { id: 1, email: '[email protected]' },- { id: 1, email: '[email protected]' }- )- expect(result).toBe(true)- })-- test('should not match row with different values', () => {- const result = rowMatchesIdentifiers({ id: 2 }, { id: 1 })- expect(result).toBe(false)- })-- test('should not match row with missing identifier keys', () => {- const result = rowMatchesIdentifiers({ id: 1 }, { id: 1, email: '[email protected]' })- expect(result).toBe(false)- })-- test('should match row with extra keys', () => {- const result = rowMatchesIdentifiers({ id: 1, name: 'John', age: 30 }, { id: 1 })- expect(result).toBe(true)- })-- test('should match with null values', () => {- const result = rowMatchesIdentifiers({ id: null }, { id: null })- expect(result).toBe(true)- })-- test('should not match with undefined values in row', () => {- const result = rowMatchesIdentifiers({ id: undefined, name: 'test' }, { id: 1 })- expect(result).toBe(false)+ test.each([+ { desc: 'single identifier', row: { id: 1 }, identifiers: { id: 1 } },+ {+ desc: 'multiple identifiers',+ row: { id: 1, email: '[email protected]' },+ identifiers: { id: 1, email: '[email protected]' },+ },+ {+ desc: 'extra keys on the row',+ row: { id: 1, name: 'John', age: 30 },+ identifiers: { id: 1 },+ },+ { desc: 'null values', row: { id: null }, identifiers: { id: null } },+ ])('matches with $desc', ({ row, identifiers }) => {+ expect(rowMatchesIdentifiers(row, identifiers)).toBe(true)+ })++ test.each([+ { desc: 'empty identifiers', row: { id: 1 }, identifiers: {} },+ { desc: 'different values', row: { id: 2 }, identifiers: { id: 1 } },+ {+ desc: 'missing identifier keys',+ row: { id: 1 },+ identifiers: { id: 1, email: '[email protected]' },+ },+ {+ desc: 'undefined values in the row',+ row: { id: undefined, name: 'test' },+ identifiers: { id: 1 },+ },+ ])('does not match with $desc', ({ row, identifiers }) => {+ expect(rowMatchesIdentifiers(row, identifiers)).toBe(false)})})diff --git a/apps/studio/components/interfaces/APIKeys/ApiKeyPill.test.tsx b/apps/studio/components/interfaces/APIKeys/ApiKeyPill.test.tsxindex d3ad7680dd1..008fd6f4289 100644--- a/apps/studio/components/interfaces/APIKeys/ApiKeyPill.test.tsx+++ b/apps/studio/components/interfaces/APIKeys/ApiKeyPill.test.tsx@@ -88,7 +88,7 @@ describe('ApiKeyPill', () => {fireEvent.click(screen.getByRole('button', { name: 'Copy API key' }))- await waitFor(() => expect(mockCopyToClipboard).toHaveBeenCalledTimes(1))+ await waitFor(() => expect(mockCopyToClipboard).toHaveBeenCalled())await expect(Promise.resolve(mockCopyToClipboard.mock.calls[0][0])).resolves.toBe(FULL)})})diff --git a/apps/studio/components/interfaces/APIKeys/CreateAPIKeyDialogs.test.tsx b/apps/studio/components/interfaces/APIKeys/CreateAPIKeyDialogs.test.tsxindex 6eb3d5b9422..bd4c3bb56ec 100644--- a/apps/studio/components/interfaces/APIKeys/CreateAPIKeyDialogs.test.tsx+++ b/apps/studio/components/interfaces/APIKeys/CreateAPIKeyDialogs.test.tsx@@ -50,7 +50,6 @@ describe('API key create dialogs', () => {expect.objectContaining({id: SHORTCUT_IDS.API_KEYS_NEW_PUBLISHABLE,onTrigger: expect.any(Function),- side: 'bottom',}),undefined)@@ -70,7 +69,6 @@ describe('API key create dialogs', () => {id: SHORTCUT_IDS.API_KEYS_CREATE_PUBLISHABLE,onTrigger: expect.any(Function),options: { enabled: true },- side: 'top',}),undefined)@@ -86,7 +84,6 @@ describe('API key create dialogs', () => {expect.objectContaining({id: SHORTCUT_IDS.API_KEYS_NEW_SECRET,onTrigger: expect.any(Function),- side: 'bottom',}),undefined)@@ -106,7 +103,6 @@ describe('API key create dialogs', () => {id: SHORTCUT_IDS.API_KEYS_CREATE_SECRET,onTrigger: expect.any(Function),options: { enabled: true },- side: 'top',}),undefined)diff --git a/apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.test.tsx b/apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.test.tsxindex 289e19dade6..221f91523ee 100644--- a/apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.test.tsx+++ b/apps/studio/components/interfaces/APIKeys/PublishableAPIKeys.test.tsx@@ -77,7 +77,7 @@ describe('PublishableAPIKeys', () => {})})- it('renders the table with publishable keys', () => {+ it('renders the table with publishable keys and the create button on platform', () => {mockUseAPIKeysQuery.mockReturnValue({data: [publishableKey],isPending: false,@@ -88,6 +88,7 @@ describe('PublishableAPIKeys', () => {render(<PublishableAPIKeys />)expect(screen.getByText('api-key-row:default-publishable')).toBeInTheDocument()+ expect(screen.getByText('CreatePublishableAPIKeyDialog')).toBeInTheDocument()expect(screen.queryByText('No publishable API keys found')).not.toBeInTheDocument()})@@ -145,17 +146,4 @@ describe('PublishableAPIKeys', () => {expect(screen.queryByText('CreatePublishableAPIKeyDialog')).not.toBeInTheDocument()})-- it('shows the create button on platform', () => {- mockUseAPIKeysQuery.mockReturnValue({- data: [publishableKey],- isPending: false,- isSuccess: true,- isError: false,- })-- render(<PublishableAPIKeys />)-- expect(screen.getByText('CreatePublishableAPIKeyDialog')).toBeInTheDocument()- })})diff --git a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.presets.test.ts b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.presets.test.tsindex c54138e3c0e..d09c0a5d5f3 100644--- a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.presets.test.ts+++ b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.presets.test.ts@@ -23,7 +23,8 @@ describe('PERMISSION_PRESETS', () => {expect(PERMISSION_PRESETS.map((preset) => preset.id)).toEqual(['none', 'read', 'full'])})- test('resolves every catalog entry to a mode its row can render', () => {+ test('resolves every catalog entry to a mode its row can render, capping full access at read for read-only resources', () => {+ expect(PERMISSION_CATALOG.some((entry) => !entry.writable)).toBe(true)for (const entry of PERMISSION_CATALOG) {expect(NONE.resolve(entry)).toBe('none')expect(READ.resolve(entry)).toBe('read')@@ -31,14 +32,6 @@ describe('PERMISSION_PRESETS', () => {}})- test('caps full access at read for resources with no write scopes', () => {- const readOnlyEntries = PERMISSION_CATALOG.filter((entry) => !entry.writable)- expect(readOnlyEntries.length).toBeGreaterThan(0)- for (const entry of readOnlyEntries) {- expect(FULL.resolve(entry)).toBe('read')- }- })-test('only marks full access as risky, and only it carries a description', () => {expect(PERMISSION_PRESETS.filter((preset) => preset.isRisky).map((preset) => preset.id)diff --git a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.utils.test.ts b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.utils.test.tsindex c33b5eac4c4..4178ab63d81 100644--- a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.utils.test.ts+++ b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.utils.test.ts@@ -311,16 +311,12 @@ describe('formatAccessText', () => {expect(formatAccessText('no access')).toBe('No access')})- it('should capitalize a single word', () => {- expect(formatAccessText('read')).toBe('Read')- })-- it('should capitalize each hyphen-separated word', () => {- expect(formatAccessText('read-write')).toBe('Read-Write')- })-- it('should handle multi-segment actions', () => {- expect(formatAccessText('read-write-delete')).toBe('Read-Write-Delete')+ it.each([+ ['read', 'Read'],+ ['read-write', 'Read-Write'],+ ['read-write-delete', 'Read-Write-Delete'],+ ])('capitalizes each hyphen-separated word of %s', (access, expected) => {+ expect(formatAccessText(access)).toBe(expected)})})@@ -338,33 +334,16 @@ describe('getExpirationDate', () => {vi.useRealTimers()})- it('should return a date exactly 1 hour from now for "hour"', () => {- const result = getExpirationDate('hour')!- expect(result).toBe(dayjs(FIXED_DATE).add(1, 'hours').toISOString())- })-- it('should return a date exactly 1 day from now for "day"', () => {- const result = getExpirationDate('day')!- expect(result).toBe(dayjs(FIXED_DATE).add(1, 'day').toISOString())- })-- it('should return a date exactly 7 days from now for "week"', () => {- const result = getExpirationDate('week')!- expect(result).toBe(dayjs(FIXED_DATE).add(7, 'days').toISOString())- })-- it('should return a date exactly 30 days from now for "month"', () => {- const result = getExpirationDate('month')!- expect(result).toBe(dayjs(FIXED_DATE).add(30, 'days').toISOString())+ it.each([+ ['hour', 1, 'hours'],+ ['day', 1, 'day'],+ ['week', 7, 'days'],+ ['month', 30, 'days'],+ ] as const)('returns the ISO date %s from now', (key, amount, unit) => {+ expect(getExpirationDate(key)).toBe(dayjs(FIXED_DATE).add(amount, unit).toISOString())})it('should return undefined for an unknown key', () => {expect(getExpirationDate('unknown')).toBeUndefined()})-- it('should return a valid ISO string', () => {- const result = getExpirationDate('hour')!- expect(dayjs(result).isValid()).toBe(true)- expect(result).toMatch(/^\d{4}-\d{2}-\d{2}T/)- })})diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.test.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.test.tsxindex 7ff6764d73a..c340adee564 100644--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.test.tsx+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, screen } from '@testing-library/react'+import { fireEvent, screen, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { platformComponents as components } from 'api-types'import { HttpResponse } from 'msw'@@ -35,6 +35,12 @@ vi.mock('@/lib/constants', async (importOriginal) => {const user = userEvent.setup()+/**+ * Each permission row renders a hidden native <select>, so an unscoped option query has to+ * check the visibility of hundreds of options. Scope it to the open listbox.+ */+const getListbox = async () => within(await screen.findByRole('listbox'))+describe('ResourceAccessStep organization selector', () => {beforeEach(() => {mockScopedTokenEnvironment()@@ -54,7 +60,11 @@ describe('ResourceAccessStep organization selector', () => {mockPermissionsApi(readonlyRows(MOCK_ORG.slug, [MOCK_PROJECT.ref]))await openOrganizationSelector()- const option = await screen.findByRole('option', { name: new RegExp(MOCK_ORG.name) })+ const option = await (+ await getListbox()+ ).findByRole('option', {+ name: new RegExp(MOCK_ORG.name),+ })expect(option).toHaveAttribute('aria-disabled', 'true')expect(await screen.findByText(@@ -67,7 +77,11 @@ describe('ResourceAccessStep organization selector', () => {mockPermissionsApi(readonlyRows(MOCK_ORG.slug))await openOrganizationSelector()- const option = await screen.findByRole('option', { name: new RegExp(MOCK_ORG.name) })+ const option = await (+ await getListbox()+ ).findByRole('option', {+ name: new RegExp(MOCK_ORG.name),+ })expect(option).not.toHaveAttribute('aria-disabled', 'true')expect(screen.queryByText(@@ -92,19 +106,10 @@ describe('ResourceAccessStep project selector', () => {const selectOrganization = async (name: string) => {fireEvent.click(await screen.findByRole('combobox', { name: 'Organization' }))- fireEvent.click(await screen.findByRole('option', { name }))+ fireEvent.click(await (await getListbox()).findByRole('option', { name }))}- test('loads projects scoped to the selected organization', async () => {- mockPermissionsApi(readonlyRows(MOCK_ORG.slug))- await openTokenForm()- await selectOrganization(MOCK_ORG.name)-- fireEvent.click(await screen.findByRole('combobox', { name: 'Projects' }))- expect(await screen.findByRole('option', { name: MOCK_PROJECT.name })).toBeInTheDocument()- })-- // Regression test: the project list used to be fetched cross-org (a single page of the user's+ // Also covers loading projects for the selected organization. Regression test: the project list used to be fetched cross-org (a single page of the user's// first 100 projects, filtered client-side by org), so switching to an org whose projects// didn't fall in that page left the selector permanently empty.test('refreshes the project list when switching organizations', async () => {@@ -122,11 +127,14 @@ describe('ResourceAccessStep project selector', () => {await openTokenForm()await selectOrganization(MOCK_ORG.name)fireEvent.click(await screen.findByRole('combobox', { name: 'Projects' }))- expect(await screen.findByRole('option', { name: MOCK_PROJECT.name })).toBeInTheDocument()+ expect(+ await (await getListbox()).findByRole('option', { name: MOCK_PROJECT.name })+ ).toBeInTheDocument()await selectOrganization(MOCK_ORG_2.name)fireEvent.click(await screen.findByRole('combobox', { name: 'Projects' }))- expect(await screen.findByRole('option', { name: MOCK_PROJECT_2.name })).toBeInTheDocument()- expect(screen.queryByRole('option', { name: MOCK_PROJECT.name })).toBeNull()- }, 30000)+ const projects = await getListbox()+ expect(await projects.findByRole('option', { name: MOCK_PROJECT_2.name })).toBeInTheDocument()+ expect(projects.queryByRole('option', { name: MOCK_PROJECT.name })).toBeNull()+ })})diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.test.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.test.tsxindex 5bb532e7add..ff881a76b72 100644--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.test.tsx+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, screen, waitFor } from '@testing-library/react'+import { fireEvent, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { platformComponents as components } from 'api-types'import { HttpResponse } from 'msw'@@ -15,6 +15,7 @@ type ProjectsResponse = components['schemas']['ListProjectsPaginatedResponse_Outtype OrganizationProjectsResponse = components['schemas']['OrganizationProjectsResponse_Output']type CreateTokenResponse = components['schemas']['CreateScopedAccessTokenResponse_Output']type CreateClassicTokenResponse = components['schemas']['CreateAccessTokenResponse_Output']+type ProjectDetailResponse = components['schemas']['ProjectDetailResponse_Output']const mockUseReducedMotion = vi.fn(() => false)vi.mock('common', async (importOriginal) => {@@ -109,6 +110,27 @@ const mockOrgProjects = () =>}),})+// The review screen's project pill looks up the selected project+const mockProjectDetail = () =>+ addAPIMock({+ method: 'get',+ path: '/platform/projects/:ref',+ response: () =>+ HttpResponse.json<ProjectDetailResponse>({+ ...createMockProject({ id: 1, ref: 'project-1', name: 'Project 1', organization_id: 1 }),+ connectionString: null,+ db_host: 'db.project-1.supabase.co',+ high_availability: false,+ integration_source: null,+ inserted_at: '2026-01-01T00:00:00Z',+ is_physical_backups_enabled: false,+ restUrl: 'https://project-1.supabase.co',+ status: 'ACTIVE_HEALTHY',+ subscription_id: 'subscription-1',+ updated_at: '2026-01-01T00:00:00Z',+ }),+ })+const mockPermissionsMap = () =>addAPIMock({method: 'get',@@ -162,6 +184,13 @@ const mockCreateClassicToken = () =>const expandPermissionCategory = async (name: string) =>fireEvent.click(await screen.findByRole('button', { name: new RegExp(`^${name}`) }))+/**+ * Each permission row renders a hidden native <select>, so an unscoped option query has to+ * check the visibility of hundreds of options (~300ms per query). Scope it to the open listbox.+ */+const findOption = async (name: string | RegExp) =>+ within(await screen.findByRole('listbox')).findByRole('option', { name })+describe('NewScopedTokenSheet', () => {const renderSheet = () =>customRender(<NewScopedTokenSheet onCreateExperimentalToken={() => {}} />, {@@ -174,71 +203,107 @@ describe('NewScopedTokenSheet', () => {mockOrganizations()mockProjects()mockOrgProjects()+ mockProjectDetail()mockCreateToken()mockCreateClassicToken()})- test('requires a token name', async () => {+ const openSheet = async () => {renderSheet()fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))await screen.findByRole('dialog')+ }++ // Typing character-by-character isn't the behaviour under test, and every keystroke+ // re-renders the whole (large) form+ const enterName = async (name = 'test') =>+ fireEvent.change(await screen.findByLabelText('Name'), { target: { value: name } })++ const clickReview = async () =>fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))- expect(await screen.findByText('Please enter a name for the token'))- })++ const selectOption = async (combobox: string, option: string) => {+ fireEvent.click(await screen.findByRole('combobox', { name: combobox }))+ fireEvent.click(await findOption(option))+ }++ const grantProjectSettingsRead = async () => {+ await expandPermissionCategory('Project')+ fireEvent.click(await screen.findByLabelText('Project Settings', { exact: false }))+ fireEvent.click(await findOption('Read'))+ }++ const fillProjectScopedForm = async () => {+ await enterName()+ await selectOption('Organization', 'Acme Production')+ await selectOption('Projects', 'Project 1')+ await grantProjectSettingsRead()+ }++ const selectOrganizationScope = async () =>+ user.click(await screen.findByRole('radio', { name: /Organization/ }))++ const findMissingPermissionsWarning = () =>+ screen.findByText('No permissions selected', { selector: '[role="alert"] *' })+// Project scope tests- test('requires an organization when scope is Project', async () => {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.type(await screen.findByLabelText('Name'), 'test')- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ test('validates the Project scope fields in order', async () => {+ await openSheet()+ await clickReview()+ expect(await screen.findByText('Please enter a name for the token'))++ await enterName()+ await clickReview()expect(await screen.findByText('Please select an organization to continue.'))- })- test('requires a project when scope is Project', async () => {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.type(await screen.findByLabelText('Name'), 'test')- fireEvent.click(await screen.findByRole('combobox', { name: 'Organization' }))- fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))++ await selectOption('Organization', 'Acme Production')+ await clickReview()expect(await screen.findByText('Please select a project to continue.'))++ await selectOption('Projects', 'Project 1')+ await clickReview()+ expect(await findMissingPermissionsWarning())})- test('requires permissions when scope is Project', async () => {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.type(await screen.findByLabelText('Name'), 'test')- fireEvent.click(await screen.findByRole('combobox', { name: 'Organization' }))- fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))- fireEvent.click(await screen.findByRole('combobox', { name: 'Projects' }))- fireEvent.click(await screen.findByRole('option', { name: 'Project 1' }))- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))- expect(await screen.findByText('No permissions selected', { selector: '[role="alert"] *' }))- })- test('creates the token when scope is Project', async () => {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.type(await screen.findByLabelText('Name'), 'test')- fireEvent.click(await screen.findByRole('combobox', { name: 'Organization' }))- fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))- fireEvent.click(await screen.findByRole('combobox', { name: 'Projects' }))- fireEvent.click(await screen.findByRole('option', { name: 'Project 1' }))- await expandPermissionCategory('Project')- fireEvent.click(await screen.findByLabelText('Project Settings', { exact: false }))- fireEvent.click(await screen.findByRole('option', { name: 'Read' }))- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))++ test('creates the token when scope is Project, without an expiry for the Never preset', async () => {+ let createBody: Record<string, unknown> | undefined+ addAPIMock({+ method: 'post',+ path: '/platform/profile/scoped-access-tokens',+ response: async ({ request }) => {+ createBody = (await request.json()) as Record<string, unknown>+ return HttpResponse.json<CreateTokenResponse>({+ created_at: '',+ expires_at: null,+ id: 'plop',+ last_used_at: null,+ name: 'test',+ token: 'a_token_value',+ token_alias: '',+ permissions: [],+ })+ },+ })+ await openSheet()+ await selectOption('Expires in', 'Never')+ await fillProjectScopedForm()+ await clickReview()// Review screen — Project Settings is a high-risk entry, downgraded one tier for read-onlyawait screen.findByText('Medium risk')await screen.findByText('Read on 1 capability, across 1 project.')+ await screen.findByText('Never')fireEvent.click(await screen.findByRole('button', { name: 'Create token' }))- // If we can click this checkbox, the token was created// Must be a real click, which focuses the button: nothing holds focus once the form// unmounts, and copyToClipboard bails out when the document has no focusawait user.click(await screen.findByRole('button', { name: 'Copy' }))await waitFor(async () =>expect(await window.navigator.clipboard.readText()).toEqual('a_token_value'))+ expect(createBody).toBeDefined()+ expect(createBody?.expires_at).toBeUndefined()+ expect(mockTrack).toHaveBeenCalledWith(+ 'access_token_created',+ expect.objectContaining({ expiryPreset: 'never' })+ )expect(mockTrack).toHaveBeenCalledWith('access_token_copied', { tokenType: 'scoped' })fireEvent.click(await screen.findByLabelText('I have copied the key and stored it securely'))expect(mockTrack).toHaveBeenCalledWith('access_token_stored_checkbox_clicked', {@@ -250,63 +315,17 @@ describe('NewScopedTokenSheet', () => {tokenType: 'scoped',hasCopiedToken: true,})- // Dialog has been closedawait waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())// Completing the flow via Done must not also emit a dismissed eventexpect(mockTrack).not.toHaveBeenCalledWith('access_token_creation_sheet_dismissed',expect.anything())- }, 10_000)-- test('creates a token without an expiry when the Never preset is selected', async () => {- let createBody: Record<string, unknown> | undefined- addAPIMock({- method: 'post',- path: '/platform/profile/scoped-access-tokens',- response: async ({ request }) => {- createBody = (await request.json()) as Record<string, unknown>- return HttpResponse.json<CreateTokenResponse>({- created_at: '',- expires_at: null,- id: 'plop',- last_used_at: null,- name: 'test',- token: 'a_token_value',- token_alias: '',- permissions: [],- })- },- })- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.type(await screen.findByLabelText('Name'), 'test')- fireEvent.click(await screen.findByRole('combobox', { name: 'Expires in' }))- fireEvent.click(await screen.findByRole('option', { name: 'Never' }))- fireEvent.click(await screen.findByRole('combobox', { name: 'Organization' }))- fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))- fireEvent.click(await screen.findByRole('combobox', { name: 'Projects' }))- fireEvent.click(await screen.findByRole('option', { name: 'Project 1' }))- await expandPermissionCategory('Project')- fireEvent.click(await screen.findByLabelText('Project Settings', { exact: false }))- fireEvent.click(await screen.findByRole('option', { name: 'Read' }))- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))- await screen.findByText('Never')- fireEvent.click(await screen.findByRole('button', { name: 'Create token' }))- await waitFor(() => expect(createBody).toBeDefined())- expect(createBody?.expires_at).toBeUndefined()- expect(mockTrack).toHaveBeenCalledWith(- 'access_token_created',- expect.objectContaining({ expiryPreset: 'never' })- )- }, 10_000)+ })test('tracks dismissal with the in-progress resourceAccess and touched state on Cancel', async () => {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.click(await screen.findByRole('radio', { name: /Organization/ }))+ await openSheet()+ await selectOrganizationScope()fireEvent.click(await screen.findByRole('button', { name: 'Cancel' }))expect(mockTrack).toHaveBeenCalledWith('access_token_creation_sheet_dismissed', {resourceAccess: 'organization',@@ -318,10 +337,8 @@ describe('NewScopedTokenSheet', () => {})test('tracks dismissal with the untouched default resourceAccess on Escape', async () => {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- const dialog = await screen.findByRole('dialog')- fireEvent.keyDown(dialog, { key: 'Escape', code: 'Escape' })+ await openSheet()+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape', code: 'Escape' })expect(mockTrack).toHaveBeenCalledWith('access_token_creation_sheet_dismissed', {resourceAccess: 'project',formStep: 'form',@@ -332,18 +349,9 @@ describe('NewScopedTokenSheet', () => {})test('tracks the review step when the sheet is dismissed from the review screen', async () => {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.type(await screen.findByLabelText('Name'), 'test')- fireEvent.click(await screen.findByRole('combobox', { name: 'Organization' }))- fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))- fireEvent.click(await screen.findByRole('combobox', { name: 'Projects' }))- fireEvent.click(await screen.findByRole('option', { name: 'Project 1' }))- await expandPermissionCategory('Project')- fireEvent.click(await screen.findByLabelText('Project Settings', { exact: false }))- fireEvent.click(await screen.findByRole('option', { name: 'Read' }))- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ await openSheet()+ await fillProjectScopedForm()+ await clickReview()await screen.findByText('Medium risk')fireEvent.click(await screen.findByRole('button', { name: 'Cancel' }))expect(mockTrack).toHaveBeenCalledWith('access_token_creation_sheet_dismissed', {@@ -353,7 +361,7 @@ describe('NewScopedTokenSheet', () => {trigger: 'user',})await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())- }, 10_000)+ })test('tracks a permissions load error as the dismissal trigger and closes the sheet', async () => {addAPIMock({@@ -380,63 +388,42 @@ describe('NewScopedTokenSheet', () => {})// Organization scope tests- test('requires an organization when scope is Organization', async () => {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.type(await screen.findByLabelText('Name'), 'test')- await user.click(await screen.findByRole('radio', { name: /Organization/ }))- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))- expect(await screen.findByText('Please select an organization to continue.'))- })- test('requires permissions when scope is Organization', async () => {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.type(await screen.findByLabelText('Name'), 'test')- await user.click(await screen.findByRole('radio', { name: /Organization/ }))- fireEvent.click(await screen.findByRole('combobox', { name: 'Organizations' }))- fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))- expect(await screen.findByText('No permissions selected', { selector: '[role="alert"] *' }))- })- test('scrolls the missing permissions warning into view once per attempt', async () => {+ test('validates the Organization scope and scrolls the missing permissions warning once per attempt', async () => {const scrollIntoView = vi.spyOn(window.HTMLElement.prototype, 'scrollIntoView')- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.type(await screen.findByLabelText('Name'), 'test')- await user.click(await screen.findByRole('radio', { name: /Organization/ }))- fireEvent.click(await screen.findByRole('combobox', { name: 'Organizations' }))- fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))- scrollIntoView.mockClear()-- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))- await screen.findByText('No permissions selected', { selector: '[role="alert"] *' })- await waitFor(() => expect(scrollIntoView).toHaveBeenCalledTimes(1))- expect(scrollIntoView).toHaveBeenLastCalledWith({ behavior: 'smooth', block: 'nearest' })+ try {+ await openSheet()+ await enterName()+ await selectOrganizationScope()+ await clickReview()+ expect(await screen.findByText('Please select an organization to continue.'))++ await selectOption('Organizations', 'Acme Production')+ scrollIntoView.mockClear()+ await clickReview()+ await findMissingPermissionsWarning()+ await waitFor(() => expect(scrollIntoView).toHaveBeenCalledTimes(1))+ expect(scrollIntoView).toHaveBeenLastCalledWith({ behavior: 'smooth', block: 'nearest' })- // Re-rendering the form while the warning is up must not scroll again- await expandPermissionCategory('Database')- expect(scrollIntoView).toHaveBeenCalledTimes(1)+ // Re-rendering the form while the warning is up must not scroll again+ await expandPermissionCategory('Database')+ expect(scrollIntoView).toHaveBeenCalledTimes(1)- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))- await waitFor(() => expect(scrollIntoView).toHaveBeenCalledTimes(2))- scrollIntoView.mockRestore()+ await clickReview()+ await waitFor(() => expect(scrollIntoView).toHaveBeenCalledTimes(2))+ } finally {+ scrollIntoView.mockRestore()+ }})test('does not re-scroll when the motion preference changes while the warning is visible', async () => {const scrollIntoView = vi.spyOn(window.HTMLElement.prototype, 'scrollIntoView')try {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.type(await screen.findByLabelText('Name'), 'test')- await user.click(await screen.findByRole('radio', { name: /Organization/ }))- fireEvent.click(await screen.findByRole('combobox', { name: 'Organizations' }))- fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))-- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))- await screen.findByText('No permissions selected', { selector: '[role="alert"] *' })+ await openSheet()+ await enterName()+ await selectOrganizationScope()+ await selectOption('Organizations', 'Acme Production')++ await clickReview()+ await findMissingPermissionsWarning()await waitFor(() => expect(scrollIntoView).toHaveBeenCalledTimes(1))mockUseReducedMotion.mockReturnValue(true)@@ -445,8 +432,8 @@ describe('NewScopedTokenSheet', () => {// warning stays up — this is what would surface a stale effect dependency on the// motion preference.await user.click(await screen.findByRole('radio', { name: /Project/ }))- await user.click(await screen.findByRole('radio', { name: /Organization/ }))- await screen.findByText('No permissions selected', { selector: '[role="alert"] *' })+ await selectOrganizationScope()+ await findMissingPermissionsWarning()expect(scrollIntoView).toHaveBeenCalledTimes(1)} finally {mockUseReducedMotion.mockReturnValue(false)@@ -454,33 +441,20 @@ describe('NewScopedTokenSheet', () => {}})test('creates the token when scope is Organization', async () => {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.type(await screen.findByLabelText('Name'), 'test')- await user.click(await screen.findByRole('radio', { name: /Organization/ }))- fireEvent.click(await screen.findByRole('combobox', { name: 'Organizations' }))- fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))- await expandPermissionCategory('Project')- fireEvent.click(await screen.findByLabelText('Project Settings', { exact: false }))- fireEvent.click(await screen.findByRole('option', { name: 'Read' }))- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))- // Review screen — Project Settings is a high-risk entry, downgraded one tier for read-only+ await openSheet()+ await enterName()+ await selectOrganizationScope()+ await selectOption('Organizations', 'Acme Production')+ await grantProjectSettingsRead()+ await clickReview()await screen.findByText('Medium risk')await screen.findByText('Read on 1 capability, across 1 organization.')fireEvent.click(await screen.findByRole('button', { name: 'Create token' }))- // If we can click this checkbox, the token was created- // Must be a real click, which focuses the button: nothing holds focus once the form- // unmounts, and copyToClipboard bails out when the document has no focusawait user.click(await screen.findByRole('button', { name: 'Copy' }))await waitFor(async () =>expect(await window.navigator.clipboard.readText()).toEqual('a_token_value'))- fireEvent.click(await screen.findByLabelText('I have copied the key and stored it securely'))- fireEvent.click(await screen.findByRole('button', { name: 'Done' }))- // Dialog has been closed- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())- }, 10_000)+ })// Permission preset testsconst FULL_ACCESS_WARNING =@@ -489,15 +463,13 @@ describe('NewScopedTokenSheet', () => {const getPresetTrigger = async () => screen.findByRole('combobox', { name: 'Permission preset' })const openPresetMenu = async () => {- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')+ await openSheet()fireEvent.click(await getPresetTrigger())}test('applies a preset to every permission row', async () => {- renderSheet()await openPresetMenu()- fireEvent.click(await screen.findByRole('option', { name: 'Read-only' }))+ fireEvent.click(await findOption('Read-only'))expect((await getPresetTrigger()).textContent).toContain('Read-only')// The bulk change is announced rather than left to the user to notice@@ -508,11 +480,10 @@ describe('NewScopedTokenSheet', () => {expect(select.textContent).toBe('Read')})- test('warns about full access in the menu and inline once applied', async () => {- renderSheet()+ test('warns about full access, and falls back to Custom when a row diverges from the preset', async () => {await openPresetMenu()- const fullAccess = await screen.findByRole('option', { name: /^Full access/ })+ const fullAccess = await findOption(/^Full access/)const describedBy = fullAccess.getAttribute('aria-describedby')expect(describedBy).not.toBeNull()expect(document.getElementById(describedBy!)?.textContent).toBe(FULL_ACCESS_WARNING)@@ -521,17 +492,10 @@ describe('NewScopedTokenSheet', () => {// The warning survives the menu closingawait screen.findByText(FULL_ACCESS_WARNING, { selector: '[role="alert"] *' })expect((await getPresetTrigger()).textContent).toContain('Full access')- })-- test('falls back to Custom when a row diverges from the preset', async () => {- renderSheet()- await openPresetMenu()- fireEvent.click(await screen.findByRole('option', { name: /^Full access/ }))- await screen.findByText(FULL_ACCESS_WARNING, { selector: '[role="alert"] *' })await expandPermissionCategory('Project')fireEvent.click(await screen.findByLabelText('Project Settings', { exact: false }))- fireEvent.click(await screen.findByRole('option', { name: 'None' }))+ fireEvent.click(await findOption('None'))await waitFor(async () => expect((await getPresetTrigger()).textContent).toContain('Custom'))expect(screen.queryByText(FULL_ACCESS_WARNING, { selector: '[role="alert"] *' })).toBeNull()@@ -551,12 +515,10 @@ describe('NewScopedTokenSheet', () => {// Classic (account-wide) token teststest('switches to the classic token form via the legacy link', async () => {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')+ await openSheet()// Trigger a resource validation error before entering legacy mode- await user.type(await screen.findByLabelText('Name'), 'test')- fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ await enterName()+ await clickReview()await screen.findByText('Please select an organization to continue.')await user.click(await screen.findByText('Create legacy token'))// The classic warning replaces resource access and permissions@@ -570,10 +532,8 @@ describe('NewScopedTokenSheet', () => {expect(screen.queryByText('Please select an organization to continue.')).toBeNull()})test('creates a classic token via the legacy link', async () => {- renderSheet()- fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))- await screen.findByRole('dialog')- await user.type(await screen.findByLabelText('Name'), 'test')+ await openSheet()+ await enterName()await user.click(await screen.findByText('Create legacy token'))fireEvent.click(await screen.findByRole('button', { name: 'Generate token' }))// If we can click this button, the token was createddiff --git a/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.test.tsx b/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.test.tsxindex f2eabc73323..25806959bf6 100644--- a/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.test.tsx+++ b/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.test.tsx@@ -1,5 +1,4 @@import { fireEvent, screen, waitFor, within } from '@testing-library/react'-import userEvent from '@testing-library/user-event'import { mockAnimationsApi } from 'jsdom-testing-mocks'import { http, HttpResponse } from 'msw'import { beforeEach, describe, expect, it, vi } from 'vitest'@@ -167,7 +166,9 @@ describe('AccountIdentities', () => {expect(emailInput).toBeDisabled()expect(emailInput).toHaveValue(EMAIL)- await userEvent.type(within(dialog).getByPlaceholderText('••••••••'), VALID_PASSWORD)+ fireEvent.change(within(dialog).getByPlaceholderText('••••••••'), {+ target: { value: VALID_PASSWORD },+ })fireEvent.click(within(dialog).getByRole('button', { name: 'Add password' }))await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())@@ -188,7 +189,9 @@ describe('AccountIdentities', () => {renderAccountIdentities()const dialog = await openAddPasswordDialog()- await userEvent.type(within(dialog).getByPlaceholderText('••••••••'), VALID_PASSWORD)+ fireEvent.change(within(dialog).getByPlaceholderText('••••••••'), {+ target: { value: VALID_PASSWORD },+ })fireEvent.click(within(dialog).getByRole('button', { name: 'Add password' }))await waitFor(() => expect(updateUserMock).toHaveBeenCalledWith({ password: VALID_PASSWORD }))@@ -202,7 +205,7 @@ describe('AccountIdentities', () => {renderAccountIdentities()const dialog = await openAddPasswordDialog()- await userEvent.type(within(dialog).getByPlaceholderText('••••••••'), 'weak')+ fireEvent.change(within(dialog).getByPlaceholderText('••••••••'), { target: { value: 'weak' } })fireEvent.click(within(dialog).getByRole('button', { name: 'Add password' }))expect(diff --git a/apps/studio/components/interfaces/Account/TOTPFactors/RegenerateRecoveryCodesModal.test.tsx b/apps/studio/components/interfaces/Account/TOTPFactors/RegenerateRecoveryCodesModal.test.tsxindex 2ba4b3098b8..6262fa8e4dd 100644--- a/apps/studio/components/interfaces/Account/TOTPFactors/RegenerateRecoveryCodesModal.test.tsx+++ b/apps/studio/components/interfaces/Account/TOTPFactors/RegenerateRecoveryCodesModal.test.tsx@@ -1,6 +1,5 @@import { AuthError } from '@supabase/auth-js'import { fireEvent, screen, waitFor, within } from '@testing-library/react'-import userEvent from '@testing-library/user-event'import { describe, expect, test, vi } from 'vitest'import { formatRecoveryCode } from './RecoveryCodesModal.utils'@@ -31,6 +30,14 @@ const codes = ['kyyfsp3eqjydj53t',]+const confirmRegenerate = async () => {+ const dialog = within(await screen.findByRole('dialog'))+ fireEvent.change(await dialog.findByRole('textbox', { name: /Type REGENERATE to confirm./ }), {+ target: { value: 'REGENERATE' },+ })+ fireEvent.click(await dialog.findByRole('button', { name: 'Regenerate' }))+}+describe('RegenerateRecoveryCodesModal', () => {test('regenerate the recovery codes after confirmation and allow users to copy them', async () => {vi.spyOn(auth.mfa.recoveryCodes, 'regenerate').mockResolvedValue({@@ -46,15 +53,7 @@ describe('RegenerateRecoveryCodesModal', () => {fireEvent.click(await screen.findByRole('button', { name: 'Regenerate' }))// Confirm regeneration- await userEvent.type(- await within(await screen.findByRole('dialog')).findByRole('textbox', {- name: /Type REGENERATE to confirm./,- }),- 'REGENERATE'- )- fireEvent.click(- await within(await screen.findByRole('dialog')).findByRole('button', { name: 'Regenerate' })- )+ await confirmRegenerate()// Codes are generatedawait screen.findByText('Save your recovery codes')@@ -99,15 +98,7 @@ describe('RegenerateRecoveryCodesModal', () => {fireEvent.click(await screen.findByRole('button', { name: 'Regenerate' }))// Confirm regeneration- await userEvent.type(- await within(await screen.findByRole('dialog')).findByRole('textbox', {- name: /Type REGENERATE to confirm./,- }),- 'REGENERATE'- )- fireEvent.click(- await within(await screen.findByRole('dialog')).findByRole('button', { name: 'Regenerate' })- )+ await confirmRegenerate()await screen.findByText('Unable to generate recovery codes')expect(await screen.findByText(/Try refreshing your browser/)).toHaveTextContent('Try refreshing your browser, but if the issue persists for more than a few minutes, contact support.'@@ -119,15 +110,7 @@ describe('RegenerateRecoveryCodesModal', () => {// RetryfireEvent.click(await screen.findByRole('button', { name: 'Regenerate' }))// Confirm regeneration- await userEvent.type(- await within(await screen.findByRole('dialog')).findByRole('textbox', {- name: /Type REGENERATE to confirm./,- }),- 'REGENERATE'- )- fireEvent.click(- await within(await screen.findByRole('dialog')).findByRole('button', { name: 'Regenerate' })- )+ await confirmRegenerate()// Codes are generatedawait screen.findByText('Save your recovery codes')await screen.findByText('WTO2-4T5X-BEUL-VJMI')diff --git a/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.test.tsx b/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.test.tsxindex 86f35351d94..890b771ee30 100644--- a/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.test.tsx+++ b/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.test.tsx@@ -153,34 +153,23 @@ describe('TemplateEditor reset to default', () => {expect(screen.queryByRole('button', { name: 'Reset template' })).not.toBeInTheDocument()})- it('shows reset when the API marks the body as custom', () => {- renderTemplateEditor({ hasCustomBody: true })-- expect(screen.getByRole('button', { name: 'Reset template' })).toBeInTheDocument()- })-- it('shows reset when the API marks the subject as custom', () => {- renderTemplateEditor({ hasCustomSubject: true })+ it.each([+ { field: 'body', options: { hasCustomBody: true } },+ { field: 'subject', options: { hasCustomSubject: true } },+ ])('shows reset when the API marks the $field as custom', ({ options }) => {+ renderTemplateEditor(options)expect(screen.getByRole('button', { name: 'Reset template' })).toBeInTheDocument()})- it('keeps reset visible while there are unsaved editor changes', async () => {+ it('keeps reset visible with unsaved editor changes, and warns that reset discards them', async () => {const user = userEvent.setup()renderTemplateEditor({ hasCustomBody: true })await user.clear(screen.getByLabelText('Body source'))- await user.type(screen.getByLabelText('Body source'), '<p>Unsaved body</p>')+ await user.paste('<p>Unsaved body</p>')expect(screen.getByRole('button', { name: 'Reset template' })).toBeInTheDocument()- })-- it('warns that reset discards unsaved changes', async () => {- const user = userEvent.setup()- renderTemplateEditor({ hasCustomBody: true })-- await user.clear(screen.getByLabelText('Body source'))- await user.type(screen.getByLabelText('Body source'), '<p>Unsaved body</p>')await user.click(screen.getByRole('button', { name: 'Reset template' }))expect(@@ -190,13 +179,17 @@ describe('TemplateEditor reset to default', () => {).toBeInTheDocument()})- it('resets the template through the dedicated reset endpoint after confirmation', async () => {+ it('resets through the dedicated reset endpoint and uses its response as the new editor state', async () => {const user = userEvent.setup()resetTemplateMock.mockImplementation((_vars, callbacks) =>callbacks?.onSuccess?.(resetAuthConfig))- renderTemplateEditor({ hasCustomBody: true })+ renderTemplateEditor({+ body: '<p>Custom body</p>',+ hasCustomBody: true,+ hasCustomSubject: true,+ })await user.click(screen.getByRole('button', { name: 'Reset template' }))const dialog = await screen.findByRole('alertdialog')@@ -208,42 +201,9 @@ describe('TemplateEditor reset to default', () => {expect.any(Object)))-expect(toast.success).toHaveBeenCalledWith('Email template reset to default')- })-- it('does not reset through the auth config update payload', async () => {- const user = userEvent.setup()- resetTemplateMock.mockImplementation((_vars, callbacks) =>- callbacks?.onSuccess?.(resetAuthConfig)- )-- renderTemplateEditor({ hasCustomBody: true })-- await user.click(screen.getByRole('button', { name: 'Reset template' }))- const dialog = await screen.findByRole('alertdialog')- await user.click(within(dialog).getByRole('button', { name: 'Reset' }))-- await waitFor(() => expect(resetTemplateMock).toHaveBeenCalled())-+ // Reset must not go through the auth config update payloadexpect(updateAuthConfigMock).not.toHaveBeenCalled()- })-- it('uses the reset response as the new editor state', async () => {- const user = userEvent.setup()- resetTemplateMock.mockImplementation((_vars, callbacks) =>- callbacks?.onSuccess?.(resetAuthConfig)- )-- renderTemplateEditor({- body: '<p>Custom body</p>',- hasCustomBody: true,- hasCustomSubject: true,- })-- await user.click(screen.getByRole('button', { name: 'Reset template' }))- const dialog = await screen.findByRole('alertdialog')- await user.click(within(dialog).getByRole('button', { name: 'Reset' }))await waitFor(() => {expect(screen.getByDisplayValue('Confirm your email address')).toBeInTheDocument()diff --git a/apps/studio/components/interfaces/Auth/Overview/OverviewMetrics.test.tsx b/apps/studio/components/interfaces/Auth/Overview/OverviewMetrics.test.tsxindex 855ab725727..eec172872b8 100644--- a/apps/studio/components/interfaces/Auth/Overview/OverviewMetrics.test.tsx+++ b/apps/studio/components/interfaces/Auth/Overview/OverviewMetrics.test.tsx@@ -109,38 +109,39 @@ describe('Auth overview logs requests', () => {}})- describe.each(logQueries)('failures with useOtel=$useOtel', (query) => {- it.each(['http', 'string', 'object'] as const)(- 'shows %s errors instead of empty log tables',- async (failure) => {- flags.otelLegacyLogs = query.useOtel- addAPIMock({- method: 'get',- path: query.endpoint,- response: () => {- if (failure === 'http') {- return HttpResponse.json<APIErrorBody>(- { message: 'Analytics unavailable' },- { status: 500 }- )- }- const error =- failure === 'string'- ? 'Analytics unavailable'- : { code: 500, errors: [], message: 'Analytics unavailable', status: 'INTERNAL' }- return HttpResponse.json<AnalyticsResponse>({ result: [], error })- },- })-- customRender(<OverviewMetrics isLoading={false} error={null} />)-- expect(await screen.findByText('Failed to retrieve Auth API errors')).toBeVisible()- expect(await screen.findByText('Failed to retrieve Auth server errors')).toBeVisible()- expect(screen.getAllByText('Error: Analytics unavailable')).toHaveLength(2)- expect(screen.queryByText('No data to show')).not.toBeInTheDocument()- }- )- })+ // Error parsing is shared by both endpoints (the success test above covers endpoint+ // selection), so the failure shapes only need checking against one of them+ it.each(['http', 'string', 'object'] as const)(+ 'shows %s errors instead of empty log tables',+ async (failure) => {+ const query = logQueries[1]+ flags.otelLegacyLogs = query.useOtel+ addAPIMock({+ method: 'get',+ path: query.endpoint,+ response: () => {+ if (failure === 'http') {+ return HttpResponse.json<APIErrorBody>(+ { message: 'Analytics unavailable' },+ { status: 500 }+ )+ }+ const error =+ failure === 'string'+ ? 'Analytics unavailable'+ : { code: 500, errors: [], message: 'Analytics unavailable', status: 'INTERNAL' }+ return HttpResponse.json<AnalyticsResponse>({ result: [], error })+ },+ })++ customRender(<OverviewMetrics isLoading={false} error={null} />)++ expect(await screen.findByText('Failed to retrieve Auth API errors')).toBeVisible()+ expect(await screen.findByText('Failed to retrieve Auth server errors')).toBeVisible()+ expect(screen.getAllByText('Error: Analytics unavailable')).toHaveLength(2)+ expect(screen.queryByText('No data to show')).not.toBeInTheDocument()+ }+ )})describe('Auth success rate presentation', () => {diff --git a/apps/studio/components/interfaces/Auth/PerformanceSettingsForm.test.ts b/apps/studio/components/interfaces/Auth/PerformanceSettingsForm.test.tsdeleted file mode 100644index 2cd87a61879..00000000000--- a/apps/studio/components/interfaces/Auth/PerformanceSettingsForm.test.ts+++ /dev/null@@ -1,111 +0,0 @@-import { describe, expect, it } from 'vitest'--import { DatabaseFormSchema } from './PerformanceSettingsForm'--describe('DatabaseFormSchema', () => {- describe('percent unit', () => {- it('accepts 1 (lower bound)', () => {- const result = DatabaseFormSchema.safeParse({- DB_MAX_POOL_SIZE: 1,- DB_MAX_POOL_SIZE_UNIT: 'percent',- })- expect(result.success).toBe(true)- })-- it('accepts 100 (upper bound)', () => {- const result = DatabaseFormSchema.safeParse({- DB_MAX_POOL_SIZE: 100,- DB_MAX_POOL_SIZE_UNIT: 'percent',- })- expect(result.success).toBe(true)- })-- it('accepts a mid-range value', () => {- const result = DatabaseFormSchema.safeParse({- DB_MAX_POOL_SIZE: 50,- DB_MAX_POOL_SIZE_UNIT: 'percent',- })- expect(result.success).toBe(true)- })-- it('rejects 0', () => {- const result = DatabaseFormSchema.safeParse({- DB_MAX_POOL_SIZE: 0,- DB_MAX_POOL_SIZE_UNIT: 'percent',- })- expect(result.success).toBe(false)- })-- it('rejects 101', () => {- const result = DatabaseFormSchema.safeParse({- DB_MAX_POOL_SIZE: 101,- DB_MAX_POOL_SIZE_UNIT: 'percent',- })- expect(result.success).toBe(false)- if (!result.success) {- const issue = result.error.issues.find((i) => i.path[0] === 'DB_MAX_POOL_SIZE')- expect(issue?.message).toBe('Percentage must be between 1 and 100')- }- })-- it('rejects negative values', () => {- const result = DatabaseFormSchema.safeParse({- DB_MAX_POOL_SIZE: -5,- DB_MAX_POOL_SIZE_UNIT: 'percent',- })- expect(result.success).toBe(false)- })-- it('coerces string input', () => {- const result = DatabaseFormSchema.safeParse({- DB_MAX_POOL_SIZE: '75',- DB_MAX_POOL_SIZE_UNIT: 'percent',- })- expect(result.success).toBe(true)- })-- it('rejects out-of-range string input', () => {- const result = DatabaseFormSchema.safeParse({- DB_MAX_POOL_SIZE: '150',- DB_MAX_POOL_SIZE_UNIT: 'percent',- })- expect(result.success).toBe(false)- })- })-- describe('connections unit', () => {- it('accepts 1 (min)', () => {- const result = DatabaseFormSchema.safeParse({- DB_MAX_POOL_SIZE: 1,- DB_MAX_POOL_SIZE_UNIT: 'connections',- })- expect(result.success).toBe(true)- })-- it('accepts values above 100 (no upper schema bound for absolute)', () => {- const result = DatabaseFormSchema.safeParse({- DB_MAX_POOL_SIZE: 500,- DB_MAX_POOL_SIZE_UNIT: 'connections',- })- expect(result.success).toBe(true)- })-- it('rejects 0', () => {- const result = DatabaseFormSchema.safeParse({- DB_MAX_POOL_SIZE: 0,- DB_MAX_POOL_SIZE_UNIT: 'connections',- })- expect(result.success).toBe(false)- })- })-- describe('unit enum', () => {- it('rejects unknown unit values', () => {- const result = DatabaseFormSchema.safeParse({- DB_MAX_POOL_SIZE: 10,- DB_MAX_POOL_SIZE_UNIT: 'bytes',- })- expect(result.success).toBe(false)- })- })-})diff --git a/apps/studio/components/interfaces/Auth/PerformanceSettingsForm.test.tsx b/apps/studio/components/interfaces/Auth/PerformanceSettingsForm.test.tsxindex dac51ffbf2f..f3e886925ee 100644--- a/apps/studio/components/interfaces/Auth/PerformanceSettingsForm.test.tsx+++ b/apps/studio/components/interfaces/Auth/PerformanceSettingsForm.test.tsx@@ -2,7 +2,7 @@ import { screen } from '@testing-library/react'import { HttpResponse } from 'msw'import { describe, expect, test, vi } from 'vitest'-import { PerformanceSettingsForm } from './PerformanceSettingsForm'+import { DatabaseFormSchema, PerformanceSettingsForm } from './PerformanceSettingsForm'import { customRender } from '@/tests/lib/custom-render'import { addAPIMock } from '@/tests/lib/msw'@@ -51,6 +51,38 @@ function mockMaxConnections(maxConnections: number) {})}+describe('DatabaseFormSchema', () => {+ test.each([+ { size: 1, unit: 'percent', valid: true },+ { size: 100, unit: 'percent', valid: true },+ { size: 0, unit: 'percent', valid: false },+ { size: 101, unit: 'percent', valid: false },+ { size: -5, unit: 'percent', valid: false },+ { size: '75', unit: 'percent', valid: true },+ { size: '150', unit: 'percent', valid: false },+ { size: 1, unit: 'connections', valid: true },+ // No upper schema bound for an absolute connection count+ { size: 500, unit: 'connections', valid: true },+ { size: 0, unit: 'connections', valid: false },+ { size: 10, unit: 'bytes', valid: false },+ ])('pool size $size with unit $unit -> valid: $valid', ({ size, unit, valid }) => {+ const result = DatabaseFormSchema.safeParse({+ DB_MAX_POOL_SIZE: size,+ DB_MAX_POOL_SIZE_UNIT: unit,+ })+ expect(result.success).toBe(valid)+ })++ test('explains the percentage bounds when out of range', () => {+ const result = DatabaseFormSchema.safeParse({+ DB_MAX_POOL_SIZE: 101,+ DB_MAX_POOL_SIZE_UNIT: 'percent',+ })+ const issue = result.error?.issues.find((i) => i.path[0] === 'DB_MAX_POOL_SIZE')+ expect(issue?.message).toBe('Percentage must be between 1 and 100')+ })+})+describe('PerformanceSettingsForm', () => {test('reflects a persisted percentage allocation strategy after loading', async () => {mockAuthConfig({ DB_MAX_POOL_SIZE: 15, DB_MAX_POOL_SIZE_UNIT: 'percent' })diff --git a/apps/studio/components/interfaces/Auth/PerformanceSettingsForm.utils.test.ts b/apps/studio/components/interfaces/Auth/PerformanceSettingsForm.utils.test.tsindex 0cbbf4cf9ca..7192f933d7c 100644--- a/apps/studio/components/interfaces/Auth/PerformanceSettingsForm.utils.test.ts+++ b/apps/studio/components/interfaces/Auth/PerformanceSettingsForm.utils.test.ts@@ -1,34 +1,18 @@-import { describe, expect, it } from 'vitest'+import { describe, expect, it, test } from 'vitest'import { convertPoolSize, isAllocationUnit } from './PerformanceSettingsForm.utils'describe('isAllocationUnit', () => {- it('accepts "percent"', () => {- expect(isAllocationUnit('percent')).toBe(true)- })-- it('accepts "connections"', () => {- expect(isAllocationUnit('connections')).toBe(true)- })-- it('rejects an empty string', () => {- expect(isAllocationUnit('')).toBe(false)- })-- it('rejects undefined', () => {- expect(isAllocationUnit(undefined)).toBe(false)- })-- it('rejects null', () => {- expect(isAllocationUnit(null)).toBe(false)- })-- it('rejects an unrelated string', () => {- expect(isAllocationUnit('bytes')).toBe(false)- })-- it('rejects a non-string value', () => {- expect(isAllocationUnit(15)).toBe(false)+ test.each([+ ['percent', true],+ ['connections', true],+ ['', false],+ [undefined, false],+ [null, false],+ ['bytes', false],+ [15, false],+ ])('%s -> %s', (value, expected) => {+ expect(isAllocationUnit(value)).toBe(expected)})})diff --git a/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.test.tsx b/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.test.tsxindex f79fa60b610..3664f45d751 100644--- a/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.test.tsx+++ b/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.test.tsx@@ -8,7 +8,8 @@ import { AddNewURLModal } from './AddNewURLModal'import { render } from '@/tests/helpers'// One entry per URL shape urlRegex() accepts. None may be split by the paste separator,-// otherwise pasting a valid URL would produce invalid rows.+// otherwise pasting a valid URL would produce invalid rows. Pasting them all at once must+// round-trip to exactly this list, which also proves no single entry gets split.const SUPPORTED_URL_FORMS = ['https://example.com','https://example.com/auth/callback',@@ -73,13 +74,15 @@ describe('AddNewURLModal', () => {expect(screen.getAllByPlaceholderText('https://mydomain.com')).toHaveLength(1)- await user.type(screen.getByPlaceholderText('https://mydomain.com'), 'https://app.example.com')+ fireEvent.change(screen.getByPlaceholderText('https://mydomain.com'), {+ target: { value: 'https://app.example.com' },+ })await user.click(screen.getByRole('button', { name: 'Add URL' }))const urlInputs = screen.getAllByPlaceholderText('https://mydomain.com')expect(urlInputs).toHaveLength(2)- await user.type(urlInputs[1], 'https://dashboard.example.com')+ fireEvent.change(urlInputs[1], { target: { value: 'https://dashboard.example.com' } })await user.click(screen.getAllByRole('button', { name: 'Remove URL' })[1])expect(screen.getAllByPlaceholderText('https://mydomain.com')).toHaveLength(1)@@ -102,14 +105,15 @@ describe('AddNewURLModal', () => {})it('normalizes a trailing-comma URL before submitting', async () => {- const user = userEvent.setup()mutateMock.mockImplementation((_vars, callbacks) => callbacks?.onSuccess?.())render(<AddNewURLModal visible allowList={[]} onClose={vi.fn()} />)await screen.findByRole('dialog')- await user.type(screen.getByPlaceholderText('https://mydomain.com'), 'https://app.example.com,')+ fireEvent.change(screen.getByPlaceholderText('https://mydomain.com'), {+ target: { value: 'https://app.example.com,' },+ })fireEvent.submit(screen.getByRole('dialog').querySelector('form') as HTMLFormElement)@@ -181,23 +185,6 @@ describe('AddNewURLModal', () => {expect(mutateMock).not.toHaveBeenCalled()})- it.each(SUPPORTED_URL_FORMS)('leaves the supported URL form %s on one row', async (url) => {- const user = userEvent.setup()-- expect(urlRegex().test(url)).toBe(true)-- render(<AddNewURLModal visible allowList={[]} onClose={vi.fn()} />)-- await screen.findByRole('dialog')-- await user.click(screen.getByPlaceholderText('https://mydomain.com'))- await user.paste(url)-- const inputs = screen.getAllByPlaceholderText('https://mydomain.com') as HTMLInputElement[]- expect(inputs).toHaveLength(1)- expect(inputs[0].value).toBe(url)- })-it('splits a list of every supported URL form back into that list', async () => {const user = userEvent.setup()@@ -237,18 +224,15 @@ describe('AddNewURLModal', () => {})it('rejects a trailing-comma URL when it already exists in the allow list', async () => {- const user = userEvent.setup()-render(<AddNewURLModal visible allowList={['https://existing.example.com']} onClose={vi.fn()} />)await screen.findByRole('dialog')- await user.type(- screen.getByPlaceholderText('https://mydomain.com'),- 'https://existing.example.com,'- )+ fireEvent.change(screen.getByPlaceholderText('https://mydomain.com'), {+ target: { value: 'https://existing.example.com,' },+ })fireEvent.submit(screen.getByRole('dialog').querySelector('form') as HTMLFormElement)@@ -257,18 +241,15 @@ describe('AddNewURLModal', () => {})it('rejects a whitespace-padded URL when it already exists in the allow list', async () => {- const user = userEvent.setup()-render(<AddNewURLModal visible allowList={['https://existing.example.com']} onClose={vi.fn()} />)await screen.findByRole('dialog')- await user.type(- screen.getByPlaceholderText('https://mydomain.com'),- ' https://existing.example.com '- )+ fireEvent.change(screen.getByPlaceholderText('https://mydomain.com'), {+ target: { value: ' https://existing.example.com ' },+ })fireEvent.submit(screen.getByRole('dialog').querySelector('form') as HTMLFormElement)diff --git a/apps/studio/components/interfaces/Auth/SessionsAuthSettingsForm/SessionsAuthSettingsForm.test.tsx b/apps/studio/components/interfaces/Auth/SessionsAuthSettingsForm/SessionsAuthSettingsForm.test.tsxindex a9b9c3b690e..183510470eb 100644--- a/apps/studio/components/interfaces/Auth/SessionsAuthSettingsForm/SessionsAuthSettingsForm.test.tsx+++ b/apps/studio/components/interfaces/Auth/SessionsAuthSettingsForm/SessionsAuthSettingsForm.test.tsx@@ -7,7 +7,6 @@ import { SessionsAuthSettingsForm } from './SessionsAuthSettingsForm'import {MAX_REFRESH_TOKEN_REUSE_INTERVAL_MESSAGE,MAX_SESSIONS_INACTIVITY_TIMEOUT_MESSAGE,- MAX_SESSIONS_TIMEBOX_HOURS,MAX_SESSIONS_TIMEBOX_MESSAGE,} from './SessionsAuthSettingsForm.utils'import { customRender } from '@/tests/lib/custom-render'@@ -124,6 +123,8 @@ async function saveForm(control: HTMLElement) {fireEvent.click(saveButton)}+// Boundary and reduction rules are covered by SessionsAuthSettingsForm.utils.test.ts; these+// tests check the schemas are wired into the form (errors shown, stored values honoured).describe('SessionsAuthSettingsForm — User Sessions', () => {test('blocks submit when the timebox exceeds the maximum', async () => {mockAuthConfig({ SESSIONS_TIMEBOX: 0 })@@ -142,24 +143,6 @@ describe('SessionsAuthSettingsForm — User Sessions', () => {expect(patchCalled).toBe(false)})- test('accepts a timebox at the maximum', async () => {- mockAuthConfig({ SESSIONS_TIMEBOX: 0 })- let patchBody: unknown- mockUpdateAuthConfig((body) => {- patchBody = body- })-- customRender(<SessionsAuthSettingsForm />)-- const input = await screen.findByLabelText('Time-box user sessions')- fireEvent.change(input, { target: { value: String(MAX_SESSIONS_TIMEBOX_HOURS) } })- await saveForm(input)-- await waitFor(() =>- expect(patchBody).toMatchObject({ SESSIONS_TIMEBOX: MAX_SESSIONS_TIMEBOX_HOURS })- )- })-test('saves an over-limit timebox that is already stored', async () => {mockAuthConfig({ SESSIONS_TIMEBOX: 20000 })let patchBody: unknown@@ -179,39 +162,6 @@ describe('SessionsAuthSettingsForm — User Sessions', () => {)})- test('blocks a reduction that is still above the maximum', async () => {- mockAuthConfig({ SESSIONS_TIMEBOX: 20000 })- let patchCalled = false- mockUpdateAuthConfig(() => {- patchCalled = true- })-- customRender(<SessionsAuthSettingsForm />)-- const input = await screen.findByLabelText('Time-box user sessions')- fireEvent.change(input, { target: { value: '15000' } })- await saveForm(input)-- expect(await screen.findByText(MAX_SESSIONS_TIMEBOX_MESSAGE)).toBeInTheDocument()- expect(patchCalled).toBe(false)- })-- test('saves a reduction into the allowed range', async () => {- mockAuthConfig({ SESSIONS_TIMEBOX: 20000 })- let patchBody: unknown- mockUpdateAuthConfig((body) => {- patchBody = body- })-- customRender(<SessionsAuthSettingsForm />)-- const input = await screen.findByLabelText('Time-box user sessions')- fireEvent.change(input, { target: { value: '5000' } })- await saveForm(input)-- await waitFor(() => expect(patchBody).toMatchObject({ SESSIONS_TIMEBOX: 5000 }))- })-test('blocks submit when the inactivity timeout exceeds the maximum', async () => {mockAuthConfig({ SESSIONS_INACTIVITY_TIMEOUT: 0 })let patchCalled = false@@ -267,22 +217,4 @@ describe('SessionsAuthSettingsForm — Refresh Tokens', () => {expect(patchBody).toMatchObject({ SECURITY_REFRESH_TOKEN_REUSE_INTERVAL: 600 }))})-- test('saves a reduction into the allowed range', async () => {- mockAuthConfig({ SECURITY_REFRESH_TOKEN_REUSE_INTERVAL: 600 })- let patchBody: unknown- mockUpdateAuthConfig((body) => {- patchBody = body- })-- customRender(<SessionsAuthSettingsForm />)-- const input = await screen.findByLabelText('Refresh token reuse interval')- fireEvent.change(input, { target: { value: '10' } })- await saveForm(input)-- await waitFor(() =>- expect(patchBody).toMatchObject({ SECURITY_REFRESH_TOKEN_REUSE_INTERVAL: 10 })- )- })})diff --git a/apps/studio/components/interfaces/ConfigDrift/github-config-drift.test.ts b/apps/studio/components/interfaces/ConfigDrift/github-config-drift.test.tsindex 4c698876cac..86f5d7f3b81 100644--- a/apps/studio/components/interfaces/ConfigDrift/github-config-drift.test.ts+++ b/apps/studio/components/interfaces/ConfigDrift/github-config-drift.test.ts@@ -67,29 +67,6 @@ describe('getConfigDriftSummary', () => {})describe('auth.additional_redirect_urls', () => {- it('counts an identical list as managed', () => {- const summary = summaryOf(- getConfigDriftSummary({- dashboardConfig: {- auth: { additional_redirect_urls: ['https://a.com', 'https://b.com'] },- },- githubConfig: { auth: { additional_redirect_urls: ['https://a.com', 'https://b.com'] } },- })- )-- expect(summary).toEqual({- driftedFields: [],- matchedFields: [- {- section: 'auth',- configPath: 'auth.additional_redirect_urls',- value: ['https://a.com', 'https://b.com'],- },- ],- unmanagedFields: [],- })- })-it('counts a list that differs only in order as managed', () => {const summary = summaryOf(getConfigDriftSummary({diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectConfigSection.test.tsx b/apps/studio/components/interfaces/ConnectSheet/ConnectConfigSection.test.tsxindex bad879d0812..0731f8f3616 100644--- a/apps/studio/components/interfaces/ConnectSheet/ConnectConfigSection.test.tsx+++ b/apps/studio/components/interfaces/ConnectSheet/ConnectConfigSection.test.tsx@@ -33,7 +33,7 @@ const manyFrameworkOptions = Array.from({ length: 20 }, (_, index) => ({}))describe('ConnectConfigSection', () => {- test('filters frameworks and selects the matching option', async () => {+ test('filters frameworks, selects the matching option, and clears the search on close', async () => {const user = userEvent.setup()const onFieldChange = vi.fn()@@ -55,6 +55,9 @@ describe('ConnectConfigSection', () => {await user.click(screen.getByRole('option', { name: 'React Native' }))expect(onFieldChange).toHaveBeenCalledWith('framework', 'react-native')++ await user.click(screen.getByRole('combobox'))+ expect(screen.getByPlaceholderText('Search frameworks...')).toHaveValue('')})test('matches frameworks by key without announcing the empty state', async () => {@@ -94,27 +97,6 @@ describe('ConnectConfigSection', () => {expect(screen.getByRole('status')).toHaveTextContent('No frameworks found')})- test('clears the search when the combobox closes after selecting an option', async () => {- const user = userEvent.setup()-- customRender(- <ConnectConfigSection- activeFields={[frameworkField]}- state={{ framework: 'nextjs' }}- onFieldChange={vi.fn()}- getFieldOptions={() => frameworkOptions}- />- )-- await user.click(screen.getByRole('combobox'))- const searchInput = screen.getByPlaceholderText('Search frameworks...')- await user.type(searchInput, 'native')- await user.click(screen.getByRole('option', { name: 'React Native' }))- await user.click(screen.getByRole('combobox'))-- expect(screen.getByPlaceholderText('Search frameworks...')).toHaveValue('')- })-test('uses a bounded scroll area for long framework lists', async () => {const user = userEvent.setup()diff --git a/apps/studio/components/interfaces/ConnectSheet/WarehouseTab.test.tsx b/apps/studio/components/interfaces/ConnectSheet/WarehouseTab.test.tsxindex e44d5a8e039..18f82fbad9b 100644--- a/apps/studio/components/interfaces/ConnectSheet/WarehouseTab.test.tsx+++ b/apps/studio/components/interfaces/ConnectSheet/WarehouseTab.test.tsx@@ -131,7 +131,6 @@ describe('WarehouseTab', () => {})expect(await screen.findByRole('combobox', { name: 'Query engine' })).toBeInTheDocument()- expect(container.querySelector('.border-0.shadow-none')).toBeInTheDocument()expect(container.querySelector('[data-orientation="horizontal"]')).not.toBeInTheDocument()expect(screen.queryByRole('heading', { name: 'Connect' })).not.toBeInTheDocument()expect(screen.getByDisplayValue('default.warehouse.supabase.co')).toBeInTheDocument()@@ -205,10 +204,7 @@ describe('WarehouseTab', () => {expect(screen.getByRole('button', { name: 'Copy prompt' })).toBeInTheDocument()expect(screen.getByText('Set environment variables')).toBeInTheDocument()expect(screen.getByText('Attach Warehouse')).toBeInTheDocument()-- const stepsSection = screen.getByRole('heading', { name: 'Follow these steps' }).parentElement- ?.parentElement- expect(stepsSection).toHaveClass('border-t', 'bg-muted/50')+ expect(screen.getByRole('heading', { name: 'Follow these steps' })).toBeInTheDocument()expect(screen.queryByText('s3-secret')).not.toBeInTheDocument()await userEvent.click(screen.getByRole('button', { name: 'Reveal DUCKLAKE_S3_SECRET' }))diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/Connect.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/Connect.utils.test.tsindex c5b7a91096c..8bad605b163 100644--- a/apps/studio/components/interfaces/ConnectSheet/__tests__/Connect.utils.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/Connect.utils.test.ts@@ -3,222 +3,23 @@ import { describe, expect, test } from 'vitest'import { resolveFrameworkLibraryKey } from '../Connect.utils'describe('Connect.utils:resolveFrameworkLibraryKey', () => {- test('should return null if no framework provided', () => {- const result = resolveFrameworkLibraryKey({- framework: undefined,- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBeNull()- })-- test('should return null for empty framework string', () => {- const result = resolveFrameworkLibraryKey({- framework: '',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBeNull()- })-- test('should return explicit library if provided', () => {- const result = resolveFrameworkLibraryKey({- framework: 'nextjs',- frameworkVariant: 'app',- library: 'custom-library',- })- expect(result).toBe('custom-library')- })-- test('should resolve library for Next.js App Router', () => {- const result = resolveFrameworkLibraryKey({- framework: 'nextjs',- frameworkVariant: 'app',- library: undefined,- })- // Next.js App Router has supabasejs as its library- expect(result).toBe('supabasejs')- })-- test('should resolve library for Next.js Pages Router', () => {- const result = resolveFrameworkLibraryKey({- framework: 'nextjs',- frameworkVariant: 'pages',- library: undefined,- })- expect(result).toBe('supabasejs')- })-- test('should resolve library for React with Vite variant', () => {- const result = resolveFrameworkLibraryKey({- framework: 'react',- frameworkVariant: 'vite',- library: undefined,- })- expect(result).toBe('supabasejs')- })-- test('should resolve library for React with Create React App variant', () => {- const result = resolveFrameworkLibraryKey({- framework: 'react',- frameworkVariant: 'create-react-app',- library: undefined,- })- expect(result).toBe('supabasejs')- })-- test('should resolve library for framework without variants (Remix)', () => {- const result = resolveFrameworkLibraryKey({- framework: 'remix',- frameworkVariant: undefined,- library: undefined,- })- // Remix has single child which is supabasejs- expect(result).toBe('supabasejs')- })-- test('should resolve library for Flutter', () => {- const result = resolveFrameworkLibraryKey({- framework: 'flutter',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabaseflutter')- })-- test('should resolve library for Swift', () => {- const result = resolveFrameworkLibraryKey({- framework: 'swift',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabaseswift')- })-- test('should resolve library for Android Kotlin', () => {- const result = resolveFrameworkLibraryKey({- framework: 'androidkotlin',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabasekt')- })-- test('should resolve library for Flask (Python)', () => {- const result = resolveFrameworkLibraryKey({- framework: 'flask',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabasepy')- })-- test('should fallback to first variant library when variant not specified for multi-variant framework', () => {- const result = resolveFrameworkLibraryKey({- framework: 'nextjs',- frameworkVariant: undefined,- library: undefined,- })- // Should get library from first variant (app router)- expect(result).toBe('supabasejs')- })-- test('should return null for unknown framework', () => {- const result = resolveFrameworkLibraryKey({- framework: 'unknown-framework',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBeNull()- })-- test('should handle SvelteKit framework', () => {- const result = resolveFrameworkLibraryKey({- framework: 'sveltekit',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabasejs')- })-- test('should handle Nuxt framework', () => {- const result = resolveFrameworkLibraryKey({- framework: 'nuxt',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabasejs')- })-- test('should handle Vue.js framework', () => {- const result = resolveFrameworkLibraryKey({- framework: 'vuejs',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabasejs')- })-- test('should handle Solid.js framework', () => {- const result = resolveFrameworkLibraryKey({- framework: 'solidjs',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabasejs')- })-- test('should handle Astro framework', () => {- const result = resolveFrameworkLibraryKey({- framework: 'astro',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabasejs')- })-- test('should handle Expo React Native', () => {- const result = resolveFrameworkLibraryKey({- framework: 'exporeactnative',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabasejs')- })-- test('should handle Ionic React', () => {- const result = resolveFrameworkLibraryKey({- framework: 'ionicreact',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabasejs')- })-- test('should handle Ionic Angular', () => {- const result = resolveFrameworkLibraryKey({- framework: 'ionicangular',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabasejs')- })-- test('should handle Refine framework', () => {- const result = resolveFrameworkLibraryKey({- framework: 'refine',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabasejs')- })-- test('should handle TanStack Start framework', () => {- const result = resolveFrameworkLibraryKey({- framework: 'tanstack',- frameworkVariant: undefined,- library: undefined,- })- expect(result).toBe('supabasejs')+ test.each<[string, string | undefined, string | undefined, string | undefined, string | null]>([+ ['no framework', undefined, undefined, undefined, null],+ ['empty framework string', '', undefined, undefined, null],+ ['unknown framework', 'unknown-framework', undefined, undefined, null],+ ['explicit library', 'nextjs', 'app', 'custom-library', 'custom-library'],+ ['Next.js App Router', 'nextjs', 'app', undefined, 'supabasejs'],+ ['Next.js Pages Router', 'nextjs', 'pages', undefined, 'supabasejs'],+ ['React with Vite', 'react', 'vite', undefined, 'supabasejs'],+ // Falls back to the first variant's library when no variant is specified+ ['multi-variant framework without variant', 'nextjs', undefined, undefined, 'supabasejs'],+ // Single child framework: the child itself is the library+ ['framework without variants (Remix)', 'remix', undefined, undefined, 'supabasejs'],+ ['Flutter', 'flutter', undefined, undefined, 'supabaseflutter'],+ ['Swift', 'swift', undefined, undefined, 'supabaseswift'],+ ['Android Kotlin', 'androidkotlin', undefined, undefined, 'supabasekt'],+ ['Flask (Python)', 'flask', undefined, undefined, 'supabasepy'],+ ])('%s', (_label, framework, frameworkVariant, library, expected) => {+ expect(resolveFrameworkLibraryKey({ framework, frameworkVariant, library })).toBe(expected)})})diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectSheet.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectSheet.utils.test.tsindex 6f8d499096d..76187d01065 100644--- a/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectSheet.utils.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectSheet.utils.test.ts@@ -20,20 +20,16 @@ const EMPTY_QUERY: ConnectSheetQueryParams = {const EMPTY_PREFS: ConnectSheetPrefs = {}describe('mapConnectTabToMode', () => {- test('returns null for null tab', () => {- expect(mapConnectTabToMode(null)).toBeNull()+ test.each([null, 'not-a-real-tab'])('returns null for %s', (tab) => {+ expect(mapConnectTabToMode(tab)).toBeNull()})- test('returns null for an unrecognized tab', () => {- expect(mapConnectTabToMode('not-a-real-tab')).toBeNull()- })-- test.each(['frameworks', 'mobiles'])('maps "%s" to framework mode', (tab) => {- expect(mapConnectTabToMode(tab)).toBe('framework')- })-- test('maps "orms" to orm mode', () => {- expect(mapConnectTabToMode('orms')).toBe('orm')+ test.each([+ ['frameworks', 'framework'],+ ['mobiles', 'framework'],+ ['orms', 'orm'],+ ])('maps legacy tab "%s" to %s mode', (tab, mode) => {+ expect(mapConnectTabToMode(tab)).toBe(mode)})test.each(ALL_MODES)('passes through an already-valid mode "%s"', (mode) => {diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectStepsSection.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectStepsSection.utils.test.tsindex 7a3c4fb6072..731dab8a768 100644--- a/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectStepsSection.utils.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectStepsSection.utils.test.ts@@ -126,11 +126,11 @@ describe('resolveContentPath', () => {})describe('shouldShowIpv4AddonNotice', () => {- const BASE = {+ const BASE: Parameters<typeof shouldShowIpv4AddonNotice>[0] = {isPlatform: true,isAws: true,isIpv4Enabled: true,- mode: 'direct' as const,+ mode: 'direct',connectionMethod: 'direct',useSharedPooler: false,hasIpv4Addon: false,@@ -151,80 +151,40 @@ describe('shouldShowIpv4AddonNotice', () => {).toBe(true)})- test('returns false for the transaction pooler when using the shared pooler (already IPv4)', () => {- expect(- shouldShowIpv4AddonNotice({ ...BASE, connectionMethod: 'transaction', useSharedPooler: true })- ).toBe(false)- })-- test('returns false for the session pooler (has its own notice)', () => {- expect(shouldShowIpv4AddonNotice({ ...BASE, connectionMethod: 'session' })).toBe(false)- })-- test('returns false when the IPv4 addon is already enabled', () => {- expect(shouldShowIpv4AddonNotice({ ...BASE, hasIpv4Addon: true })).toBe(false)- })-- test('returns false when not in direct mode', () => {- expect(shouldShowIpv4AddonNotice({ ...BASE, mode: 'framework' })).toBe(false)- })-- test('returns false when self-hosted (not platform)', () => {- expect(shouldShowIpv4AddonNotice({ ...BASE, isPlatform: false })).toBe(false)- })-- test('returns false when not on AWS (e.g. Multigres/Fly)', () => {- expect(shouldShowIpv4AddonNotice({ ...BASE, isAws: false })).toBe(false)- })-- test('returns false when the IPv4 add-on is not enabled for the project', () => {- expect(shouldShowIpv4AddonNotice({ ...BASE, isIpv4Enabled: false })).toBe(false)- })-- test('returns false for high-availability projects even with a direct connection and no addon', () => {- expect(shouldShowIpv4AddonNotice({ ...BASE, isHighAvailability: true })).toBe(false)+ test.each<[string, Partial<typeof BASE>]>([+ [+ 'the transaction pooler via the shared pooler (already IPv4)',+ { connectionMethod: 'transaction', useSharedPooler: true },+ ],+ ['the session pooler (has its own notice)', { connectionMethod: 'session' }],+ ['the IPv4 addon is already enabled', { hasIpv4Addon: true }],+ ['not in direct mode', { mode: 'framework' }],+ ['self-hosted (not platform)', { isPlatform: false }],+ ['not on AWS (e.g. Multigres/Fly)', { isAws: false }],+ ['the IPv4 add-on is not enabled for the project', { isIpv4Enabled: false }],+ ['high-availability projects', { isHighAvailability: true }],+ ])('returns false for %s', (_label, overrides) => {+ expect(shouldShowIpv4AddonNotice({ ...BASE, ...overrides })).toBe(false)})})describe('shouldShowSessionPoolerNotice', () => {- test('returns true for the session pooler on platform in direct mode', () => {- expect(- shouldShowSessionPoolerNotice({- isPlatform: true,- mode: 'direct',- connectionMethod: 'session',- })- ).toBe(true)- })-- test('returns false when self-hosted (not platform)', () => {- expect(- shouldShowSessionPoolerNotice({- isPlatform: false,- mode: 'direct',- connectionMethod: 'session',- })- ).toBe(false)- })+ const BASE: Parameters<typeof shouldShowSessionPoolerNotice>[0] = {+ isPlatform: true,+ mode: 'direct',+ connectionMethod: 'session',+ }- test('returns false when not in direct mode', () => {- expect(- shouldShowSessionPoolerNotice({- isPlatform: true,- mode: 'framework',- connectionMethod: 'session',- })- ).toBe(false)+ test('returns true for the session pooler on platform in direct mode', () => {+ expect(shouldShowSessionPoolerNotice(BASE)).toBe(true)})- test('returns false for a non-session connection method', () => {- expect(- shouldShowSessionPoolerNotice({- isPlatform: true,- mode: 'direct',- connectionMethod: 'transaction',- })- ).toBe(false)+ test.each<[string, Partial<typeof BASE>]>([+ ['self-hosted (not platform)', { isPlatform: false }],+ ['not in direct mode', { mode: 'framework' }],+ ['a non-session connection method', { connectionMethod: 'transaction' }],+ ])('returns false for %s', (_label, overrides) => {+ expect(shouldShowSessionPoolerNotice({ ...BASE, ...overrides })).toBe(false)})})diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectionString.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectionString.utils.test.tsindex 613bf998d84..34ab54374a6 100644--- a/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectionString.utils.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/ConnectionString.utils.test.ts@@ -1,5 +1,7 @@import { describe, expect, test } from 'vitest'+import type { ConnectionStringMethod } from '../Connect.constants'+import type { ConnectionStringPooler } from '../Connect.types'import {appendConnectionStringParams,buildConnectionParameters,@@ -16,18 +18,8 @@ import {} from '../ConnectionString.utils'describe('parseConnectionParams', () => {- test('returns hidden defaults for an empty string', () => {- expect(parseConnectionParams('')).toEqual({- host: 'hidden',- port: DEFAULT_PORT,- user: 'hidden',- database: 'hidden',- search: '',- })- })-- test('returns hidden defaults for an unparseable URL', () => {- expect(parseConnectionParams('not a url')).toEqual({+ test.each(['', 'not a url'])('returns hidden defaults for %j', (uri) => {+ expect(parseConnectionParams(uri)).toEqual({host: 'hidden',port: DEFAULT_PORT,user: 'hidden',@@ -103,7 +95,7 @@ describe('buildConnectionStringWithPassword', () => {})describe('resolveConnectionString', () => {- const pooler = {+ const pooler: ConnectionStringPooler = {transactionShared: 'tx-shared',sessionShared: 'session-shared',transactionDedicated: 'tx-dedicated',@@ -122,55 +114,21 @@ describe('resolveConnectionString', () => {).toBe('')})- test('direct method returns the direct URI', () => {- expect(- resolveConnectionString({- connectionMethod: 'direct',- useSharedPooler: false,- connectionStringPooler: pooler,- })- ).toBe('direct-uri')- })-- test('session method returns sessionShared', () => {- expect(- resolveConnectionString({- connectionMethod: 'session',- useSharedPooler: false,- connectionStringPooler: pooler,- })- ).toBe('session-shared')- })-- test('transaction prefers dedicated when available and useSharedPooler is false', () => {- expect(- resolveConnectionString({- connectionMethod: 'transaction',- useSharedPooler: false,- connectionStringPooler: pooler,- })- ).toBe('tx-dedicated')- })-- test('transaction falls back to shared when useSharedPooler is true', () => {- expect(- resolveConnectionString({- connectionMethod: 'transaction',- useSharedPooler: true,- connectionStringPooler: pooler,- })- ).toBe('tx-shared')- })-- test('transaction falls back to shared when no dedicated pooler exists', () => {- expect(- resolveConnectionString({- connectionMethod: 'transaction',- useSharedPooler: false,- connectionStringPooler: { ...pooler, transactionDedicated: undefined },- })- ).toBe('tx-shared')- })+ test.each<[ConnectionStringMethod, boolean, ConnectionStringPooler, string]>([+ ['direct', false, pooler, 'direct-uri'],+ ['session', false, pooler, 'session-shared'],+ // transaction prefers the dedicated pooler when available+ ['transaction', false, pooler, 'tx-dedicated'],+ ['transaction', true, pooler, 'tx-shared'],+ ['transaction', false, { ...pooler, transactionDedicated: undefined }, 'tx-shared'],+ ])(+ '%s method (useSharedPooler: %s) resolves the expected URI',+ (connectionMethod, useSharedPooler, connectionStringPooler, expected) => {+ expect(+ resolveConnectionString({ connectionMethod, useSharedPooler, connectionStringPooler })+ ).toBe(expected)+ }+ )})describe('appendConnectionStringParams', () => {diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/CopyPromptAdmonition.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/CopyPromptAdmonition.test.tsindex 22769daa6d4..20fe5bdc16a 100644--- a/apps/studio/components/interfaces/ConnectSheet/__tests__/CopyPromptAdmonition.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/CopyPromptAdmonition.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { describe, expect, test } from 'vitest'import { buildConnectPrompt } from '../CopyPromptAdmonition'diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/DatabaseSettings.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/DatabaseSettings.utils.test.tsindex b710553ba70..dcfa1136009 100644--- a/apps/studio/components/interfaces/ConnectSheet/__tests__/DatabaseSettings.utils.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/DatabaseSettings.utils.test.ts@@ -64,11 +64,6 @@ describe('getSelfHostedPoolerStrings', () => {expect(strings.dotnet).toContain('Database=mydb')expect(strings.nodejs).toBe(`DATABASE_URL=${strings.uri}`)})-- test('defaults database name to postgres', () => {- const strings = getSelfHostedPoolerStrings('db.example.com', 6543)- expect(strings.uri.endsWith('/postgres')).toBe(true)- })})describe('getSelfHostedDirectStrings', () => {@@ -202,22 +197,6 @@ describe('buildConnectionStringPooler', () => {expect(result.sessionDedicated).toBeUndefined()expect(result.ipv4SupportedForDedicatedPooler).toBe(false)})-- test('platform without high availability appends no SSL params', () => {- const result = buildConnectionStringPooler({- deploymentMode: platform,- connectionInfo,- connectionStringsShared: sharedPlatform,- connectionStringsDedicated: dedicatedPlatform,- ipv4Addon: true,- isHighAvailability: false,- })-- expect(result.direct).toBe(sharedPlatform.direct.uri)- expect(result.transactionShared).toBe(sharedPlatform.pooler.uri)- expect(result.direct).not.toContain('sslnegotiation')- expect(result.transactionShared).not.toContain('sslnegotiation')- })})describe('appendHighAvailabilitySslParams', () => {diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/connect.resolver.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/connect.resolver.test.tsindex 002fe0c7f3d..cd61cc56b24 100644--- a/apps/studio/components/interfaces/ConnectSheet/__tests__/connect.resolver.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/connect.resolver.test.ts@@ -163,7 +163,7 @@ describe('connect.resolver:resolveSteps', () => {steps,})- test('should resolve steps array for framework mode', () => {+ test('should resolve the steps array for the current mode', () => {const schema = createMockSchema({mode: {framework: [@@ -181,26 +181,11 @@ describe('connect.resolver:resolveSteps', () => {},})- const steps = resolveSteps(schema, { mode: 'framework' })- expect(steps).toHaveLength(2)- expect(steps[0].id).toBe('step1')- expect(steps[0].title).toBe('Install')- expect(steps[1].id).toBe('step2')- })+ const frameworkSteps = resolveSteps(schema, { mode: 'framework' })+ expect(frameworkSteps.map((s) => s.id)).toEqual(['step1', 'step2'])+ expect(frameworkSteps[0].title).toBe('Install')- test('should resolve steps for direct mode', () => {- const schema = createMockSchema({- mode: {- framework: [{ id: 'step1', title: 'Install', description: 'Install', content: 'install' }],- direct: [- { id: 'connection', title: 'Connection', description: 'Connect', content: 'direct' },- ],- },- })-- const steps = resolveSteps(schema, { mode: 'direct' })- expect(steps).toHaveLength(1)- expect(steps[0].id).toBe('connection')+ expect(resolveSteps(schema, { mode: 'direct' }).map((s) => s.id)).toEqual(['connection'])})test('should filter out steps with empty content', () => {@@ -247,17 +232,6 @@ describe('connect.resolver:resolveSteps', () => {expect(vueSteps[0].content).toBe('generic-content')})- test('should return empty array when no steps resolve', () => {- const schema = createMockSchema({- mode: {- framework: [{ id: 'step1', title: 'Step', description: 'Desc', content: '' }],- },- })-- const steps = resolveSteps(schema, { mode: 'framework' })- expect(steps).toEqual([])- })-test('should return empty array when steps is not an array', () => {const schema = createMockSchema({mode: {@@ -593,20 +567,21 @@ describe('connect.resolver:resetDependentFields', () => {expect(newState.frameworkUi).toBe(true)})- test('should handle mode changes', () => {+ test('should drop fields from the other mode when the mode changes', () => {const schema = createSchemaForReset()const state: ConnectState = {- mode: 'direct', // Changed mode+ mode: 'direct',framework: 'nextjs',frameworkVariant: 'app',+ connectionMethod: 'direct',}- // Note: The current implementation of resetDependentFields for mode changes- // looks for fields not in the current mode, but the logic compares against previous modeconst newState = resetDependentFields(state, 'mode', schema)- // Mode-specific field reset logic is handledexpect(newState.mode).toBe('direct')+ expect(newState.connectionMethod).toBe('direct')+ expect(newState.framework).toBeUndefined()+ expect(newState.frameworkVariant).toBeUndefined()})test('should not modify state for fields without dependencies', () => {diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/connect.schema.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/connect.schema.test.tsindex 07d9727967e..0b959688e9d 100644--- a/apps/studio/components/interfaces/ConnectSheet/__tests__/connect.schema.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/connect.schema.test.ts@@ -1,57 +1,17 @@import { describe, expect, test } from 'vitest'import { resolveSteps } from '../connect.resolver'-import { connectSchema, EXTRA_PACKAGES, INSTALL_COMMANDS } from '../connect.schema'+import { connectSchema } from '../connect.schema'import type { ConnectState } from '../Connect.types'// ============================================================================-// Schema Structure Tests+// Schema Integrity Tests// ============================================================================describe('connect.schema:structure', () => {test('should have all required modes', () => {const modeIds = connectSchema.modes.map((m) => m.id)- expect(modeIds).toContain('framework')- expect(modeIds).toContain('direct')- expect(modeIds).toContain('orm')- expect(modeIds).toContain('mcp')- })-- test('each mode should have required properties', () => {- connectSchema.modes.forEach((mode) => {- expect(mode.id).toBeDefined()- expect(mode.label).toBeDefined()- expect(mode.description).toBeDefined()- expect(mode.fields).toBeDefined()- expect(Array.isArray(mode.fields)).toBe(true)- })- })-- test('framework mode should have correct fields', () => {- const frameworkMode = connectSchema.modes.find((m) => m.id === 'framework')- expect(frameworkMode?.fields).toContain('framework')- expect(frameworkMode?.fields).toContain('frameworkVariant')- expect(frameworkMode?.fields).toContain('library')- expect(frameworkMode?.fields).toContain('frameworkUi')- })-- test('direct mode should have correct fields', () => {- const directMode = connectSchema.modes.find((m) => m.id === 'direct')- expect(directMode?.fields).toContain('connectionMethod')- expect(directMode?.fields).toContain('useSharedPooler')- expect(directMode?.fields).toContain('connectionType')- })-- test('orm mode should have correct fields', () => {- const ormMode = connectSchema.modes.find((m) => m.id === 'orm')- expect(ormMode?.fields).toContain('orm')- })-- test('mcp mode should have correct fields', () => {- const mcpMode = connectSchema.modes.find((m) => m.id === 'mcp')- expect(mcpMode?.fields).toContain('mcpClient')- expect(mcpMode?.fields).toContain('mcpReadonly')- expect(mcpMode?.fields).toContain('mcpFeatures')+ expect(modeIds).toEqual(expect.arrayContaining(['framework', 'direct', 'orm', 'mcp']))})test('all mode fields should exist in fields definition', () => {@@ -64,114 +24,11 @@ describe('connect.schema:structure', () => {})})})-})-// ============================================================================-// Field Definition Tests-// ============================================================================--describe('connect.schema:fields', () => {- test('framework field should have correct type', () => {- const field = connectSchema.fields.framework- expect(field.type).toBe('combobox')- expect(field.options).toEqual({ source: 'frameworks' })- expect(field.defaultValue).toBe('nextjs')- })-- test('frameworkVariant field should depend on framework', () => {- const field = connectSchema.fields.frameworkVariant- expect(field.dependsOn).toEqual({ framework: ['nextjs', 'react', 'dotnet'] })- })-- test('frameworkUi field should be a switch type', () => {- const field = connectSchema.fields.frameworkUi- expect(field.type).toBe('switch')- expect(field.defaultValue).toBe(false)- expect(field.dependsOn).toEqual({ framework: ['nextjs', 'react'] })- })-- test('connectionMethod field should have radio-list type', () => {- const field = connectSchema.fields.connectionMethod- expect(field.type).toBe('radio-list')- expect(field.options).toEqual({ source: 'connectionMethods' })+ test('connectionMethod has no static default', () => {// defaultValue is intentionally unset — useConnectState.setMode picks the// per-deployment-mode default (platform/CLI: 'direct'; self-hosted: 'session')- expect(field.defaultValue).toBeUndefined()- })-- test('useSharedPooler field should depend on transaction connection method', () => {- const field = connectSchema.fields.useSharedPooler- expect(field.type).toBe('switch')- expect(field.dependsOn).toEqual({ connectionMethod: ['transaction'] })- })-- test('orm field should have radio-list type', () => {- const field = connectSchema.fields.orm- expect(field.type).toBe('radio-list')- expect(field.options).toEqual({ source: 'orms' })- expect(field.defaultValue).toBe('prisma')- })-- test('mcpClient field should have combobox type', () => {- const field = connectSchema.fields.mcpClient- expect(field.type).toBe('combobox')- expect(field.options).toEqual({ source: 'mcpClients' })- expect(field.defaultValue).toBe('claude-code')- })-- test('mcpFeatures field should have multi-select type', () => {- const field = connectSchema.fields.mcpFeatures- expect(field.type).toBe('multi-select')- expect(field.options).toEqual({ source: 'mcpFeatures' })- expect(field.defaultValue).toEqual([- 'docs',- 'account',- 'database',- 'debugging',- 'development',- 'functions',- 'branching',- ])- })-})--// ============================================================================-// Install Commands Tests-// ============================================================================--describe('connect.schema:INSTALL_COMMANDS', () => {- test('should have install command for supabase-js', () => {- expect(INSTALL_COMMANDS.supabasejs).toBe('npm install @supabase/supabase-js')- })-- test('should have install command for supabase-py', () => {- expect(INSTALL_COMMANDS.supabasepy).toBe('pip install supabase')- })-- test('should have install command for supabase-flutter', () => {- expect(INSTALL_COMMANDS.supabaseflutter).toBe('flutter pub add supabase_flutter')- })-- test('should have install command for supabase-swift', () => {- expect(INSTALL_COMMANDS.supabaseswift).toContain('swift package add-dependency')- })-- test('should have install command for supabase-kt', () => {- expect(INSTALL_COMMANDS.supabasekt).toContain('io.github.jan-tennert.supabase')- })-})--describe('connect.schema:EXTRA_PACKAGES', () => {- test('should have @supabase/ssr as extra package for nextjs app router with supabasejs', () => {- expect(EXTRA_PACKAGES.supabasejs?.['nextjs/app']).toContain('@supabase/ssr')- })-- test('should not have extra packages for nextjs pages router', () => {- expect(EXTRA_PACKAGES.supabasejs?.['nextjs/pages']).toBeUndefined()- })-- test('should have @supabase/ssr as extra package for remix with supabasejs', () => {- expect(EXTRA_PACKAGES.supabasejs?.remix).toContain('@supabase/ssr')+ expect(connectSchema.fields.connectionMethod.defaultValue).toBeUndefined()})})@@ -179,200 +36,87 @@ describe('connect.schema:EXTRA_PACKAGES', () => {// Steps Resolution Integration Tests// ============================================================================-describe('connect.schema:steps resolution', () => {- describe('framework mode steps', () => {- test('should resolve steps for nextjs without shadcn', () => {- const state: ConnectState = { mode: 'framework', framework: 'nextjs', frameworkUi: false }- const steps = resolveSteps(connectSchema, state)+const stepIds = (state: ConnectState) => resolveSteps(connectSchema, state).map((s) => s.id)- expect(steps.length).toBeGreaterThan(0)- expect(steps.find((s) => s.id === 'install')).toBeDefined()- expect(steps.find((s) => s.id === 'install-skills')).toBeDefined()- })-- test('should use "Install packages" title for nextjs app router', () => {- const state: ConnectState = {- mode: 'framework',- framework: 'nextjs',- frameworkVariant: 'app',- frameworkUi: false,- }- const steps = resolveSteps(connectSchema, state)- const installStep = steps.find((s) => s.id === 'install')-- expect(installStep?.title).toBe('Install packages')- })-- test('should use "Install package" title for nextjs pages router', () => {- const state: ConnectState = {- mode: 'framework',- framework: 'nextjs',- frameworkVariant: 'pages',- frameworkUi: false,- }- const steps = resolveSteps(connectSchema, state)- const installStep = steps.find((s) => s.id === 'install')-- expect(installStep?.title).toBe('Install package')- })-- test('should use "Install packages" title for remix install step', () => {- const state: ConnectState = { mode: 'framework', framework: 'remix' }- const steps = resolveSteps(connectSchema, state)- const installStep = steps.find((s) => s.id === 'install')-- expect(installStep?.title).toBe('Install packages')- })-- test('should use "Install package" title for frameworks without extra packages', () => {- const state: ConnectState = { mode: 'framework', framework: 'vuejs' }- const steps = resolveSteps(connectSchema, state)- const installStep = steps.find((s) => s.id === 'install')-- expect(installStep?.title).toBe('Install package')- })-- test('should resolve shadcn steps for nextjs with frameworkUi true', () => {- const state: ConnectState = { mode: 'framework', framework: 'nextjs', frameworkUi: true }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'shadcn-add')).toBeDefined()- expect(steps.find((s) => s.id === 'shadcn-env')).toBeDefined()- expect(steps.find((s) => s.id === 'shadcn-explore')).toBeUndefined()- })-- test('should resolve steps for react without shadcn', () => {- const state: ConnectState = { mode: 'framework', framework: 'react', frameworkUi: false }- const steps = resolveSteps(connectSchema, state)-- expect(steps.length).toBeGreaterThan(0)- expect(steps.find((s) => s.id === 'install')).toBeDefined()- })-- test('should resolve shadcn steps for react with frameworkUi true', () => {- const state: ConnectState = { mode: 'framework', framework: 'react', frameworkUi: true }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'shadcn-add')).toBeDefined()- expect(steps.find((s) => s.id === 'shadcn-env')).toBeDefined()- })-- test('should resolve default steps for other frameworks', () => {- const state: ConnectState = { mode: 'framework', framework: 'remix' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.length).toBeGreaterThan(0)- expect(steps.find((s) => s.id === 'install')).toBeDefined()- expect(steps.find((s) => s.id === 'configure')).toBeDefined()- })- })-- describe('direct mode steps', () => {- test('should resolve connection step for default direct mode', () => {- const state: ConnectState = { mode: 'direct' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'connection')).toBeDefined()- })-- test('should resolve install and files steps for nodejs connection type', () => {- const state: ConnectState = { mode: 'direct', connectionType: 'nodejs' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'direct-install')).toBeDefined()- expect(steps.find((s) => s.id === 'direct-files')).toBeDefined()- })-- test('should resolve install and files steps for golang connection type', () => {- const state: ConnectState = { mode: 'direct', connectionType: 'golang' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'direct-install')).toBeDefined()- expect(steps.find((s) => s.id === 'direct-files')).toBeDefined()- })-- test('should resolve install and files steps for python connection type', () => {- const state: ConnectState = { mode: 'direct', connectionType: 'python' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'direct-install')).toBeDefined()- })-- test('should resolve install and files steps for dotnet connection type', () => {- const state: ConnectState = { mode: 'direct', connectionType: 'dotnet' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'direct-install')).toBeDefined()- })- })-- describe('orm mode steps', () => {- test('should resolve install and configure steps for prisma', () => {- const state: ConnectState = { mode: 'orm', orm: 'prisma' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'install')).toBeDefined()- expect(steps.find((s) => s.id === 'configure')).toBeDefined()- expect(steps.find((s) => s.id === 'install-skills')).toBeDefined()- })-- test('should resolve install and configure steps for drizzle', () => {- const state: ConnectState = { mode: 'orm', orm: 'drizzle' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'install')).toBeDefined()- expect(steps.find((s) => s.id === 'configure')).toBeDefined()- })- })-- describe('mcp mode steps', () => {- test('should resolve configure step for cursor client', () => {- const state: ConnectState = { mode: 'mcp', mcpClient: 'cursor' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'configure-mcp')).toBeDefined()- expect(steps.find((s) => s.id === 'install-skills')).toBeDefined()- })-- test('should resolve codex-specific steps for codex client', () => {- const state: ConnectState = { mode: 'mcp', mcpClient: 'codex' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'codex-add-server')).toBeDefined()- expect(steps.find((s) => s.id === 'codex-authenticate')).toBeDefined()- expect(steps.find((s) => s.id === 'codex-verify')).toBeDefined()- })-- test('should resolve claude-code-specific steps for claude-code client', () => {- const state: ConnectState = { mode: 'mcp', mcpClient: 'claude-code' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'claude-add-server')).toBeDefined()- expect(steps.find((s) => s.id === 'claude-authenticate')).toBeDefined()- })-- test('should resolve default mcp steps for other clients', () => {- const state: ConnectState = { mode: 'mcp', mcpClient: 'unknown-client' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'configure-mcp')).toBeDefined()- })- })-- describe('skills install step', () => {- test('should include skills install step in all modes', () => {- const modes: ConnectState['mode'][] = ['framework', 'direct', 'orm', 'mcp']-- modes.forEach((mode) => {- const state: ConnectState = { mode }- const steps = resolveSteps(connectSchema, state)-- expect(- steps.find((s) => s.id === 'install-skills'),- `Mode "${mode}" should have skills install step`- ).toBeDefined()- })- })+describe('connect.schema:steps resolution', () => {+ test.each<[string, ConnectState, string[], string[]]>([+ [+ 'nextjs without shadcn',+ { mode: 'framework', framework: 'nextjs', frameworkUi: false },+ ['install', 'install-skills'],+ ['shadcn-add'],+ ],+ [+ 'nextjs with shadcn',+ { mode: 'framework', framework: 'nextjs', frameworkUi: true },+ ['shadcn-add', 'shadcn-env'],+ ['shadcn-explore'],+ ],+ [+ 'react without shadcn',+ { mode: 'framework', framework: 'react', frameworkUi: false },+ ['install'],+ ['shadcn-add'],+ ],+ [+ 'react with shadcn',+ { mode: 'framework', framework: 'react', frameworkUi: true },+ ['shadcn-add', 'shadcn-env'],+ [],+ ],+ ['other frameworks', { mode: 'framework', framework: 'remix' }, ['install', 'configure'], []],+ ['default direct mode', { mode: 'direct' }, ['connection'], []],+ [+ 'direct nodejs',+ { mode: 'direct', connectionType: 'nodejs' },+ ['direct-install', 'direct-files'],+ [],+ ],+ [+ 'direct golang',+ { mode: 'direct', connectionType: 'golang' },+ ['direct-install', 'direct-files'],+ [],+ ],+ ['direct python', { mode: 'direct', connectionType: 'python' }, ['direct-install'], []],+ ['direct dotnet', { mode: 'direct', connectionType: 'dotnet' }, ['direct-install'], []],+ ['orm prisma', { mode: 'orm', orm: 'prisma' }, ['install', 'configure', 'install-skills'], []],+ ['orm drizzle', { mode: 'orm', orm: 'drizzle' }, ['install', 'configure'], []],+ ['mcp cursor', { mode: 'mcp', mcpClient: 'cursor' }, ['configure-mcp', 'install-skills'], []],+ [+ 'mcp codex',+ { mode: 'mcp', mcpClient: 'codex' },+ ['codex-add-server', 'codex-authenticate', 'codex-verify'],+ [],+ ],+ [+ 'mcp claude-code',+ { mode: 'mcp', mcpClient: 'claude-code' },+ ['claude-add-server', 'claude-authenticate'],+ [],+ ],+ ['mcp unknown client', { mode: 'mcp', mcpClient: 'unknown-client' }, ['configure-mcp'], []],+ ])('resolves steps for %s', (_label, state, present, absent) => {+ const ids = stepIds(state)+ expect(ids).toEqual(expect.arrayContaining(present))+ absent.forEach((id) => expect(ids).not.toContain(id))+ })++ test.each<ConnectState['mode']>(['framework', 'direct', 'orm', 'mcp'])(+ 'includes the skills install step in %s mode',+ (mode) => {+ expect(stepIds({ mode })).toContain('install-skills')+ }+ )++ test.each<[ConnectState, string]>([+ [{ mode: 'framework', framework: 'nextjs', frameworkVariant: 'app' }, 'Install packages'],+ [{ mode: 'framework', framework: 'nextjs', frameworkVariant: 'pages' }, 'Install package'],+ [{ mode: 'framework', framework: 'remix' }, 'Install packages'],+ [{ mode: 'framework', framework: 'vuejs' }, 'Install package'],+ ])('install step title for %o is "%s"', (state, title) => {+ const installStep = resolveSteps(connectSchema, state).find((s) => s.id === 'install')+ expect(installStep?.title).toBe(title)})})@@ -381,87 +125,38 @@ describe('connect.schema:steps resolution', () => {// ============================================================================describe('connect.schema:step content paths', () => {- test('install step should have valid content path', () => {- const state: ConnectState = { mode: 'framework', framework: 'nextjs' }- const steps = resolveSteps(connectSchema, state)- const installStep = steps.find((s) => s.id === 'install')-- expect(installStep?.content).toBe('steps/install')- })-- test('shadcn command step should have valid content path', () => {- const state: ConnectState = { mode: 'framework', framework: 'nextjs', frameworkUi: true }- const steps = resolveSteps(connectSchema, state)- const shadcnStep = steps.find((s) => s.id === 'shadcn-add')-- expect(shadcnStep?.content).toBe('steps/shadcn/command')- })-- test('shadcn env step should have valid content path', () => {- const state: ConnectState = { mode: 'framework', framework: 'nextjs', frameworkUi: true }- const steps = resolveSteps(connectSchema, state)- const envStep = steps.find((s) => s.id === 'shadcn-env')-- expect(envStep?.content).toBe('steps/shadcn/env')- })-- test('direct connection step should have valid content path', () => {- const state: ConnectState = { mode: 'direct' }- const steps = resolveSteps(connectSchema, state)- const connectionStep = steps.find((s) => s.id === 'connection')-- expect(connectionStep?.content).toBe('steps/direct-connection')- })-- test('skills install step should have valid content path', () => {- const state: ConnectState = { mode: 'framework' }- const steps = resolveSteps(connectSchema, state)- const skillsStep = steps.find((s) => s.id === 'install-skills')-- expect(skillsStep?.content).toBe('steps/skills-install')- })-- test('orm configure step should use template content path', () => {- // The ORM configure step uses a template {{orm}} that gets resolved- // by the dynamic import system, not the resolver- const state: ConnectState = { mode: 'orm', orm: 'prisma' }- const steps = resolveSteps(connectSchema, state)- const configureStep = steps.find((s) => s.id === 'configure')-- // The content path uses template syntax for the component loader- expect(configureStep?.content).toBe('{{orm}}')- })-- test('mcp cursor configure step should have valid content path', () => {- const state: ConnectState = { mode: 'mcp', mcpClient: 'cursor' }- const steps = resolveSteps(connectSchema, state)- const configureStep = steps.find((s) => s.id === 'configure-mcp')-- expect(configureStep?.content).toBe('steps/mcp/cursor')- })-- test('codex steps should have valid content paths', () => {- const state: ConnectState = { mode: 'mcp', mcpClient: 'codex' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'codex-add-server')?.content).toBe(- 'steps/mcp/codex/add-server'- )- expect(steps.find((s) => s.id === 'codex-authenticate')?.content).toBe(- 'steps/mcp/codex/authenticate'- )- expect(steps.find((s) => s.id === 'codex-verify')?.content).toBe('steps/mcp/codex/verify')- })-- test('claude-code steps should have valid content paths', () => {- const state: ConnectState = { mode: 'mcp', mcpClient: 'claude-code' }- const steps = resolveSteps(connectSchema, state)-- expect(steps.find((s) => s.id === 'claude-add-server')?.content).toBe(- 'steps/mcp/claude-code/add-server'- )- expect(steps.find((s) => s.id === 'claude-authenticate')?.content).toBe(- 'steps/mcp/claude-code/authenticate'- )+ test.each<[ConnectState, string, string]>([+ [{ mode: 'framework', framework: 'nextjs' }, 'install', 'steps/install'],+ [+ { mode: 'framework', framework: 'nextjs', frameworkUi: true },+ 'shadcn-add',+ 'steps/shadcn/command',+ ],+ [+ { mode: 'framework', framework: 'nextjs', frameworkUi: true },+ 'shadcn-env',+ 'steps/shadcn/env',+ ],+ [{ mode: 'direct' }, 'connection', 'steps/direct-connection'],+ [{ mode: 'framework' }, 'install-skills', 'steps/skills-install'],+ // The ORM configure step uses a {{orm}} template resolved by the dynamic import system+ [{ mode: 'orm', orm: 'prisma' }, 'configure', '{{orm}}'],+ [{ mode: 'mcp', mcpClient: 'cursor' }, 'configure-mcp', 'steps/mcp/cursor'],+ [{ mode: 'mcp', mcpClient: 'codex' }, 'codex-add-server', 'steps/mcp/codex/add-server'],+ [{ mode: 'mcp', mcpClient: 'codex' }, 'codex-authenticate', 'steps/mcp/codex/authenticate'],+ [{ mode: 'mcp', mcpClient: 'codex' }, 'codex-verify', 'steps/mcp/codex/verify'],+ [+ { mode: 'mcp', mcpClient: 'claude-code' },+ 'claude-add-server',+ 'steps/mcp/claude-code/add-server',+ ],+ [+ { mode: 'mcp', mcpClient: 'claude-code' },+ 'claude-authenticate',+ 'steps/mcp/claude-code/authenticate',+ ],+ ])('%o: step "%s" uses content "%s"', (state, stepId, content) => {+ const step = resolveSteps(connectSchema, state).find((s) => s.id === stepId)+ expect(step?.content).toBe(content)})})diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.revealRace.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.revealRace.test.tsdeleted file mode 100644index 475c3e63778..00000000000--- a/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.revealRace.test.ts+++ /dev/null@@ -1,103 +0,0 @@-import { act, renderHook } from '@testing-library/react'-import { beforeEach, describe, expect, it, vi } from 'vitest'--import { useConnectServerEnv } from '../useConnectServerEnv'-import { getAPIKeysById } from '@/data/api-keys/api-key-id-query'-import { useAPIKeys } from '@/data/api-keys/api-keys-query'-import { useProjectApiUrl } from '@/data/config/project-endpoint-query'-import { useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'--// Uses the real useRevealedSecret (not mocked) so the requestId invalidation-// in clear() actually interacts with revealPromiseRef in useConnectServerEnv.-vi.mock('@/hooks/misc/useCheckPermissionsV2', () => ({- useAsyncCheckPermissionsV2: vi.fn(),- FGA_PERMISSIONS: {- PROJECT: {},- },-}))-vi.mock('@/data/config/project-endpoint-query', () => ({- useProjectApiUrl: vi.fn(),-}))-vi.mock('@/data/api-keys/api-keys-query', () => ({- useAPIKeys: vi.fn(),-}))-vi.mock('@/data/api-keys/api-key-id-query', () => ({- getAPIKeysById: vi.fn(),-}))--const SECRET_KEY = { id: 'secret-id', api_key: 'sb_secret_abcdefghijklmnopqrstuv' }-const SECRET_FULL = 'sb_secret_abcdefghijklmnopqrstuv_full'--function deferred<T>() {- let resolve!: (value: T) => void- const promise = new Promise<T>((res) => {- resolve = res- })- return { promise, resolve }-}--describe('useConnectServerEnv secret reveal (real useRevealedSecret)', () => {- beforeEach(() => {- vi.mocked(useAsyncCheckPermissionsV2).mockReturnValue({- can: true,- isLoading: false,- } as any)- vi.mocked(useProjectApiUrl).mockReturnValue({- data: 'https://test.supabase.co',- isPending: false,- } as any)- vi.mocked(useAPIKeys).mockReturnValue({- data: { secretKey: SECRET_KEY, publishableKey: { api_key: 'sb_publishable_x' } },- isLoading: false,- } as any)- })-- it('fires a fresh request on reveal after a hide interrupts an in-flight reveal, instead of reusing the invalidated promise', async () => {- const first = deferred<{ api_key: string }>()- const second = deferred<{ api_key: string }>()- vi.mocked(getAPIKeysById).mockReturnValueOnce(first.promise as any)- vi.mocked(getAPIKeysById).mockReturnValueOnce(second.promise as any)-- const { result } = renderHook(() => useConnectServerEnv())-- // Reveal is clicked, kicking off the first (never-resolving-yet) request.- let togglePromise1!: Promise<void>- act(() => {- togglePromise1 = result.current.secret.toggle()- })- expect(result.current.secret.isRevealed).toBe(true)-- // Hide is clicked before that request settles.- act(() => {- result.current.secret.toggle()- })- expect(result.current.secret.isRevealed).toBe(false)-- // Reveal is clicked again, still before the first request settles.- let togglePromise2!: Promise<void>- act(() => {- togglePromise2 = result.current.secret.toggle()- })- expect(result.current.secret.isRevealed).toBe(true)-- // A brand new request must have been issued rather than reusing the- // (now-invalidated) first one.- expect(getAPIKeysById).toHaveBeenCalledTimes(2)-- // The stale first request finally resolves; it must be ignored.- await act(async () => {- first.resolve({ api_key: SECRET_FULL + '_stale' })- await togglePromise1- })-- // The second (live) request resolves with the real value.- await act(async () => {- second.resolve({ api_key: SECRET_FULL })- await togglePromise2- })-- expect(result.current.secret.isRevealed).toBe(true)- expect(result.current.secret.isRevealing).toBe(false)- expect(result.current.secret.displayValue).toBe(SECRET_FULL)- })-})diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.test.tsindex 699e95d2193..b792e4072c5 100644--- a/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectServerEnv.test.ts@@ -1,8 +1,10 @@+// @vitest-environment jsdomimport { act, renderHook } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { useConnectServerEnv } from '../useConnectServerEnv'import { useRevealedSecret } from '@/components/interfaces/APIKeys/useRevealedSecret'+import { getAPIKeysById } from '@/data/api-keys/api-key-id-query'import { useAPIKeys } from '@/data/api-keys/api-keys-query'import { useProjectApiUrl } from '@/data/config/project-endpoint-query'import { useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'@@ -19,6 +21,9 @@ vi.mock('@/data/config/project-endpoint-query', () => ({vi.mock('@/data/api-keys/api-keys-query', () => ({useAPIKeys: vi.fn(),}))+vi.mock('@/data/api-keys/api-key-id-query', () => ({+ getAPIKeysById: vi.fn(),+}))vi.mock('@/components/interfaces/APIKeys/useRevealedSecret', () => ({useRevealedSecret: vi.fn(),}))@@ -36,24 +41,26 @@ function deferred<T>() {return { promise, resolve, reject }}+beforeEach(() => {+ vi.mocked(useAsyncCheckPermissionsV2).mockReturnValue({+ can: true,+ isLoading: false,+ } as any)+ vi.mocked(useProjectApiUrl).mockReturnValue({+ data: 'https://test.supabase.co',+ isPending: false,+ } as any)+ vi.mocked(useAPIKeys).mockReturnValue({+ data: { secretKey: SECRET_KEY, publishableKey: { api_key: 'sb_publishable_x' } },+ isLoading: false,+ } as any)+})+describe('useConnectServerEnv secret reveal', () => {const clearMock = vi.fn()let revealMock: ReturnType<typeof vi.fn>beforeEach(() => {- vi.mocked(useAsyncCheckPermissionsV2).mockReturnValue({- can: true,- isLoading: false,- } as any)- vi.mocked(useProjectApiUrl).mockReturnValue({- data: 'https://test.supabase.co',- isPending: false,- } as any)- vi.mocked(useAPIKeys).mockReturnValue({- data: { secretKey: SECRET_KEY, publishableKey: { api_key: 'sb_publishable_x' } },- isLoading: false,- } as any)-clearMock.mockClear()revealMock = vi.fn()vi.mocked(useRevealedSecret).mockReturnValue({@@ -165,3 +172,63 @@ describe('useConnectServerEnv secret reveal', () => {expect(clearMock).toHaveBeenCalledTimes(1)})})++// Uses the real useRevealedSecret so the requestId invalidation in clear() actually interacts+// with revealPromiseRef in useConnectServerEnv.+describe('useConnectServerEnv secret reveal (real useRevealedSecret)', () => {+ beforeEach(async () => {+ const actual = await vi.importActual<+ typeof import('@/components/interfaces/APIKeys/useRevealedSecret')+ >('@/components/interfaces/APIKeys/useRevealedSecret')+ vi.mocked(useRevealedSecret).mockImplementation(actual.useRevealedSecret)+ })++ it('fires a fresh request on reveal after a hide interrupts an in-flight reveal, instead of reusing the invalidated promise', async () => {+ const first = deferred<{ api_key: string }>()+ const second = deferred<{ api_key: string }>()+ vi.mocked(getAPIKeysById).mockReturnValueOnce(first.promise as any)+ vi.mocked(getAPIKeysById).mockReturnValueOnce(second.promise as any)++ const { result } = renderHook(() => useConnectServerEnv())++ // Reveal is clicked, kicking off the first (never-resolving-yet) request.+ let togglePromise1!: Promise<void>+ act(() => {+ togglePromise1 = result.current.secret.toggle()+ })+ expect(result.current.secret.isRevealed).toBe(true)++ // Hide is clicked before that request settles.+ act(() => {+ result.current.secret.toggle()+ })+ expect(result.current.secret.isRevealed).toBe(false)++ // Reveal is clicked again, still before the first request settles.+ let togglePromise2!: Promise<void>+ act(() => {+ togglePromise2 = result.current.secret.toggle()+ })+ expect(result.current.secret.isRevealed).toBe(true)++ // A brand new request must have been issued rather than reusing the+ // (now-invalidated) first one.+ expect(getAPIKeysById).toHaveBeenCalledTimes(2)++ // The stale first request finally resolves; it must be ignored.+ await act(async () => {+ first.resolve({ api_key: SECRET_FULL + '_stale' })+ await togglePromise1+ })++ // The second (live) request resolves with the real value.+ await act(async () => {+ second.resolve({ api_key: SECRET_FULL })+ await togglePromise2+ })++ expect(result.current.secret.isRevealed).toBe(true)+ expect(result.current.secret.isRevealing).toBe(false)+ expect(result.current.secret.displayValue).toBe(SECRET_FULL)+ })+})diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectSheetShortcut.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectSheetShortcut.test.tsindex 4570149bbcd..7365afb15f9 100644--- a/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectSheetShortcut.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectSheetShortcut.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { renderHook } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'diff --git a/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectState.test.ts b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectState.test.tsindex 02cda9fc3a1..a0e2b288d94 100644--- a/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectState.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/__tests__/useConnectState.test.ts@@ -1,5 +1,6 @@+// @vitest-environment jsdomimport { act, renderHook } from '@testing-library/react'-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'+import { afterEach, describe, expect, test, vi } from 'vitest'import { useConnectState } from '../useConnectState'@@ -27,44 +28,40 @@ vi.mock('@/hooks/misc/useDeploymentMode', () => ({useDeploymentMode: () => deploymentModeMock,}))+type DeploymentMode = typeof deploymentModeMock+const PLATFORM: DeploymentMode = { isPlatform: true, isCli: false, isSelfHosted: false }+const CLI: DeploymentMode = { isPlatform: false, isCli: true, isSelfHosted: false }+const SELF_HOSTED: DeploymentMode = { isPlatform: false, isCli: false, isSelfHosted: true }++const activeFieldIds = (result: { current: ReturnType<typeof useConnectState> }) =>+ result.current.activeFields.map((f) => f.id)+describe('useConnectState', () => {// ============================================================================// Initial State Tests// ============================================================================describe('initial state', () => {- test('should initialize with framework mode by default', () => {- const { result } = renderHook(() => useConnectState())- expect(result.current.state.mode).toBe('framework')- })-- test('should initialize with nextjs as default framework', () => {- const { result } = renderHook(() => useConnectState())- expect(result.current.state.framework).toBe('nextjs')- })-- test('should initialize with app variant for nextjs', () => {+ test('should initialize with framework defaults (Next.js app router + supabase-js)', () => {const { result } = renderHook(() => useConnectState())- expect(result.current.state.frameworkVariant).toBe('app')- })-- test('should initialize with supabasejs library', () => {- const { result } = renderHook(() => useConnectState())- expect(result.current.state.library).toBe('supabasejs')+ expect(result.current.state).toMatchObject({+ mode: 'framework',+ framework: 'nextjs',+ frameworkVariant: 'app',+ library: 'supabasejs',+ })})- test('should accept initial state override', () => {- const { result } = renderHook(() =>+ test('should merge an initial state override with defaults', () => {+ const { result: direct } = renderHook(() =>useConnectState({ mode: 'direct', connectionMethod: 'transaction' }))- expect(result.current.state.mode).toBe('direct')- expect(result.current.state.connectionMethod).toBe('transaction')- })+ expect(direct.current.state.mode).toBe('direct')+ expect(direct.current.state.connectionMethod).toBe('transaction')- test('should merge initial state with defaults', () => {- const { result } = renderHook(() => useConnectState({ framework: 'react' }))- expect(result.current.state.mode).toBe('framework')- expect(result.current.state.framework).toBe('react')+ const { result: react } = renderHook(() => useConnectState({ framework: 'react' }))+ expect(react.current.state.mode).toBe('framework')+ expect(react.current.state.framework).toBe('react')})})@@ -73,7 +70,7 @@ describe('useConnectState', () => {// ============================================================================describe('setMode', () => {- test('should switch to direct mode', () => {+ test('should switch to direct mode and initialize its defaults', () => {const { result } = renderHook(() => useConnectState())act(() => {@@ -81,55 +78,33 @@ describe('useConnectState', () => {})expect(result.current.state.mode).toBe('direct')- })-- test('should initialize direct mode defaults when switching', () => {- const { result } = renderHook(() => useConnectState())-- act(() => {- result.current.setMode('direct')- })-expect(result.current.state.connectionMethod).toBeDefined()expect(result.current.state.connectionType).toBeDefined()})- test('should switch to orm mode and initialize defaults', () => {- const { result } = renderHook(() => useConnectState())-- act(() => {- result.current.setMode('orm')- })-- expect(result.current.state.mode).toBe('orm')- expect(result.current.state.orm).toBe('prisma')- })-- test('should switch to mcp mode and initialize defaults', () => {+ test.each([+ ['orm', 'orm'],+ ['mcp', 'mcpClient'],+ ] as const)('should switch to %s mode and initialize %s', (mode, field) => {const { result } = renderHook(() => useConnectState())act(() => {- result.current.setMode('mcp')+ result.current.setMode(mode)})- expect(result.current.state.mode).toBe('mcp')- expect(result.current.state.mcpClient).toBeDefined()+ expect(result.current.state.mode).toBe(mode)+ expect(result.current.state[field]).toBeDefined()})test('should preserve framework state when switching back to framework mode', () => {const { result } = renderHook(() => useConnectState())- // Change frameworkact(() => {result.current.updateField('framework', 'react')})-- // Switch to directact(() => {result.current.setMode('direct')})-- // Switch back to frameworkact(() => {result.current.setMode('framework')})@@ -143,38 +118,37 @@ describe('useConnectState', () => {// ============================================================================describe('updateField', () => {- test('should update framework selection', () => {- const { result } = renderHook(() => useConnectState())+ test.each<[Parameters<typeof useConnectState>[0], string, string | boolean]>([+ [undefined, 'framework', 'react'],+ [{ mode: 'direct' }, 'connectionMethod', 'transaction'],+ [{ mode: 'mcp' }, 'mcpClient', 'codex'],+ [{ mode: 'orm' }, 'orm', 'drizzle'],+ [undefined, 'frameworkUi', true],+ ])('%o: should update %s', (initial, fieldId, value) => {+ const { result } = renderHook(() => useConnectState(initial))act(() => {- result.current.updateField('framework', 'react')+ result.current.updateField(fieldId, value)})- expect(result.current.state.framework).toBe('react')+ expect(result.current.state[fieldId]).toBe(value)})- test('should cascade variant reset when changing framework', () => {+ test("should reset the variant to the new framework's first variant", () => {const { result } = renderHook(() => useConnectState())-- // Start with nextjs which has variantsexpect(result.current.state.frameworkVariant).toBe('app')- // Switch to a framework with multiple variantsact(() => {result.current.updateField('framework', 'react')})- // Should have the first variant of reactexpect(result.current.state.frameworkVariant).toBeDefined()+ expect(result.current.state.frameworkVariant).not.toBe('app')})test('should remove variant when switching to framework without variants', () => {const { result } = renderHook(() => useConnectState())- // Start with nextjs which has variants- expect(result.current.state.frameworkVariant).toBe('app')-- // Switch to remix which has no variantsact(() => {result.current.updateField('framework', 'remix')})@@ -182,26 +156,6 @@ describe('useConnectState', () => {expect(result.current.state.frameworkVariant).toBeUndefined()})- test('should update library when variant changes', () => {- const { result } = renderHook(() => useConnectState())-- act(() => {- result.current.updateField('frameworkVariant', 'pages')- })-- expect(result.current.state.library).toBe('supabasejs')- })-- test('should update connection method', () => {- const { result } = renderHook(() => useConnectState({ mode: 'direct' }))-- act(() => {- result.current.updateField('connectionMethod', 'transaction')- })-- expect(result.current.state.connectionMethod).toBe('transaction')- })-test('should clear useSharedPooler when connectionMethod changes to direct', () => {const { result } = renderHook(() =>useConnectState({@@ -215,40 +169,9 @@ describe('useConnectState', () => {result.current.updateField('connectionMethod', 'direct')})- // useSharedPooler is cleared because it depends on connectionMethod: ['transaction']- // When the dependency is not satisfied, the field is removed from state+ // useSharedPooler depends on connectionMethod: ['transaction'], so it is removedexpect(result.current.state.useSharedPooler).toBeUndefined()})-- test('should update MCP client', () => {- const { result } = renderHook(() => useConnectState({ mode: 'mcp' }))-- act(() => {- result.current.updateField('mcpClient', 'codex')- })-- expect(result.current.state.mcpClient).toBe('codex')- })-- test('should update boolean fields', () => {- const { result } = renderHook(() => useConnectState())-- act(() => {- result.current.updateField('frameworkUi', true)- })-- expect(result.current.state.frameworkUi).toBe(true)- })-- test('should update ORM selection', () => {- const { result } = renderHook(() => useConnectState({ mode: 'orm' }))-- act(() => {- result.current.updateField('orm', 'drizzle')- })-- expect(result.current.state.orm).toBe('drizzle')- })})// ============================================================================@@ -256,161 +179,57 @@ describe('useConnectState', () => {// ============================================================================describe('activeFields', () => {- test('should return framework mode fields', () => {- const { result } = renderHook(() => useConnectState())-- const fieldIds = result.current.activeFields.map((f) => f.id)- expect(fieldIds).toContain('framework')- })-- test('should include variant field for nextjs', () => {- const { result } = renderHook(() => useConnectState({ framework: 'nextjs' }))-- const fieldIds = result.current.activeFields.map((f) => f.id)- expect(fieldIds).toContain('frameworkVariant')- })-- test('should include frameworkUi field for nextjs', () => {- const { result } = renderHook(() => useConnectState({ framework: 'nextjs' }))-- const fieldIds = result.current.activeFields.map((f) => f.id)- expect(fieldIds).toContain('frameworkUi')- })-- test('should not include frameworkUi for non-nextjs/react frameworks', () => {- const { result } = renderHook(() => useConnectState({ framework: 'remix' }))-- const fieldIds = result.current.activeFields.map((f) => f.id)- expect(fieldIds).not.toContain('frameworkUi')- })-- test('should return direct mode fields', () => {- const { result } = renderHook(() => useConnectState({ mode: 'direct' }))-- const fieldIds = result.current.activeFields.map((f) => f.id)- expect(fieldIds).toContain('connectionMethod')- expect(fieldIds).toContain('connectionType')- })-- test('should show useSharedPooler only for transaction connection method when user has dedicated_pooler entitlement', async () => {- const { useCheckEntitlements } = await import('@/hooks/misc/useCheckEntitlements')- vi.mocked(useCheckEntitlements).mockReturnValue({ hasAccess: true } as any)-- const { result } = renderHook(() =>- useConnectState({ mode: 'direct', connectionMethod: 'transaction' })- )-- const fieldIds = result.current.activeFields.map((f) => f.id)- expect(fieldIds).toContain('useSharedPooler')- })-- test('should hide useSharedPooler even if using transaction method when user lacks dedicated_pooler entitlement', async () => {- const { useCheckEntitlements } = await import('@/hooks/misc/useCheckEntitlements')- vi.mocked(useCheckEntitlements).mockReturnValue({ hasAccess: false } as any)-- const { result } = renderHook(() =>- useConnectState({ mode: 'direct', connectionMethod: 'transaction' })- )-- const fieldIds = result.current.activeFields.map((f) => f.id)- expect(fieldIds).not.toContain('useSharedPooler')- })-- test('should hide useSharedPooler for direct connection method', () => {- const { result } = renderHook(() =>- useConnectState({ mode: 'direct', connectionMethod: 'direct' })- )-- const fieldIds = result.current.activeFields.map((f) => f.id)- expect(fieldIds).not.toContain('useSharedPooler')- })-- test('should return orm mode fields', () => {- const { result } = renderHook(() => useConnectState({ mode: 'orm' }))-- const fieldIds = result.current.activeFields.map((f) => f.id)- expect(fieldIds).toContain('orm')- })+ test.each<[Parameters<typeof useConnectState>[0], string[], string[]]>([+ [{ framework: 'nextjs' }, ['framework', 'frameworkVariant', 'frameworkUi'], []],+ [{ framework: 'remix' }, ['framework'], ['frameworkUi']],+ [+ { mode: 'direct', connectionMethod: 'direct' },+ ['connectionMethod', 'connectionType'],+ ['useSharedPooler'],+ ],+ [{ mode: 'orm' }, ['orm'], []],+ [{ mode: 'mcp' }, ['mcpClient', 'mcpReadonly'], []],+ ])('%o: includes %j, excludes %j', (initial, included, excluded) => {+ const { result } = renderHook(() => useConnectState(initial))++ const fieldIds = activeFieldIds(result)+ expect(fieldIds).toEqual(expect.arrayContaining(included))+ excluded.forEach((id) => expect(fieldIds).not.toContain(id))+ })++ // `true` last so the module-level entitlement mock is left at its default+ test.each([+ [false, false],+ [true, true],+ ])(+ 'transaction method with dedicated_pooler entitlement %s shows useSharedPooler: %s',+ async (hasAccess, isShown) => {+ const { useCheckEntitlements } = await import('@/hooks/misc/useCheckEntitlements')+ vi.mocked(useCheckEntitlements).mockReturnValue({ hasAccess } as any)- test('should return mcp mode fields', () => {- const { result } = renderHook(() => useConnectState({ mode: 'mcp' }))+ const { result } = renderHook(() =>+ useConnectState({ mode: 'direct', connectionMethod: 'transaction' })+ )- const fieldIds = result.current.activeFields.map((f) => f.id)- expect(fieldIds).toContain('mcpClient')- expect(fieldIds).toContain('mcpReadonly')- })+ expect(activeFieldIds(result).includes('useSharedPooler')).toBe(isShown)+ }+ )})// ============================================================================- // Resolved Steps Tests+ // Resolved Steps Tests (resolution itself is covered in connect.schema.test.ts)// ============================================================================describe('resolvedSteps', () => {- test('should resolve steps for framework mode', () => {- const { result } = renderHook(() => useConnectState())-- expect(result.current.resolvedSteps.length).toBeGreaterThan(0)- })-- test('should have install step for framework mode', () => {+ test('should resolve steps from the current state', () => {const { result } = renderHook(() => useConnectState())+ const stepIds = () => result.current.resolvedSteps.map((s) => s.id)+ expect(stepIds()).toEqual(expect.arrayContaining(['install', 'install-skills']))- const stepIds = result.current.resolvedSteps.map((s) => s.id)- expect(stepIds).toContain('install')- })-- test('should resolve different steps for mcp mode', () => {- const { result } = renderHook(() => useConnectState({ mode: 'mcp' }))-- const stepIds = result.current.resolvedSteps.map((s) => s.id)- // MCP mode (defaults to claude-code) should have claude-add-server step- expect(stepIds.some((id) => id.includes('claude') || id.includes('mcp'))).toBe(true)- })-- test('should resolve different steps for different mcp clients', () => {- const { result: cursorResult } = renderHook(() =>- useConnectState({ mode: 'mcp', mcpClient: 'cursor' })- )- const { result: codexResult } = renderHook(() =>- useConnectState({ mode: 'mcp', mcpClient: 'codex' })- )-- // Codex has more steps than cursor- expect(codexResult.current.resolvedSteps.length).toBeGreaterThanOrEqual(- cursorResult.current.resolvedSteps.length- )- })-- test('should include skills install step', () => {- const { result } = renderHook(() => useConnectState())-- const stepIds = result.current.resolvedSteps.map((s) => s.id)- expect(stepIds).toContain('install-skills')- })-- test('should resolve steps for direct mode', () => {- const { result } = renderHook(() => useConnectState({ mode: 'direct' }))-- expect(result.current.resolvedSteps.length).toBeGreaterThan(0)- })-- test('should resolve steps for orm mode', () => {- const { result } = renderHook(() => useConnectState({ mode: 'orm' }))-- expect(result.current.resolvedSteps.length).toBeGreaterThan(0)- const stepIds = result.current.resolvedSteps.map((s) => s.id)- expect(stepIds).toContain('install')- expect(stepIds).toContain('configure')- })-- test('should resolve shadcn steps when frameworkUi is true', () => {- const { result } = renderHook(() =>- useConnectState({ framework: 'nextjs', frameworkUi: true })- )-- const stepIds = result.current.resolvedSteps.map((s) => s.id)- expect(stepIds).toContain('shadcn-add')- expect(stepIds).toContain('shadcn-env')+ act(() => {+ result.current.updateField('frameworkUi', true)+ })+ expect(stepIds()).toEqual(expect.arrayContaining(['shadcn-add', 'shadcn-env']))})})@@ -419,80 +238,27 @@ describe('useConnectState', () => {// ============================================================================describe('getFieldOptions', () => {- test('should return framework options', () => {- const { result } = renderHook(() => useConnectState())-- const options = result.current.getFieldOptions('framework')- expect(options.length).toBeGreaterThan(0)- expect(options.some((o) => o.value === 'nextjs')).toBe(true)- expect(options.some((o) => o.value === 'react')).toBe(true)- })-- test('should return variant options for nextjs', () => {- const { result } = renderHook(() => useConnectState({ framework: 'nextjs' }))-- const options = result.current.getFieldOptions('frameworkVariant')- expect(options.length).toBeGreaterThan(0)- expect(options.some((o) => o.value === 'app')).toBe(true)- expect(options.some((o) => o.value === 'pages')).toBe(true)- })-- test('should return empty variant options for frameworks without variants', () => {- const { result } = renderHook(() => useConnectState({ framework: 'remix' }))-- const options = result.current.getFieldOptions('frameworkVariant')- expect(options).toEqual([])- })-- test('should return connection method options', () => {- const { result } = renderHook(() => useConnectState({ mode: 'direct' }))-- const options = result.current.getFieldOptions('connectionMethod')- expect(options.length).toBeGreaterThan(0)- expect(options.some((o) => o.value === 'direct')).toBe(true)- expect(options.some((o) => o.value === 'transaction')).toBe(true)- })-- test('should return connection type options', () => {- const { result } = renderHook(() => useConnectState({ mode: 'direct' }))-- const options = result.current.getFieldOptions('connectionType')- expect(options.length).toBeGreaterThan(0)- expect(options.some((o) => o.value === 'uri')).toBe(true)- expect(options.some((o) => o.value === 'psql')).toBe(true)- })-- test('should return ORM options', () => {- const { result } = renderHook(() => useConnectState({ mode: 'orm' }))-- const options = result.current.getFieldOptions('orm')- expect(options.length).toBeGreaterThan(0)- expect(options.some((o) => o.value === 'prisma')).toBe(true)- expect(options.some((o) => o.value === 'drizzle')).toBe(true)- })-- test('should return MCP client options', () => {- const { result } = renderHook(() => useConnectState({ mode: 'mcp' }))-- const options = result.current.getFieldOptions('mcpClient')- expect(options.length).toBeGreaterThan(0)- expect(options.some((o) => o.value === 'cursor')).toBe(true)- })-- test('should return empty array for unknown field', () => {- const { result } = renderHook(() => useConnectState())-- const options = result.current.getFieldOptions('unknownField')- expect(options).toEqual([])- })-- test('should return library options for selected framework', () => {- const { result } = renderHook(() =>- useConnectState({ framework: 'nextjs', frameworkVariant: 'app' })- )-- const options = result.current.getFieldOptions('library')- expect(options.length).toBeGreaterThan(0)+ test.each<[Parameters<typeof useConnectState>[0], string, string[]]>([+ [undefined, 'framework', ['nextjs', 'react']],+ [{ framework: 'nextjs' }, 'frameworkVariant', ['app', 'pages']],+ [{ mode: 'direct' }, 'connectionMethod', ['direct', 'transaction']],+ [{ mode: 'direct' }, 'connectionType', ['uri', 'psql']],+ [{ mode: 'orm' }, 'orm', ['prisma', 'drizzle']],+ [{ mode: 'mcp' }, 'mcpClient', ['cursor']],+ [{ framework: 'nextjs', frameworkVariant: 'app' }, 'library', ['supabasejs']],+ ])('%o: %s options include %j', (initial, fieldId, values) => {+ const { result } = renderHook(() => useConnectState(initial))++ const options = result.current.getFieldOptions(fieldId).map((o) => o.value)+ expect(options).toEqual(expect.arrayContaining(values))+ })++ test.each<[Parameters<typeof useConnectState>[0], string]>([+ [{ framework: 'remix' }, 'frameworkVariant'],+ [undefined, 'unknownField'],+ ])('%o: returns no options for %s', (initial, fieldId) => {+ const { result } = renderHook(() => useConnectState(initial))+ expect(result.current.getFieldOptions(fieldId)).toEqual([])})})@@ -639,170 +405,60 @@ describe('useConnectState', () => {})})- // ============================================================================- // Schema Access Tests- // ============================================================================-- describe('schema', () => {- test('should expose the connect schema', () => {- const { result } = renderHook(() => useConnectState())-- expect(result.current.schema).toBeDefined()- expect(result.current.schema.modes).toBeDefined()- expect(result.current.schema.fields).toBeDefined()- expect(result.current.schema.steps).toBeDefined()- })-- test('should have all expected modes in schema', () => {- const { result } = renderHook(() => useConnectState())-- const modeIds = result.current.schema.modes.map((m) => m.id)- expect(modeIds).toContain('framework')- expect(modeIds).toContain('direct')- expect(modeIds).toContain('orm')- expect(modeIds).toContain('mcp')- })- })-// ============================================================================// Deployment-Mode-Aware Tests// ============================================================================describe('deployment mode', () => {- beforeEach(() => {- Object.assign(deploymentModeMock, {- isPlatform: true,- isCli: false,- isSelfHosted: false,- })- })-afterEach(() => {- Object.assign(deploymentModeMock, {- isPlatform: true,- isCli: false,- isSelfHosted: false,- })+ Object.assign(deploymentModeMock, PLATFORM)})- describe('connectionMethod options filtering', () => {- test('platform exposes direct, transaction and session', () => {- Object.assign(deploymentModeMock, {- isPlatform: true,- isCli: false,- isSelfHosted: false,- })- const { result } = renderHook(() => useConnectState({ mode: 'direct' }))- const values = result.current.getFieldOptions('connectionMethod').map((o) => o.value)- expect(values).toEqual(['direct', 'transaction', 'session'])- })-- test('CLI exposes only direct', () => {- Object.assign(deploymentModeMock, {- isPlatform: false,- isCli: true,- isSelfHosted: false,- })- const { result } = renderHook(() => useConnectState({ mode: 'direct' }))- const values = result.current.getFieldOptions('connectionMethod').map((o) => o.value)- expect(values).toEqual(['direct'])- })-- test('self-hosted exposes session, transaction, direct (session first)', () => {- Object.assign(deploymentModeMock, {- isPlatform: false,- isCli: false,- isSelfHosted: true,- })- const { result } = renderHook(() => useConnectState({ mode: 'direct' }))- const values = result.current.getFieldOptions('connectionMethod').map((o) => o.value)- expect(values).toEqual(['session', 'transaction', 'direct'])- })-- test('self-hosted overrides direct method description', () => {- Object.assign(deploymentModeMock, {- isPlatform: false,- isCli: false,- isSelfHosted: true,- })- const { result } = renderHook(() => useConnectState({ mode: 'direct' }))- const directOption = result.current- .getFieldOptions('connectionMethod')- .find((o) => o.value === 'direct')- expect(directOption?.description).toBe('Manually configurable for self-hosted Supabase.')- })-- test('self-hosted overrides session method description', () => {- Object.assign(deploymentModeMock, {- isPlatform: false,- isCli: false,- isSelfHosted: true,- })- const { result } = renderHook(() => useConnectState({ mode: 'direct' }))- const sessionOption = result.current- .getFieldOptions('connectionMethod')- .find((o) => o.value === 'session')- expect(sessionOption?.description).toBe(- 'Supavisor (default pooler for self-hosted Supabase).'- )- })+ test.each([+ ['platform', PLATFORM, ['direct', 'transaction', 'session']],+ ['CLI', CLI, ['direct']],+ ['self-hosted', SELF_HOSTED, ['session', 'transaction', 'direct']],+ ])('%s exposes connectionMethod options %j', (_label, mode, expected) => {+ Object.assign(deploymentModeMock, mode)+ const { result } = renderHook(() => useConnectState({ mode: 'direct' }))+ const values = result.current.getFieldOptions('connectionMethod').map((o) => o.value)+ expect(values).toEqual(expected)})- describe('setMode default for connectionMethod', () => {- test('platform defaults to direct', () => {- Object.assign(deploymentModeMock, {- isPlatform: true,- isCli: false,- isSelfHosted: false,- })- const { result } = renderHook(() => useConnectState({ mode: 'framework' }))- act(() => {- result.current.setMode('direct')- })- expect(result.current.state.connectionMethod).toBe('direct')- })-- test('CLI defaults to direct', () => {- Object.assign(deploymentModeMock, {- isPlatform: false,- isCli: true,- isSelfHosted: false,- })- const { result } = renderHook(() => useConnectState({ mode: 'framework' }))- act(() => {- result.current.setMode('direct')- })- expect(result.current.state.connectionMethod).toBe('direct')- })+ test('self-hosted overrides direct and session method descriptions', () => {+ Object.assign(deploymentModeMock, SELF_HOSTED)+ const { result } = renderHook(() => useConnectState({ mode: 'direct' }))+ const options = result.current.getFieldOptions('connectionMethod')+ expect(options.find((o) => o.value === 'direct')?.description).toBe(+ 'Manually configurable for self-hosted Supabase.'+ )+ expect(options.find((o) => o.value === 'session')?.description).toBe(+ 'Supavisor (default pooler for self-hosted Supabase).'+ )+ })- test('self-hosted defaults to session', () => {- Object.assign(deploymentModeMock, {- isPlatform: false,- isCli: false,- isSelfHosted: true,- })- const { result } = renderHook(() => useConnectState({ mode: 'framework' }))- act(() => {- result.current.setMode('direct')- })- expect(result.current.state.connectionMethod).toBe('session')+ test.each([+ ['platform', PLATFORM, 'direct'],+ ['CLI', CLI, 'direct'],+ ['self-hosted', SELF_HOSTED, 'session'],+ ])('setMode("direct") on %s defaults connectionMethod to %s', (_label, mode, expected) => {+ Object.assign(deploymentModeMock, mode)+ const { result } = renderHook(() => useConnectState({ mode: 'framework' }))+ act(() => {+ result.current.setMode('direct')})+ expect(result.current.state.connectionMethod).toBe(expected)})describe('mcp features for deployment mode', () => {test('self-hosted defaults and options stay within the non-platform subset', () => {- Object.assign(deploymentModeMock, {- isPlatform: false,- isCli: false,- isSelfHosted: true,- })+ Object.assign(deploymentModeMock, SELF_HOSTED)const { result } = renderHook(() => useConnectState({ mode: 'framework' }))act(() => {result.current.setMode('mcp')})const features = result.current.state.mcpFeatures- expect(Array.isArray(features)).toBe(true)expect(features).toEqual(expect.arrayContaining(['docs', 'database', 'development', 'debugging']))@@ -815,11 +471,7 @@ describe('useConnectState', () => {})test('self-hosted strips unsupported features when re-entering mcp mode', () => {- Object.assign(deploymentModeMock, {- isPlatform: false,- isCli: false,- isSelfHosted: true,- })+ Object.assign(deploymentModeMock, SELF_HOSTED)const { result } = renderHook(() =>useConnectState({ mode: 'mcp', mcpFeatures: ['docs', 'account', 'database'] }))diff --git a/apps/studio/components/interfaces/Database/Backups/RestoreToNewProject/RestoreToNewProject.utils.test.ts b/apps/studio/components/interfaces/Database/Backups/RestoreToNewProject/RestoreToNewProject.utils.test.tsindex 72422a069c5..8e9fdac9aa0 100644--- a/apps/studio/components/interfaces/Database/Backups/RestoreToNewProject/RestoreToNewProject.utils.test.ts+++ b/apps/studio/components/interfaces/Database/Backups/RestoreToNewProject/RestoreToNewProject.utils.test.ts@@ -14,12 +14,9 @@ const getComputePrice = (targetComputeSize: InfraInstanceSize, planId: PlanId) =}).computePricedescribe('projectSpecToMonthlyPrice', () => {- it('prices nano at the micro rate on paid plans', () => {+ it('prices nano and pico at the micro rate on paid plans', () => {expect(getComputePrice('nano', 'pro')).toBe(9.68)expect(getComputePrice('nano', 'team')).toBe(9.68)- })-- it('prices pico at the micro rate on paid plans', () => {expect(getComputePrice('pico', 'pro')).toBe(9.68)})diff --git a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.utils.test.ts b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.utils.test.tsindex 0d9d007913e..1a8798be9e2 100644--- a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.utils.test.ts+++ b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.utils.test.ts@@ -9,18 +9,14 @@ describe('FunctionList.utils: getDatabaseTriggersHref', () => {)})- it('preserves special characters in the function name', () => {- const href = getDatabaseTriggersHref('abc', 'on_insert&schema=secret')- const parsed = new URL(href, 'http://example.com')- expect(parsed.searchParams.get('search')).toBe('on_insert&schema=secret')- expect(parsed.searchParams.get('schema')).toBeNull()- })-- it('preserves spaces and plus signs in the function name', () => {- const href = getDatabaseTriggersHref('abc', 'a name+x')- const parsed = new URL(href, 'http://example.com')- expect(parsed.searchParams.get('search')).toBe('a name+x')- })+ it.each(['on_insert&schema=secret', 'a name+x'])(+ 'encodes special characters in the function name: %s',+ (name) => {+ const parsed = new URL(getDatabaseTriggersHref('abc', name), 'http://example.com')+ expect(parsed.searchParams.get('search')).toBe(name)+ expect(parsed.searchParams.get('schema')).toBeNull()+ }+ )it('falls back to empty strings for undefined inputs', () => {expect(getDatabaseTriggersHref(undefined, undefined)).toBe(diff --git a/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.constants.test.ts b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.constants.test.tsindex 2bdb310718d..b9156c8e664 100644--- a/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.constants.test.ts+++ b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.constants.test.ts@@ -2,90 +2,48 @@ import { describe, expect, it } from 'vitest'import { FormSchema } from './EditHookPanel.constants'-describe('EditHookPanel FormSchema', () => {- it('rejects incomplete http_request hostnames', () => {- const result = FormSchema.safeParse({- name: 'Test hook',- table_id: 'public.messages',- http_method: 'POST' as const,- timeout_ms: 1000,- events: ['INSERT'],- httpHeaders: [],- httpParameters: [],- function_type: 'http_request' as const,- http_url: 'https://webhook',- })-- expect(result.success).toBe(false)- if (!result.success) {- expect(- result.error.issues.some((issue) => issue.message === 'Please provide a valid URL')- ).toBe(true)- }- })-- it('rejects http_request URLs without an explicit protocol', () => {- const result = FormSchema.safeParse({- name: 'Test hook',- table_id: 'public.messages',- http_method: 'POST' as const,- timeout_ms: 1000,- events: ['INSERT'],- httpHeaders: [],- httpParameters: [],- function_type: 'http_request' as const,- http_url: 'hooks.example.com/webhook',- })+const validHook = {+ name: 'Test hook',+ table_id: 'public.messages',+ http_method: 'POST' as const,+ timeout_ms: 1000,+ events: ['INSERT'],+ httpHeaders: [],+ httpParameters: [],+ function_type: 'http_request' as const,+ http_url: 'https://hooks.example.com/webhook',+}- expect(result.success).toBe(false)- if (!result.success) {- expect(- result.error.issues.some(- (issue) => issue.message === 'Please prefix your URL with http:// or https://'- )- ).toBe(true)- }- })-- it('rejects key-only webhook headers', () => {- const result = FormSchema.safeParse({- name: 'Test hook',- table_id: 'public.messages',- http_method: 'POST' as const,- timeout_ms: 1000,- events: ['INSERT'],- httpHeaders: [{ id: 'header-1', name: 'X-Test', value: '' }],- httpParameters: [],- function_type: 'http_request' as const,- http_url: 'https://hooks.example.com/webhook',- })+describe('EditHookPanel FormSchema', () => {+ it.each([+ {+ description: 'incomplete http_request hostnames',+ overrides: { http_url: 'https://webhook' },+ message: 'Please provide a valid URL',+ },+ {+ description: 'http_request URLs without an explicit protocol',+ overrides: { http_url: 'hooks.example.com/webhook' },+ message: 'Please prefix your URL with http:// or https://',+ },+ {+ description: 'key-only webhook headers',+ overrides: { httpHeaders: [{ id: 'header-1', name: 'X-Test', value: '' }] },+ message: 'Header value is required',+ },+ {+ description: 'value-only webhook parameters',+ overrides: { httpParameters: [{ id: 'param-1', name: '', value: 'tenant' }] },+ message: 'Parameter name is required',+ },+ ])('rejects $description', ({ overrides, message }) => {+ const result = FormSchema.safeParse({ ...validHook, ...overrides })expect(result.success).toBe(false)- if (!result.success) {- expect(- result.error.issues.some((issue) => issue.message === 'Header value is required')- ).toBe(true)- }+ expect(result.error?.issues.map((issue) => issue.message)).toContain(message)})- it('rejects value-only webhook parameters', () => {- const result = FormSchema.safeParse({- name: 'Test hook',- table_id: 'public.messages',- http_method: 'POST' as const,- timeout_ms: 1000,- events: ['INSERT'],- httpHeaders: [],- httpParameters: [{ id: 'param-1', name: '', value: 'tenant' }],- function_type: 'http_request' as const,- http_url: 'https://hooks.example.com/webhook',- })-- expect(result.success).toBe(false)- if (!result.success) {- expect(- result.error.issues.some((issue) => issue.message === 'Parameter name is required')- ).toBe(true)- }+ it('accepts a complete http_request hook', () => {+ expect(FormSchema.safeParse(validHook).success).toBe(true)})})diff --git a/apps/studio/components/interfaces/Database/Policies/PolicyTableRow/PolicyTableRow.utils.test.ts b/apps/studio/components/interfaces/Database/Policies/PolicyTableRow/PolicyTableRow.utils.test.tsindex 7f048bd877f..35df0147c0e 100644--- a/apps/studio/components/interfaces/Database/Policies/PolicyTableRow/PolicyTableRow.utils.test.ts+++ b/apps/studio/components/interfaces/Database/Policies/PolicyTableRow/PolicyTableRow.utils.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { render } from '@testing-library/react'import type { ReactElement } from 'react'import { describe, expect, it } from 'vitest'@@ -44,15 +45,6 @@ describe('getTableDataApiStatus', () => {expect(status).toBe('no-grants')})- it('returns custom-grants for partial/non-standard grants — even if RLS is off', () => {- const status = getTableDataApiStatus({- apiAccessData: customAccess,- isRLSEnabled: false,- policiesCount: 0,- })- expect(status).toBe('custom-grants')- })-it('returns publicly-readable when fully granted and RLS is off', () => {const status = getTableDataApiStatus({apiAccessData: grantedAccess,diff --git a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineConnectionSection.test.tsx b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineConnectionSection.test.tsxindex 756b93e5507..863a629fb17 100644--- a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineConnectionSection.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineConnectionSection.test.tsx@@ -58,9 +58,6 @@ describe('PipelineConnectionSection', () => {expect(screen.getByText('Credentials')).toBeInTheDocument()fireEvent.click(screen.getByRole('button', { name: /Advanced settings/ }))expect(screen.getByText(`Adjust how data is written to ${type}.`)).toBeInTheDocument()- expect(- screen.getByRole('button', { name: /Advanced settings/ }).closest('.border-t')- ).toHaveClass('border-t', 'border-default')expect(screen.getByLabelText(label)).toBeInTheDocument()expect(screen.queryByText('Batch wait time')).not.toBeInTheDocument()expect(screen.queryByText('Table layout')).not.toBeInTheDocument()@@ -86,9 +83,6 @@ describe('PipelineConnectionSection', () => {expect(screen.queryByText(label)).not.toBeInTheDocument()}expect(screen.queryByText('Table layout controls') !== null).toBe(type === 'BigQuery')- expect(- screen.getByRole('button', { name: /Advanced settings/ }).closest('.border-t')- ).toHaveClass('border-default')})diff --git a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCostEstimate.test.tsx b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCostEstimate.test.tsxindex 70de5c86dda..e9324f8ec0e 100644--- a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCostEstimate.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCostEstimate.test.tsx@@ -48,7 +48,7 @@ describe('PipelineCostEstimate', () => {)expect(screen.getByRole('heading', { name: 'Estimated costs' })).toBeInTheDocument()- expect(screen.getByText('public.orders')).not.toHaveClass('font-mono')+ expect(screen.getByText('public.orders')).toBeInTheDocument()expect(screen.queryByText('billing.invoices')).not.toBeInTheDocument()expect(screen.getByText('$0.05/hour')).toBeInTheDocument()expect(screen.getByText('$3.00/GB')).toBeInTheDocument()diff --git a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCreationFlow.test.tsx b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCreationFlow.test.tsxindex daaf700f192..a0bcc5f4a64 100644--- a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCreationFlow.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCreationFlow.test.tsx@@ -188,12 +188,7 @@ describe('PipelineCreationFlow', () => {push.mockRestore()})- it.each([- ['BigQuery', 'bigquery#configure-bigquery-as-a-destination'],- ['DuckLake', 'ducklake#choose-a-configuration-mode'],- ['Snowflake', 'snowflake#prepare-snowflake-resources'],- ['ClickHouse', 'clickhouse#configure-clickhouse-as-a-destination'],- ] as const)('matches the connection subtitle and Docs to %s', async (type, path) => {+ it('matches the connection subtitle and Docs to each destination', async () => {addAPIMock({method: 'get',path: '/platform/projects/:ref',@@ -226,17 +221,26 @@ describe('PipelineCreationFlow', () => {)expect(screen.getByText('Where should this database be replicated?')).toBeInTheDocument()expect(screen.queryByRole('link', { name: 'Docs' })).not.toBeInTheDocument()- fireEvent.click(destinationType().getByRole('radio', { name: new RegExp(type) }))- await next('?step=connection')- expect(- screen.getByText(`Name this pipeline and enter credentials for ${type}.`)- ).toBeInTheDocument()- expect(screen.getByRole('link', { name: 'Docs' })).toHaveAttribute(- 'href',- `${DOCS_URL}/guides/database/replication/pipelines/${path}`- )- await back('')- expect(screen.queryByRole('link', { name: 'Docs' })).not.toBeInTheDocument()++ const docsPaths = [+ ['BigQuery', 'bigquery#configure-bigquery-as-a-destination'],+ ['DuckLake', 'ducklake#choose-a-configuration-mode'],+ ['Snowflake', 'snowflake#prepare-snowflake-resources'],+ ['ClickHouse', 'clickhouse#configure-clickhouse-as-a-destination'],+ ] as const+ for (const [type, path] of docsPaths) {+ fireEvent.click(destinationType().getByRole('radio', { name: new RegExp(type) }))+ await next('?step=connection')+ expect(+ screen.getByText(`Name this pipeline and enter credentials for ${type}.`)+ ).toBeInTheDocument()+ expect(screen.getByRole('link', { name: 'Docs' })).toHaveAttribute(+ 'href',+ `${DOCS_URL}/guides/database/replication/pipelines/${path}`+ )+ await back('')+ expect(screen.queryByRole('link', { name: 'Docs' })).not.toBeInTheDocument()+ }})const reachReview = async (@@ -327,8 +331,6 @@ describe('PipelineCreationFlow', () => {it.each([[false, false],- [true, false],- [false, true],[true, true],])('places review failures and keeps the current position (connection: %s, warnings: %s)',@@ -828,35 +830,6 @@ describe('PipelineCreationFlow', () => {expect(dataAfterReturn.getByRole('spinbutton', { name: 'Batch wait time' })).toHaveValue(750)})- it('preserves data values across steps and reaches Review', async () => {- renderWizard(- <PipelineCreationFlow availableDestinations={['BigQuery', 'Snowflake']} onClose={vi.fn()} />,- { rateLimitFactor: 1 }- )- await next('?step=connection')- fireEvent.change(screen.getByLabelText('Pipeline name'), {- target: { value: 'Warehouse' },- })- fillConnection()- await continueToData()- const data = withinRegion('Data')- fireEvent.click(data.getByRole('button', { name: /Advanced settings/ }))- fireEvent.change(data.getByRole('spinbutton', { name: 'Batch wait time' }), {- target: { value: '750' },- })- await back('?step=connection')- await continueToData()- const dataAfterReturn = withinRegion('Data')- fireEvent.click(dataAfterReturn.getByRole('button', { name: /Advanced settings/ }))- expect(dataAfterReturn.getByRole('spinbutton', { name: 'Batch wait time' })).toHaveValue(750)- await selectPublication()- await next('?step=review')- await waitFor(() =>- expect(within(stepCard()).getByRole('button', { name: 'Start pipeline' })).toBeEnabled()- )- expect(screen.getByDisplayValue('Warehouse')).toBeInTheDocument()- })-it('shows one publication loading failure before Continue and clears it after a successful retry', async () => {let shouldFail = trueaddAPIMock({diff --git a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCreationPage.test.tsx b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCreationPage.test.tsxindex abaee60d7ae..4c06da40d35 100644--- a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCreationPage.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineCreationPage.test.tsx@@ -108,26 +108,15 @@ it('renders the page body when the preview and project allow access', async () =customRender(<PipelineCreationPage />)expect(await screen.findByText('Wizard form')).toBeInTheDocument()})-it.each(['loading', 'orgPending'] as const)('waits while %s', (key) => {- state[key] = true- customRender(<PipelineCreationPage />)- expect(screen.queryByText('Wizard form')).not.toBeInTheDocument()-})-it('waits for rollout flags', () => {- state.flagsLoaded = false- customRender(<PipelineCreationPage />)- expect(screen.queryByText('Wizard form')).not.toBeInTheDocument()-})-it.each(['enabled', 'canUseReplication'] as const)(- 'does not expose the wizard when %s is false',- (key) => {- state[key] = false- customRender(<PipelineCreationPage />)- expect(screen.queryByText('Wizard form')).not.toBeInTheDocument()- }-)-it('does not expose the wizard for High Availability projects', () => {- state.isHighAvailability = true+it.each([+ { loading: true },+ { orgPending: true },+ { flagsLoaded: false },+ { enabled: false },+ { canUseReplication: false },+ { isHighAvailability: true },+])('does not expose the wizard when %o', (overrides) => {+ Object.assign(state, overrides)customRender(<PipelineCreationPage />)expect(screen.queryByText('Wizard form')).not.toBeInTheDocument()})diff --git a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineDataReview.test.tsx b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineDataReview.test.tsxindex 41a92ff6eea..7723bb21510 100644--- a/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineDataReview.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/CreatePipeline/PipelineDataReview.test.tsx@@ -126,10 +126,6 @@ describe('PipelineDataReview', () => {expect(screen.getByLabelText(label)).toHaveValue(value)expect(screen.queryByLabelText('Connection pool size')).not.toBeInTheDocument()})- it('marks unavailable publication data without inventing a table count', () => {- customRender(<TestReview available={false} />)- expect(screen.getByLabelText('Publication tables')).toHaveValue('Unavailable')- })it('puts the table name and incomplete partition summary in the value column', () => {customRender(<TestReview@@ -150,10 +146,10 @@ describe('PipelineDataReview', () => {'Partitioning and clustering applied when destination tables are first created or reset.')).toBeInTheDocument()- expect(screen.getByText('public.orders')).toHaveClass('break-all')- expect(screen.getByText('Partition by Not selected (month); Cluster by table_id')).toHaveClass(- 'break-words'- )+ expect(screen.getByText('public.orders')).toBeInTheDocument()+ expect(+ screen.getByText('Partition by Not selected (month); Cluster by table_id')+ ).toBeInTheDocument()expect(screen.queryByText('Table layout: public.orders')).not.toBeInTheDocument()})@@ -168,6 +164,7 @@ describe('PipelineDataReview', () => {}}/>)+ expect(screen.getByLabelText('Publication tables')).toHaveValue('Unavailable')expect(screen.getByLabelText('Tables to include')).toHaveValue('Unavailable')expect(screen.queryByText('Table 999')).not.toBeInTheDocument()view.unmount()diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/BigQuery.utils.test.ts b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/BigQuery.utils.test.tsindex 321f805152b..c0b5d1abf07 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/BigQuery.utils.test.ts+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/BigQuery.utils.test.ts@@ -8,32 +8,96 @@ import {} from './BigQuery.utils'describe('getBigQueryValidationIssues', () => {- const validData = {- projectId: 'my-project',- datasetId: 'analytics',- serviceAccountKey: '{}',- }-- it('returns no issues when all required fields are set', () => {- expect(getBigQueryValidationIssues(validData)).toEqual([])- })-- it('flags blank required fields', () => {+ it.each([+ ['empty', ''],+ ['whitespace-only', ' \t\n'],+ ])('returns required-field errors for %s BigQuery settings', (_, value) => {expect(- getBigQueryValidationIssues({ projectId: '', datasetId: ' ', serviceAccountKey: '{}' })+ getBigQueryValidationIssues({+ projectId: value,+ datasetId: value,+ serviceAccountKey: value,+ })).toEqual([{ path: 'projectId', message: 'Project ID is required.' },{ path: 'datasetId', message: 'Dataset ID is required.' },+ { path: 'serviceAccountKey', message: 'Service account key is required.' },])})- it('skips the service account key when secrets are optional (edit mode)', () => {- expect(- getBigQueryValidationIssues(- { ...validData, serviceAccountKey: '' },- { secretsOptional: true }- )- ).toEqual([])+ it('returns no issues for a complete configuration', () => {+ const issues = getBigQueryValidationIssues({+ projectId: 'my-project',+ datasetId: 'my_dataset',+ serviceAccountKey: '{ "type": "service_account" }',+ })++ expect(issues).toEqual([])+ })++ it('rejects invalid JSON in the service account key', () => {+ const issues = getBigQueryValidationIssues({+ projectId: 'my-project',+ datasetId: 'my_dataset',+ serviceAccountKey: '{ "type": "service_account" ',+ })++ expect(issues).toEqual([+ { path: 'serviceAccountKey', message: 'Service account key must be valid JSON.' },+ ])+ })++ it('skips JSON shape checks when validateJson is false', () => {+ const issues = getBigQueryValidationIssues(+ {+ projectId: 'my-project',+ datasetId: 'my_dataset',+ serviceAccountKey: '{ "type": "service_account" ',+ },+ { validateJson: false }+ )++ expect(issues).toEqual([])+ })++ it('rejects non-JSON text in the service account key', () => {+ const issues = getBigQueryValidationIssues({+ projectId: 'my-project',+ datasetId: 'my_dataset',+ serviceAccountKey: 'not-json',+ })++ expect(issues).toEqual([+ { path: 'serviceAccountKey', message: 'Service account key must be valid JSON.' },+ ])+ })++ it('validates JSON when replacing credentials in edit mode', () => {+ const issues = getBigQueryValidationIssues(+ {+ projectId: 'my-project',+ datasetId: 'my_dataset',+ serviceAccountKey: '{ invalid',+ },+ { secretsOptional: true }+ )++ expect(issues).toEqual([+ { path: 'serviceAccountKey', message: 'Service account key must be valid JSON.' },+ ])+ })++ it('allows an omitted BigQuery service account key in edit mode', () => {+ const issues = getBigQueryValidationIssues(+ {+ projectId: 'my-project',+ datasetId: 'my_dataset',+ serviceAccountKey: '',+ },+ { secretsOptional: true }+ )++ expect(issues).toEqual([])})})@@ -83,27 +147,16 @@ describe('defaultPartitionByForKind', () => {})describe('parseIntegerInput', () => {- it('parses a valid integer string', () => {- expect(parseIntegerInput('42', 0)).toBe(42)- })-- it('parses a negative number', () => {- expect(parseIntegerInput('-5', 0)).toBe(-5)- })-- it('uses the empty sentinel for an empty string', () => {- expect(parseIntegerInput('', 7)).toBe('')- })-- it('uses the empty sentinel for whitespace-only input', () => {- expect(parseIntegerInput(' ', 7)).toBe('')- })-- it('keeps the previous value for non-numeric input', () => {- expect(parseIntegerInput('abc', 7)).toBe(7)- })-- it('uses the empty sentinel while a negative sign is typed alone', () => {- expect(parseIntegerInput('-', 7)).toBe('')+ it.each([+ ['42', 42],+ ['-5', -5],+ // Empty, whitespace-only and a lone minus sign (mid-typing) use the empty sentinel+ ['', ''],+ [' ', ''],+ ['-', ''],+ // Non-numeric input keeps the previous value+ ['abc', 7],+ ])('parses %j as %j', (input, expected) => {+ expect(parseIntegerInput(input, 7)).toBe(expected)})})diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/Fields.test.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/Fields.test.tsxindex 6322f20270d..36f004173f2 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/Fields.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/Fields.test.tsx@@ -37,7 +37,6 @@ describe('BigQueryFields', () => {fireEvent.change(textarea, { target: { value: `${contents}\n` } })expect(textarea).toHaveValue(`${contents}\n`)- expect(textarea).toHaveClass('max-h-[calc(13lh+1rem)]')})it('imports a dropped JSON file into the service account key field', async () => {diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/TableOptions.test.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/TableOptions.test.tsxindex 711757428c3..36693018b03 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/TableOptions.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/TableOptions.test.tsx@@ -466,7 +466,7 @@ describe('TableOptions source reconciliation', () => {customRender(<TableOptionsHarness tableOptions={[{ tableId: 202, clusterBy: ['Region'] }]} />)expect(await screen.findByText('Billing.Invoices')).toBeInTheDocument()- expect(screen.getByText('No longer in publication')).toHaveClass('text-destructive-600')+ expect(screen.getByText('No longer in publication')).toBeInTheDocument()expect(screen.getByText('Some tables are no longer in the publication')).toBeInTheDocument()expect(screen.queryByText('Region')).not.toBeInTheDocument()expect(document.body).not.toHaveTextContent('202')diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/TableOptions.utils.test.ts b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/TableOptions.utils.test.tsindex ca6c8415bf3..d35cda81520 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/TableOptions.utils.test.ts+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/TableOptions.utils.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { describe, expect, it } from 'vitest'import {diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.utils.test.ts b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.utils.test.tsindex 4d6a2442bd7..dc29f50faab 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.utils.test.ts+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.utils.test.ts@@ -1,7 +1,6 @@import { describe, expect, it, vi } from 'vitest'import { getAnalyticsBucketValidationIssues } from './AnalyticsBucket/AnalyticsBucket.utils'-import { getBigQueryValidationIssues } from './BigQuery/BigQuery.utils'import { getClickHouseValidationIssues } from './ClickHouse/ClickHouse.utils'import { CREATE_NEW_KEY, CREATE_NEW_NAMESPACE } from './DestinationForm.constants'import {@@ -810,111 +809,6 @@ describe('DestinationForm.utils ClickHouse', () => {})})-describe('DestinationForm.utils BigQuery', () => {- it('returns required-field errors for missing BigQuery settings', () => {- const issues = getBigQueryValidationIssues({- projectId: '',- datasetId: '',- serviceAccountKey: '',- })-- expect(issues).toEqual([- { path: 'projectId', message: 'Project ID is required.' },- { path: 'datasetId', message: 'Dataset ID is required.' },- { path: 'serviceAccountKey', message: 'Service account key is required.' },- ])- })-- it('treats whitespace-only values as missing', () => {- const issues = getBigQueryValidationIssues({- projectId: ' ',- datasetId: '\t',- serviceAccountKey: '\n',- })-- expect(issues).toEqual([- { path: 'projectId', message: 'Project ID is required.' },- { path: 'datasetId', message: 'Dataset ID is required.' },- { path: 'serviceAccountKey', message: 'Service account key is required.' },- ])- })-- it('returns no issues for a complete configuration', () => {- const issues = getBigQueryValidationIssues({- projectId: 'my-project',- datasetId: 'my_dataset',- serviceAccountKey: '{ "type": "service_account" }',- })-- expect(issues).toEqual([])- })-- it('rejects invalid JSON in the service account key', () => {- const issues = getBigQueryValidationIssues({- projectId: 'my-project',- datasetId: 'my_dataset',- serviceAccountKey: '{ "type": "service_account" ',- })-- expect(issues).toEqual([- { path: 'serviceAccountKey', message: 'Service account key must be valid JSON.' },- ])- })-- it('skips JSON shape checks when validateJson is false', () => {- const issues = getBigQueryValidationIssues(- {- projectId: 'my-project',- datasetId: 'my_dataset',- serviceAccountKey: '{ "type": "service_account" ',- },- { validateJson: false }- )-- expect(issues).toEqual([])- })-- it('rejects non-JSON text in the service account key', () => {- const issues = getBigQueryValidationIssues({- projectId: 'my-project',- datasetId: 'my_dataset',- serviceAccountKey: 'not-json',- })-- expect(issues).toEqual([- { path: 'serviceAccountKey', message: 'Service account key must be valid JSON.' },- ])- })-- it('validates JSON when replacing credentials in edit mode', () => {- const issues = getBigQueryValidationIssues(- {- projectId: 'my-project',- datasetId: 'my_dataset',- serviceAccountKey: '{ invalid',- },- { secretsOptional: true }- )-- expect(issues).toEqual([- { path: 'serviceAccountKey', message: 'Service account key must be valid JSON.' },- ])- })-- it('allows an omitted BigQuery service account key in edit mode', () => {- const issues = getBigQueryValidationIssues(- {- projectId: 'my-project',- datasetId: 'my_dataset',- serviceAccountKey: '',- },- { secretsOptional: true }- )-- expect(issues).toEqual([])- })-})-describe('DestinationForm.utils Analytics Bucket', () => {it('returns required-field errors for an empty configuration', () => {const issues = getAnalyticsBucketValidationIssues({diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/NewPublicationPanel.test.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/NewPublicationPanel.test.tsxindex 8aaea4bf6e4..14a7f7c462a 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/NewPublicationPanel.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/NewPublicationPanel.test.tsx@@ -140,7 +140,6 @@ describe('NewPublicationPanel', () => {const partitionOption = screen.getByRole('option', {name: 'Replicate each partition separately',})- expect(partitionOption).toHaveClass('whitespace-nowrap')fireEvent.click(partitionOption)fireEvent.click(screen.getByRole('button', { name: 'Create publication' }))diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PipelineRegionField.test.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PipelineRegionField.test.tsxindex 6f751d0a569..053943ceeb1 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PipelineRegionField.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/PipelineRegionField.test.tsx@@ -42,5 +42,5 @@ test('reuses the region display without a form label or description', () => {expect(screen.getByText(PIPELINE_REGION.code)).toBeInTheDocument()expect(screen.queryByText('Pipeline region')).not.toBeInTheDocument()expect(screen.queryByRole('combobox')).not.toBeInTheDocument()- expect(screen.getByText(PIPELINE_REGION.code).parentElement).toHaveClass('w-full', 'px-3')+ expect(screen.getByText(PIPELINE_REGION.code).parentElement).toHaveClass('w-full')})diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/Snowflake/Fields.test.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/Snowflake/Fields.test.tsxindex fa60d3f5344..2e0c054bab0 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/Snowflake/Fields.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/Snowflake/Fields.test.tsx@@ -67,17 +67,4 @@ describe('SnowflakeFields', () => {await waitFor(() => expect(textarea).toHaveValue(PRIVATE_KEY))})-- it('rejects a public key file without replacing the private key', async () => {- const { container } = customRender(<TestForm snowflakePrivateKey="existing-key" />)- const publicKey = '-----BEGIN PUBLIC KEY-----\npublic-key\n-----END PUBLIC KEY-----'- const file = new File([publicKey], 'rsa_key.pub', { type: 'application/x-pem-file' })- Object.defineProperty(file, 'text', { value: vi.fn().mockResolvedValue(publicKey) })-- const fileInput = container.querySelector<HTMLInputElement>('input[type="file"]')- fireEvent.change(fileInput!, { target: { files: [file] } })-- expect(await screen.findByText('Select a P8 or PEM private key.')).toBeInTheDocument()- expect(screen.getByDisplayValue('existing-key')).toBeInTheDocument()- })})diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/Snowflake/Snowflake.utils.test.ts b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/Snowflake/Snowflake.utils.test.tsindex 07daecd3a4c..6ce73610e48 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/Snowflake/Snowflake.utils.test.ts+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/Snowflake/Snowflake.utils.test.ts@@ -91,15 +91,6 @@ describe('getSnowflakeValidationIssues', () => {expect(issues).toEqual([])})-- it('does not flag an empty private key left blank while editing', () => {- const issues = getSnowflakeValidationIssues(- { ...VALID_DATA, snowflakePrivateKey: '' },- { secretsOptional: true }- )-- expect(issues).toEqual([])- })})describe('readPrivateKeyFile', () => {diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/TableCopySelection.test.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/TableCopySelection.test.tsxindex d02cb02066d..d54f590a49d 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/TableCopySelection.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/TableCopySelection.test.tsx@@ -178,9 +178,7 @@ describe('TableCopySelection', () => {expect(await screen.findByText('Legacy.ArchivedOrders')).toBeInTheDocument()expect(screen.getByText('Legacy.ArchivedOrders')).toHaveClass('text-destructive-600')- expect(screen.getByText('Some tables are no longer in the publication.')).toHaveClass(- 'text-destructive-600'- )+ expect(screen.getByText('Some tables are no longer in the publication.')).toBeInTheDocument()expect(screen.queryByText('No longer in publication')).not.toBeInTheDocument()expect(document.body).not.toHaveTextContent('999')})diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/useDestinationForm.test.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/useDestinationForm.test.tsxindex 9b7b66e0ddf..f0be7e0cb38 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/useDestinationForm.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/useDestinationForm.test.tsx@@ -166,28 +166,7 @@ describe('useDestinationForm', () => {expect(result.current.requestStatus).toBe(PipelineStatusRequestStatus.None)})- it('validates destination and pipeline configuration before creating', async () => {- const { result } = await renderDestinationForm()- await act(async () => {- expect(- await result.current.validateConfiguration({- data: { ...formData, serviceAccountKey: '{"type":"service_account"}' },- onValidationFail: vi.fn(),- })- ).toEqual({ canContinue: true, warnings: [] })- })- expect(validationRequests).toEqual([- expect.objectContaining({- source_id: 42,- config: expect.objectContaining({- publication_name: 'analytics',- table_sync_copy: { type: 'include_tables', table_ids: [101] },- }),- }),- ])- })-- it('sends the same pipeline settings to both validation endpoints', async () => {+ it('validates with the same pipeline settings sent to both validation endpoints', async () => {const expectedPipelineConfig = {publication_name: 'analytics',table_sync_copy: { type: 'include_tables', table_ids: [101] },@@ -197,10 +176,12 @@ describe('useDestinationForm', () => {}const { result } = await renderDestinationForm()await act(async () => {- await result.current.validateConfiguration({- data: { ...formData, serviceAccountKey: '{"type":"service_account"}' },- onValidationFail: vi.fn(),- })+ expect(+ await result.current.validateConfiguration({+ data: { ...formData, serviceAccountKey: '{"type":"service_account"}' },+ onValidationFail: vi.fn(),+ })+ ).toEqual({ canContinue: true, warnings: [] })})expect(destinationRequests).toEqual([{diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationRow.test.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationRow.test.tsxindex d90533cf797..7200be4b28e 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationRow.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/DestinationRow.test.tsx@@ -228,10 +228,8 @@ describe('DestinationRow', () => {await screen.findByText('supabase_realtime')await userEvent.click(screen.getByRole('button', { name: 'Pipeline options' }))await userEvent.click(screen.getByRole('menuitem', { name: 'Delete pipeline' }))- await userEvent.type(- screen.getByPlaceholderText('Type the pipeline name'),- 'My BigQuery Destination'- )+ await userEvent.click(screen.getByPlaceholderText('Type the pipeline name'))+ await userEvent.paste('My BigQuery Destination')await waitFor(() =>expect(screen.getByRole('button', { name: 'Delete pipeline' })).toBeEnabled())@@ -289,10 +287,8 @@ describe('DestinationRow', () => {await screen.findByText('supabase_realtime')await userEvent.click(screen.getByRole('button', { name: 'Pipeline options' }))await userEvent.click(screen.getByRole('menuitem', { name: 'Delete pipeline' }))- await userEvent.type(- screen.getByPlaceholderText('Type the pipeline name'),- 'My BigQuery Destination'- )+ await userEvent.click(screen.getByPlaceholderText('Type the pipeline name'))+ await userEvent.paste('My BigQuery Destination')await waitFor(() =>expect(screen.getByRole('button', { name: 'Delete pipeline' })).toBeEnabled())@@ -336,17 +332,11 @@ describe('DestinationRow', () => {})test('shows "Caught up" when confirmed_flush_lsn_bytes is 0', async () => {- addSourcesMock()- addDestinationMock()- addPipelinesMock()- addPipelineStatusMock('started')- addReplicationStatusMock(0)- addVersionMock()+ addAllMocks()customRender(<DestinationRow destinationId={DESTINATION_ID} />)const lag = await screen.findByText('Caught up')- expect(lag).toHaveClass('text-foreground-light')expect(lag.closest('[aria-live="polite"]')).toHaveAttribute('aria-atomic', 'true')})@@ -360,7 +350,7 @@ describe('DestinationRow', () => {customRender(<DestinationRow destinationId={DESTINATION_ID} />)- expect(await screen.findByText('2 KB')).toHaveClass('text-foreground-light')+ expect(await screen.findByText('2 KB')).toBeInTheDocument()})test('shows unavailable lag instead of caught up when the distance is null', async () => {@@ -400,7 +390,7 @@ describe('DestinationRow', () => {expect(screen.queryByText('Caught up')).not.toBeInTheDocument()})- test('shows initial sync with the same lag text treatment', async () => {+ test('shows initial sync while tables are copying', async () => {addSourcesMock()addDestinationMock()addPipelinesMock()@@ -419,7 +409,7 @@ describe('DestinationRow', () => {customRender(<DestinationRow destinationId={DESTINATION_ID} />)- expect(await screen.findByText('Initial sync')).toHaveClass('text-foreground-light')+ expect(await screen.findByText('Initial sync')).toBeInTheDocument()})test('shows initial sync when apply lag is unavailable', async () => {@@ -516,60 +506,18 @@ describe('DestinationRow', () => {expect(await screen.findByText('Lag unavailable')).toBeInTheDocument()})- test('shows publication name from pipeline config', async () => {- addSourcesMock()- addDestinationMock()- addPipelinesMock()- addPipelineStatusMock('started')- addReplicationStatusMock(0)- addVersionMock()-- customRender(<DestinationRow destinationId={DESTINATION_ID} />)-- expect(await screen.findByText('supabase_realtime')).toBeInTheDocument()- })-- test('shows Running badge when pipeline is started', async () => {- addSourcesMock()- addDestinationMock()- addPipelinesMock()- addPipelineStatusMock('started')- addReplicationStatusMock(0)- addVersionMock()-- customRender(<DestinationRow destinationId={DESTINATION_ID} />)-- const status = await screen.findByText('Running')- const liveRegion = status.closest('[aria-live="polite"]')-- expect(status).toBeInTheDocument()- expect(liveRegion).toHaveAttribute('aria-atomic', 'true')- })-- test('shows Failed badge when pipeline has failed', async () => {- addSourcesMock()- addDestinationMock()- addPipelinesMock()- addPipelineStatusMock('failed')- addReplicationStatusMock(0)- addVersionMock()-- customRender(<DestinationRow destinationId={DESTINATION_ID} />)-- expect(await screen.findByText('Failed')).toBeInTheDocument()- })-- test('shows Stopped badge when pipeline is stopped', async () => {- addSourcesMock()- addDestinationMock()- addPipelinesMock()- addPipelineStatusMock('stopped')- addReplicationStatusMock(0)- addVersionMock()+ test.each([+ ['started', 'Running'],+ ['failed', 'Failed'],+ ['stopped', 'Stopped'],+ ] as const)('shows the %s pipeline status as %s', async (statusName, label) => {+ addAllMocks()+ addPipelineStatusMock(statusName)customRender(<DestinationRow destinationId={DESTINATION_ID} />)- expect(await screen.findByText('Stopped')).toBeInTheDocument()+ const status = await screen.findByText(label)+ expect(status.closest('[aria-live="polite"]')).toHaveAttribute('aria-atomic', 'true')})test('shows table errors in the subtext and on the logo when tables have replication errors', async () => {diff --git a/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/Nodes.utils.test.ts b/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/Nodes.utils.test.tsindex 73eeaabd83c..8f538466e75 100644--- a/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/Nodes.utils.test.ts+++ b/apps/studio/components/interfaces/Database/Replication/ReplicationDiagram/Nodes.utils.test.ts@@ -3,24 +3,14 @@ import { describe, expect, it } from 'vitest'import { getReplicationDestinationType } from './Nodes.utils'describe('getReplicationDestinationType', () => {- it('returns BigQuery for big_query configs', () => {- expect(getReplicationDestinationType({ big_query: {} })).toBe('BigQuery')- })-- it('returns Analytics Bucket for iceberg configs', () => {- expect(getReplicationDestinationType({ iceberg: {} })).toBe('Analytics Bucket')- })-- it('returns DuckLake for ducklake configs', () => {- expect(getReplicationDestinationType({ ducklake: {} })).toBe('DuckLake')- })-- it('returns Snowflake for snowflake configs', () => {- expect(getReplicationDestinationType({ snowflake: {} })).toBe('Snowflake')- })-- it('returns ClickHouse for clickhouse configs', () => {- expect(getReplicationDestinationType({ clickhouse: {} })).toBe('ClickHouse')+ it.each([+ ['big_query', 'BigQuery'],+ ['iceberg', 'Analytics Bucket'],+ ['ducklake', 'DuckLake'],+ ['snowflake', 'Snowflake'],+ ['clickhouse', 'ClickHouse'],+ ])('maps %s configs to %s', (key, expected) => {+ expect(getReplicationDestinationType({ [key]: {} })).toBe(expected)})it('returns undefined for unknown or missing configs', () => {diff --git a/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineLayout.test.tsx b/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineLayout.test.tsxindex aef947ac1b2..65b8b1fcfe4 100644--- a/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineLayout.test.tsx+++ b/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineLayout.test.tsx@@ -325,7 +325,6 @@ describe('ReplicationPipelineLayout', () => {renderLayout()const updateButton = await screen.findByRole('button', { name: 'Update available' })- expect(updateButton).toHaveClass('bg-primary-solid')await userEvent.click(updateButton)// The trigger button shares this name, so match the dialog's heading specificallyexpect(await screen.findByRole('heading', { name: 'Update available' })).toBeVisible()diff --git a/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus/ReplicationPipelineStatus.utils.test.ts b/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus/ReplicationPipelineStatus.utils.test.tsindex b804a5a5938..973ee3a7e98 100644--- a/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus/ReplicationPipelineStatus.utils.test.ts+++ b/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus/ReplicationPipelineStatus.utils.test.ts@@ -52,14 +52,19 @@ describe('slot health', () => {})describe('getTableSyncLagLabel', () => {- test('does not infer unlimited retention from missing headroom', () => {+ // Missing or invalid headroom must not be reported as unlimited (or any) retention+ test.each([+ ['null', { safe_wal_size_bytes: null }],+ ['omitted', {}],+ ['NaN', { safe_wal_size_bytes: Number.NaN }],+ ])('omits WAL retention when headroom is %s', (_, headroom) => {expect(getTableSyncLagLabel({active: true,wal_status: 'reserved',restart_lsn_bytes: 0,confirmed_flush_lsn_bytes: 0,- safe_wal_size_bytes: null,+ ...headroom,})).toEqual([])})@@ -101,29 +106,6 @@ describe('getTableSyncLagLabel', () => {).toEqual(['0 bytes WAL retention remaining', 'Some changes at risk'])})- test('omits WAL retention when the API does not provide it', () => {- expect(- getTableSyncLagLabel({- active: true,- wal_status: 'reserved',- restart_lsn_bytes: 0,- confirmed_flush_lsn_bytes: 0,- })- ).toEqual([])- })-- test('omits an invalid WAL retention value', () => {- expect(- getTableSyncLagLabel({- active: true,- wal_status: 'reserved',- restart_lsn_bytes: 0,- confirmed_flush_lsn_bytes: 0,- safe_wal_size_bytes: Number.NaN,- })- ).toEqual([])- })-test('reports an exceeded WAL retention budget', () => {expect(getTableSyncLagLabel({diff --git a/apps/studio/components/interfaces/Database/Replication/RestartCostEstimate.test.ts b/apps/studio/components/interfaces/Database/Replication/RestartCostEstimate.test.tsdeleted file mode 100644index 397d907a5d7..00000000000--- a/apps/studio/components/interfaces/Database/Replication/RestartCostEstimate.test.ts+++ /dev/null@@ -1,52 +0,0 @@-import { describe, expect, it } from 'vitest'--import { calculateRestartCostEstimate } from './RestartCostEstimate'--const tables = [- {- schema: 'public',- name: 'orders',- estimated_bytes: 2_000_000_000,- estimated_cost: 1.25,- is_row_filtered: false,- },- {- schema: 'public',- name: 'customers',- estimated_bytes: 1_000_000_000,- estimated_cost: 0.75,- is_row_filtered: true,- },- {- schema: 'internal',- name: 'audit_log',- estimated_bytes: 500_000_000,- estimated_cost: 0.3,- is_row_filtered: false,- },-]--describe('calculateRestartCostEstimate', () => {- it('sums only the tables being restarted', () => {- expect(- calculateRestartCostEstimate(tables, [- { schema: 'public', name: 'orders' },- { schema: 'public', name: 'customers' },- ])- ).toMatchObject({- isComplete: true,- estimatedBytes: 3_000_000_000,- estimatedCost: 2,- hasRowFilteredTables: true,- })- })-- it('marks the estimate incomplete when a restarted table is missing', () => {- expect(- calculateRestartCostEstimate(tables, [- { schema: 'public', name: 'orders' },- { schema: 'public', name: 'missing' },- ]).isComplete- ).toBe(false)- })-})diff --git a/apps/studio/components/interfaces/Database/Replication/useRedirectLegacyReadReplicaDestination.test.ts b/apps/studio/components/interfaces/Database/Replication/useRedirectLegacyReadReplicaDestination.test.tsindex b61898c3d57..e93add3ebaf 100644--- a/apps/studio/components/interfaces/Database/Replication/useRedirectLegacyReadReplicaDestination.test.ts+++ b/apps/studio/components/interfaces/Database/Replication/useRedirectLegacyReadReplicaDestination.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { renderHook, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, test, vi } from 'vitest'diff --git a/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.test.ts b/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.test.tsindex e09c66342fc..59b37df190f 100644--- a/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.test.ts+++ b/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.test.ts@@ -1,13 +1,9 @@import { describe, expect, test } from 'vitest'-import {- getEnumsAsMarkdown,- getPoliciesAsMarkdown,- getSchemaAsMarkdown,- getTableDefinitionAsMarkdown,-} from './Schemas.utils'+import { getEnumsAsMarkdown, getPoliciesAsMarkdown, getSchemaAsMarkdown } from './Schemas.utils'describe('Schemas.utils', () => {+ // getSchemaAsMarkdown composes getTableDefinitionAsMarkdown per table, so this covers bothtest('getSchemaAsMarkdown returns properly formatted markdown', () => {const schema = 'public'const tables = [@@ -120,65 +116,6 @@ An excellent description`)})- test('getTableDefinitionAsMarkdown returns properly formatted markdown', () => {- const table = {- ref: 'default',- id: 20999,- name: 'test',- description: 'An excellent description',- schema: 'public',- isForeign: false,- columns: [- {- id: '20999.1',- isPrimary: true,- name: 'id',- format: 'int8',- isNullable: false,- isUnique: false,- isUpdateable: true,- isIdentity: true,- description: '',- },- {- id: '20999.2',- isPrimary: false,- name: 'created_at',- format: 'timestamptz',- isNullable: false,- isUnique: false,- isUpdateable: true,- isIdentity: false,- description: '',- },- {- id: '20999.3',- isPrimary: false,- name: 'user_id',- format: 'uuid',- isNullable: true,- isUnique: false,- isUpdateable: true,- isIdentity: false,- description: '',- },- ],- }- const result = getTableDefinitionAsMarkdown(table)- expect(result).toBe(`## Table \`test\`--An excellent description--### Columns--| Name | Type | Constraints |-|------|------|-------------|-| \`id\` | \`int8\` | Primary Identity |-| \`created_at\` | \`timestamptz\` | |-| \`user_id\` | \`uuid\` | Nullable |-`)- })-test('getEnumsAsMarkdown returns formatted enum section', () => {const enums = [{ name: 'order_status', schema: 'public', enums: ['pending', 'processing', 'shipped'] },diff --git a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.utils.test.ts b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.utils.test.tsindex 3b9ecfa0d3c..690097c4a5d 100644--- a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.utils.test.ts+++ b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggerList.utils.test.ts@@ -9,21 +9,7 @@ describe('TriggerList.utils: getDatabaseFunctionsHref', () => {)})- it('preserves special characters in the function name', () => {- const href = getDatabaseFunctionsHref('abc', 'public', 'do_thing&secret=1')- const parsed = new URL(href, 'http://example.com')- expect(parsed.searchParams.get('search')).toBe('do_thing&secret=1')- expect(parsed.searchParams.get('schema')).toBe('public')- })-- it('preserves special characters in the schema', () => {- const href = getDatabaseFunctionsHref('abc', 'my schema+x', 'do_thing')- const parsed = new URL(href, 'http://example.com')- expect(parsed.searchParams.get('schema')).toBe('my schema+x')- expect(parsed.searchParams.get('search')).toBe('do_thing')- })-- it('encodes both name and schema together', () => {+ it('encodes special characters in both name and schema', () => {const href = getDatabaseFunctionsHref('abc', 'a&b=c', 'd e+f')const parsed = new URL(href, 'http://example.com')expect(parsed.searchParams.get('schema')).toBe('a&b=c')diff --git a/apps/studio/components/interfaces/DiskManagement/ComputeAndDiskUsageCharts.utils.test.ts b/apps/studio/components/interfaces/DiskManagement/ComputeAndDiskUsageCharts.utils.test.tsindex 270c3265a44..deb508904a0 100644--- a/apps/studio/components/interfaces/DiskManagement/ComputeAndDiskUsageCharts.utils.test.ts+++ b/apps/studio/components/interfaces/DiskManagement/ComputeAndDiskUsageCharts.utils.test.ts@@ -260,21 +260,6 @@ describe('ComputeAndDiskUsageCharts utils', () => {expect(result.diskChartData[0].timestamp).toBe('2024-01-02T00:00:00Z')expect(result.computeChartData).toHaveLength(2)})-- test('keeps missing disk IO balance unavailable', () => {- const result = buildUsageChartData(- buildMultiResponse([{ period_start: '2024-01-01T00:00:00Z', values: {} }])- )-- expect(result.computeChartData).toEqual([- {- timestamp: '2024-01-01T00:00:00Z',- maxCpuUsage: 0,- ramUsage: 0,- diskIoBalance: undefined,- },- ])- })})describe('getComputeUsageSummary', () => {diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.test.ts b/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.test.tsindex 43aec754b38..fbf0a03611c 100644--- a/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.test.ts+++ b/apps/studio/components/interfaces/Explorer/QueryCell/QueryCell.utils.test.ts@@ -112,49 +112,41 @@ describe('changeCellSource', () => {})describe('shouldInvalidateResultOnSourceChange', () => {- it('invalidates when the backend changes from database to logs', () => {- expect(- shouldInvalidateResultOnSourceChange(DATABASE_CELL, {- _tag: 'logs',- time_range: LOG_CELL.time_range,- })- ).toBe(true)- })-- it('invalidates when the backend changes from logs to database', () => {- expect(- shouldInvalidateResultOnSourceChange(LOG_CELL, {- _tag: 'database',- database_identifier: undefined,- })- ).toBe(true)- })-- it('invalidates a log cell result when the time range changes', () => {- expect(- shouldInvalidateResultOnSourceChange(LOG_CELL, {- _tag: 'logs',- time_range: { _tag: 'relative_time_range', unit: 'day', amount: 7 },- })- ).toBe(true)- })-- it('keeps a log cell result when the time range is unchanged', () => {- expect(- shouldInvalidateResultOnSourceChange(LOG_CELL, {- _tag: 'logs',- time_range: { ...LOG_CELL.time_range },- })- ).toBe(false)- })-- it('keeps a database cell result when only the connected database changes', () => {- expect(- shouldInvalidateResultOnSourceChange(DATABASE_CELL, {- _tag: 'database',- database_identifier: 'replica-2',- })- ).toBe(false)+ it.each<[string, QueryCell, Parameters<typeof shouldInvalidateResultOnSourceChange>[1], boolean]>(+ [+ [+ 'invalidates when the backend changes from database to logs',+ DATABASE_CELL,+ { _tag: 'logs', time_range: { _tag: 'relative_time_range', unit: 'hour', amount: 1 } },+ true,+ ],+ [+ 'invalidates when the backend changes from logs to database',+ LOG_CELL,+ { _tag: 'database', database_identifier: undefined },+ true,+ ],+ [+ 'invalidates a log cell result when the time range changes',+ LOG_CELL,+ { _tag: 'logs', time_range: { _tag: 'relative_time_range', unit: 'day', amount: 7 } },+ true,+ ],+ [+ 'keeps a log cell result when the time range is unchanged',+ LOG_CELL,+ { _tag: 'logs', time_range: { _tag: 'relative_time_range', unit: 'hour', amount: 1 } },+ false,+ ],+ [+ 'keeps a database cell result when only the connected database changes',+ DATABASE_CELL,+ { _tag: 'database', database_identifier: 'replica-2' },+ false,+ ],+ ]+ )('%s', (_, cell, source, expected) => {+ expect(shouldInvalidateResultOnSourceChange(cell, source)).toBe(expected)})})diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.assistant-cache-invalidation.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.assistant-cache-invalidation.test.tsxdeleted file mode 100644index 815a74e7142..00000000000--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.assistant-cache-invalidation.test.tsx+++ /dev/null@@ -1,447 +0,0 @@-import { QueryClient } from '@tanstack/react-query'-import { fireEvent, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { HttpResponse } from 'msw'-import { afterEach, describe, expect, it, vi } from 'vitest'--import { ExplorerNotebookTab } from '../ExplorerNotebookTab'-import { ExplorerProvider } from '@/components/layouts/ExplorerLayout/ExplorerProvider'-import type { components } from '@/data/api'-import { contentKeys } from '@/data/content/keys'-import {- applyNotebookCacheEffects,- collectNotebookCacheEffects,-} from '@/lib/ai/notebook-cache-invalidation'-import {- createAssistantMessageWithDeleteNotebookTool,- createAssistantMessageWithUpdateNotebookTool,-} from '@/lib/ai/test-fixtures'-import { notebooksState } from '@/state/notebooks/notebooks-state'-import type { Notebook } from '@/state/notebooks/types'-import { createTabId, createTabsState, TabsStateContext } from '@/state/tabs'-import { customRender } from '@/tests/lib/custom-render'-import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'-import { setupSqlEditorMocks } from '@/tests/lib/sql-editor-test-utils'--const PROJECT_REF = 'default'-const NOTEBOOK_ID = 'notebook-assistant-cache-test'--vi.mock('common', async (importOriginal) => {- const actual = await importOriginal<typeof import('common')>()- return {- ...actual,- IS_PLATFORM: true,- useParams: () => ({ ref: 'default', id: 'notebook-assistant-cache-test' }),- useFlag: () => false,- }-})--vi.mock('@/components/ui/CodeEditor/CodeEditor', () => ({- CodeEditor: ({ value }: { value: string }) => (- <textarea aria-label="SQL editor" value={value} readOnly />- ),-}))--vi.mock('../QueryEditor/QuerySourceMenu', () => ({- QuerySourceMenu: () => null,-}))--const seedNotebook = () => {- delete notebooksState.notebooks[NOTEBOOK_ID]- const notebook: Notebook = {- id: NOTEBOOK_ID,- type: 'notebook',- name: 'Test notebook',- visibility: 'project',- favorite: false,- owner_id: 1,- project_id: 1,- content: {- schema_version: 1,- cells: [{ _tag: 'markdown_cell', _id: 'cell-1', text: 'Original content' }],- },- }- notebooksState.setNotebook({ projectRef: PROJECT_REF, notebook })-}--const renderNotebookTab = (queryClient: QueryClient, tabsState = createTabsState(PROJECT_REF)) =>- customRender(- <TabsStateContext.Provider value={tabsState}>- <ExplorerProvider>- <ExplorerNotebookTab />- </ExplorerProvider>- </TabsStateContext.Provider>,- { queryClient }- )--afterEach(() => {- notebooksState.serverDivergedWhileDirty.clear()-})--describe('ExplorerNotebookTab — assistant cache invalidation', () => {- it('refetches and renders the updated cells after an assistant update_notebook tool call completes', async () => {- setupSqlEditorMocks()- seedNotebook()-- const queryClient = new QueryClient()- queryClient.setQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID), { id: NOTEBOOK_ID })-- addAPIMock({- method: 'get',- path: '/platform/projects/:ref/content/item/:id',- response: () =>- HttpResponse.json<components['schemas']['GetUserContentByIdResponse_Output']>({- id: NOTEBOOK_ID,- type: 'notebook',- name: 'Test notebook',- description: '',- favorite: false,- folder_id: null,- inserted_at: '2024-01-01T00:00:00.000Z',- updated_at: '2024-01-02T00:00:00.000Z',- visibility: 'project',- owner_id: 1,- project_id: 1,- content: {- schema_version: 1,- cells: [{ _tag: 'markdown_cell', _id: 'cell-1', text: 'Updated by assistant' }],- },- }),- })-- renderNotebookTab(queryClient)-- expect(await screen.findByText('Original content')).toBeInTheDocument()-- const message = createAssistantMessageWithUpdateNotebookTool({- id: NOTEBOOK_ID,- name: 'Test notebook',- })- const effects = collectNotebookCacheEffects([message], new Set())- await applyNotebookCacheEffects({ queryClient, projectRef: PROJECT_REF, effects })-- expect(await screen.findByText('Updated by assistant')).toBeInTheDocument()- expect(screen.queryByText('Original content')).not.toBeInTheDocument()- })-- it('shows the updated cells on remount, when the query cache still holds the pre-eviction notebook', async () => {- setupSqlEditorMocks()- seedNotebook()-- const queryClient = new QueryClient()- queryClient.setQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID), {- id: NOTEBOOK_ID,- type: 'notebook',- name: 'Test notebook',- description: '',- favorite: false,- visibility: 'project',- owner_id: 1,- project_id: 1,- inserted_at: '2024-01-01T00:00:00.000Z',- updated_at: '2024-01-01T00:00:00.000Z',- content: {- schema_version: 1,- cells: [{ _tag: 'markdown_cell', _id: 'cell-1', text: 'Original content' }],- },- })-- addAPIMock({- method: 'get',- path: '/platform/projects/:ref/content/item/:id',- response: () =>- HttpResponse.json<components['schemas']['GetUserContentByIdResponse_Output']>({- id: NOTEBOOK_ID,- type: 'notebook',- name: 'Test notebook',- description: '',- favorite: false,- folder_id: null,- inserted_at: '2024-01-01T00:00:00.000Z',- updated_at: '2024-01-02T00:00:00.000Z',- visibility: 'project',- owner_id: 1,- project_id: 1,- content: {- schema_version: 1,- cells: [{ _tag: 'markdown_cell', _id: 'cell-1', text: 'Updated by assistant' }],- },- }),- })-- // While the tab is unmounted (navigated away to a separate Explorer chat tab), the- // assistant updates the notebook.- const message = createAssistantMessageWithUpdateNotebookTool({- id: NOTEBOOK_ID,- name: 'Test notebook',- })- const effects = collectNotebookCacheEffects([message], new Set())- await applyNotebookCacheEffects({ queryClient, projectRef: PROJECT_REF, effects })-- // Simulate navigating back: the notebook tab mounts fresh.- renderNotebookTab(queryClient)-- expect(await screen.findByText('Updated by assistant')).toBeInTheDocument()- expect(screen.queryByText('Original content')).not.toBeInTheDocument()- })-- it('shows the not-found state after an assistant delete_notebook tool call completes', async () => {- setupSqlEditorMocks()- seedNotebook()-- const queryClient = new QueryClient()- queryClient.setQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID), { id: NOTEBOOK_ID })-- addAPIMock({- method: 'get',- path: '/platform/projects/:ref/content/item/:id',- response: () =>- HttpResponse.json<APIErrorBody>({ message: 'Notebook not found' }, { status: 404 }),- })-- renderNotebookTab(queryClient)-- expect(await screen.findByText('Original content')).toBeInTheDocument()-- const message = createAssistantMessageWithDeleteNotebookTool({- id: NOTEBOOK_ID,- name: 'Test notebook',- })- const effects = collectNotebookCacheEffects([message], new Set())- await applyNotebookCacheEffects({ queryClient, projectRef: PROJECT_REF, effects })-- expect(await screen.findByText('Notebook not found')).toBeInTheDocument()- expect(screen.queryByText('Original content')).not.toBeInTheDocument()- })-- it('saves normally without a conflict dialog when the notebook has not diverged', async () => {- setupSqlEditorMocks()- seedNotebook()- const queryClient = new QueryClient()- let mutationCount = 0- addAPIMock({- method: 'put',- path: '/platform/projects/:ref/content',- response: () => {- mutationCount += 1- return HttpResponse.json({ id: NOTEBOOK_ID })- },- })-- renderNotebookTab(queryClient)-- await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))-- await waitFor(() => expect(mutationCount).toBe(1))- expect(- screen.queryByRole('dialog', { name: 'Notebook changed on the server' })- ).not.toBeInTheDocument()- })-- it.each([- {- type: 'updated' as const,- description:- 'This notebook changed on the server after your local changes. Saving will overwrite those changes.',- saveLabel: 'Save anyway',- },- {- type: 'deleted' as const,- description:- 'This notebook was deleted on the server after your local changes. Saving will recreate it.',- saveLabel: 'Recreate',- },- ])('shows the $type conflict copy before saving', async ({ type, description, saveLabel }) => {- setupSqlEditorMocks()- seedNotebook()- notebooksState.updateCells({- id: NOTEBOOK_ID,- cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,- })- notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type })-- renderNotebookTab(new QueryClient())-- await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))-- const dialog = await screen.findByRole('dialog', { name: 'Notebook changed on the server' })- expect(dialog).toHaveTextContent(description)- expect(dialog).toHaveTextContent(saveLabel)- expect(dialog).toHaveTextContent('Discard changes')- })-- it('saves exactly once and clears the conflict only after a successful save', async () => {- setupSqlEditorMocks()- seedNotebook()- notebooksState.updateCells({- id: NOTEBOOK_ID,- cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,- })- notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type: 'updated' })- const queryClient = new QueryClient()- let mutationCount = 0- let resolveSave: (() => void) | undefined- const savePromise = new Promise<void>((resolve) => {- resolveSave = resolve- })- addAPIMock({- method: 'put',- path: '/platform/projects/:ref/content',- response: async () => {- mutationCount += 1- await savePromise- return HttpResponse.json({ id: NOTEBOOK_ID })- },- })-- renderNotebookTab(queryClient)-- await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))- expect(notebooksState.serverDivergedWhileDirty.get(NOTEBOOK_ID)).toBe('updated')- await userEvent.click(await screen.findByRole('button', { name: 'Save anyway' }))-- await waitFor(() => expect(mutationCount).toBe(1))- expect(notebooksState.serverDivergedWhileDirty.get(NOTEBOOK_ID)).toBe('updated')- resolveSave?.()- await waitFor(() =>- expect(notebooksState.serverDivergedWhileDirty.has(NOTEBOOK_ID)).toBe(false)- )- })-- it('keeps the conflict marker when saving anyway fails', async () => {- setupSqlEditorMocks()- seedNotebook()- notebooksState.updateCells({- id: NOTEBOOK_ID,- cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,- })- notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type: 'updated' })- let mutationCount = 0- addAPIMock({- method: 'put',- path: '/platform/projects/:ref/content',- response: () => {- mutationCount += 1- return HttpResponse.json({ message: 'Save failed' }, { status: 500 })- },- })-- renderNotebookTab(new QueryClient())-- await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))- await userEvent.click(await screen.findByRole('button', { name: 'Save anyway' }))-- await waitFor(() => expect(mutationCount).toBe(1))- expect(notebooksState.serverDivergedWhileDirty.get(NOTEBOOK_ID)).toBe('updated')- })-- it('omits existing cell IDs when saving anyway recreates an assistant-deleted notebook', async () => {- setupSqlEditorMocks()- seedNotebook()- notebooksState.updateCells({- id: NOTEBOOK_ID,- cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,- })- notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type: 'deleted' })- let sentBody: Record<string, unknown> | undefined- addAPIMock({- method: 'put',- path: '/platform/projects/:ref/content',- response: async ({ request }) => {- sentBody = (await request.json()) as Record<string, unknown>- return HttpResponse.json({ id: NOTEBOOK_ID })- },- })-- renderNotebookTab(new QueryClient())-- await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))- await userEvent.click(await screen.findByRole('button', { name: 'Recreate' }))-- await waitFor(() => expect(sentBody).toBeDefined())- const content = sentBody?.content as { cells: Array<Record<string, unknown>> }- content.cells.forEach((cell) => expect(cell).not.toHaveProperty('_id'))- })-- it('discards local changes without mutating and evicts the conflicted notebook', async () => {- setupSqlEditorMocks()- seedNotebook()- notebooksState.updateCells({- id: NOTEBOOK_ID,- cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,- })- notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type: 'updated' })- const queryClient = new QueryClient()- queryClient.setQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID), { id: NOTEBOOK_ID })- let mutationCount = 0- addAPIMock({- method: 'put',- path: '/platform/projects/:ref/content',- response: () => {- mutationCount += 1- return HttpResponse.json({ id: NOTEBOOK_ID })- },- })-- renderNotebookTab(queryClient)-- await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))- await userEvent.click(await screen.findByRole('button', { name: 'Discard changes' }))-- await waitFor(() => expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeUndefined())- expect(notebooksState.serverDivergedWhileDirty.has(NOTEBOOK_ID)).toBe(false)- expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toBeUndefined()- expect(mutationCount).toBe(0)- })-- it('closes the notebook tab when discarding edits after an assistant deletion', async () => {- setupSqlEditorMocks()- seedNotebook()- notebooksState.updateCells({- id: NOTEBOOK_ID,- cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,- })- notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type: 'deleted' })- const tabsState = createTabsState(PROJECT_REF)- const tabId = createTabId('notebook', { id: NOTEBOOK_ID })- tabsState.addTab({ id: tabId, type: 'notebook', metadata: { notebookId: NOTEBOOK_ID } })-- renderNotebookTab(new QueryClient(), tabsState)-- await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))- await userEvent.click(await screen.findByRole('button', { name: 'Discard changes' }))-- await waitFor(() => expect(tabsState.tabsMap[tabId]).toBeUndefined())- })-- it.each(['the close button', 'the backdrop'])(- 'dismisses the conflict with %s without changing notebook state',- async (dismissal) => {- setupSqlEditorMocks()- seedNotebook()- notebooksState.updateCells({- id: NOTEBOOK_ID,- cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,- })- notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type: 'updated' })-- renderNotebookTab(new QueryClient())-- await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))- const dialog = await screen.findByRole('dialog', { name: 'Notebook changed on the server' })- if (dismissal === 'the close button') {- await userEvent.click(screen.getByRole('button', { name: 'Close' }))- } else {- fireEvent.pointerDown(dialog.parentElement!, { button: 0, ctrlKey: false })- }-- await waitFor(() =>- expect(- screen.queryByRole('dialog', { name: 'Notebook changed on the server' })- ).not.toBeInTheDocument()- )- expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeDefined()- expect(notebooksState.serverDivergedWhileDirty.get(NOTEBOOK_ID)).toBe('updated')- }- )-})diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsxindex 5f651c72d9f..71fea568ef9 100644--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx@@ -1,3 +1,4 @@+import { QueryClient } from '@tanstack/react-query'import { fireEvent, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { LOCAL_STORAGE_KEYS, safeLocalStorage } from 'common'@@ -8,13 +9,23 @@ import { ExplorerNotebookTab } from '../ExplorerNotebookTab'import { setCellSql } from '../QueryCell/QueryCell.utils'import { createMarkdownCellSkeleton, createQueryCellSkeleton } from '../utils'import { ExplorerProvider } from '@/components/layouts/ExplorerLayout/ExplorerProvider'+import type { components } from '@/data/api'+import { contentKeys } from '@/data/content/keys'import { isQueryCell } from '@/data/content/notebooks/notebook-schema'import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'+import {+ applyNotebookCacheEffects,+ collectNotebookCacheEffects,+} from '@/lib/ai/notebook-cache-invalidation'+import {+ createAssistantMessageWithDeleteNotebookTool,+ createAssistantMessageWithUpdateNotebookTool,+} from '@/lib/ai/test-fixtures'import { notebooksState } from '@/state/notebooks/notebooks-state'import type { Notebook } from '@/state/notebooks/types'import { createTabId, createTabsState, TabsStateContext } from '@/state/tabs'import { customRender } from '@/tests/lib/custom-render'-import { addAPIMock } from '@/tests/lib/msw'+import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'import { setupSqlEditorMocks } from '@/tests/lib/sql-editor-test-utils'import type { Notebooks } from '@/types'@@ -55,6 +66,7 @@ vi.mock('../QueryEditor/QuerySourceMenu', () => ({QuerySourceMenu: () => null,}))+const PROJECT_REF = 'default'const NOTEBOOK_ID = 'notebook-test'const databaseCell = createQueryCellSkeleton({ sql: 'select 1' })@@ -85,13 +97,17 @@ const seedNotebook = (cells: Notebooks.Cell[], status: 'new' | 'saved' = 'saved'else notebooksState.setNotebook({ projectRef: 'default', notebook })}-const renderNotebookTab = (tabsState = createTabsState('default')) =>+const renderNotebookTab = ({+ tabsState = createTabsState(PROJECT_REF),+ queryClient,+}: { tabsState?: ReturnType<typeof createTabsState>; queryClient?: QueryClient } = {}) =>customRender(<TabsStateContext.Provider value={tabsState}><ExplorerProvider><ExplorerNotebookTab /></ExplorerProvider>- </TabsStateContext.Provider>+ </TabsStateContext.Provider>,+ { queryClient })// `useAddDefinitions` fires its own background keywords/functions/schemas/table-columns@@ -134,6 +150,7 @@ beforeEach(() => {afterEach(() => {notebooksState.needsSaving.clear()notebooksState.cellLocalState.clear()+ notebooksState.serverDivergedWhileDirty.clear()safeLocalStorage.removeItem(LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE)})@@ -228,18 +245,6 @@ describe('ExplorerNotebookTab', () => {seedNotebook([readOnlyCell, mutatingCell])})- it('opens a confirmation modal instead of running immediately when a cell mutates data', async () => {- const queries = mockDatabaseQueryRequests()-- renderNotebookTab()-- await userEvent.click(await screen.findByRole('button', { name: 'Run notebook' }))-- const dialog = await screen.findByRole('dialog', { name: 'Confirm to run notebook' })- expect(within(dialog).getByText('Mutating query')).toBeInTheDocument()- expect(queries).toHaveLength(0)- })-it('runs no cells when the confirmation is cancelled', async () => {const queries = mockDatabaseQueryRequests()@@ -276,23 +281,6 @@ describe('ExplorerNotebookTab', () => {expect(queries.some((query) => query.includes('delete from foo'))).toBe(true)})- it('runs no cells when the combined confirmation is cancelled', async () => {- const queries = mockDatabaseQueryRequests()-- renderNotebookTab()-- await userEvent.click(await screen.findByRole('button', { name: 'Run notebook' }))- const dialog = await screen.findByRole('dialog', { name: 'Confirm to run notebook' })- await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))-- await waitFor(() =>- expect(- screen.queryByRole('dialog', { name: 'Confirm to run notebook' })- ).not.toBeInTheDocument()- )- expect(queries).toHaveLength(0)- })-it('does not label non-destructive mutations', async () => {seedNotebook([readOnlyCell,@@ -422,7 +410,7 @@ describe('ExplorerNotebookTab', () => {tabsState.addTab({ id: tabId, type: 'notebook', metadata: { notebookId: NOTEBOOK_ID } })expect(tabsState.tabsMap[tabId]?.isPreview).toBe(true)- renderNotebookTab(tabsState)+ renderNotebookTab({ tabsState })const saveButton = await screen.findByRole('button', { name: 'Save changes' })await userEvent.click(saveButton)@@ -512,3 +500,300 @@ describe('ExplorerNotebookTab', () => {expect(notebooksState.notebooks[NOTEBOOK_ID]?.status).toBe('unsaved')})})++describe('ExplorerNotebookTab — assistant cache invalidation', () => {+ const seedMarkdownNotebook = () =>+ seedNotebook([{ _tag: 'markdown_cell', _id: 'cell-1', text: 'Original content' }])++ /** Seeds a dirty notebook that the server changed (or deleted) underneath it. */+ const seedDivergedNotebook = (type: 'updated' | 'deleted') => {+ seedMarkdownNotebook()+ notebooksState.updateCells({+ id: NOTEBOOK_ID,+ cells: notebooksState.notebooks[NOTEBOOK_ID]!.notebook.content!.cells,+ })+ notebooksState.markServerDivergence({ id: NOTEBOOK_ID, type })+ }++ const mockUpdatedNotebookFetch = () =>+ addAPIMock({+ method: 'get',+ path: '/platform/projects/:ref/content/item/:id',+ response: () =>+ HttpResponse.json<components['schemas']['GetUserContentByIdResponse_Output']>({+ id: NOTEBOOK_ID,+ type: 'notebook',+ name: 'Test notebook',+ description: '',+ favorite: false,+ folder_id: null,+ inserted_at: '2024-01-01T00:00:00.000Z',+ updated_at: '2024-01-02T00:00:00.000Z',+ visibility: 'project',+ owner_id: 1,+ project_id: 1,+ content: {+ schema_version: 1,+ cells: [{ _tag: 'markdown_cell', _id: 'cell-1', text: 'Updated by assistant' }],+ },+ }),+ })++ /** Mocks the save endpoint and returns a counter of save requests. */+ const mockSave = (response: () => Response | Promise<Response>) => {+ const saves = { count: 0 }+ addAPIMock({+ method: 'put',+ path: '/platform/projects/:ref/content',+ response: () => {+ saves.count += 1+ return response()+ },+ })+ return saves+ }++ const applyAssistantMessage = (+ queryClient: QueryClient,+ message: Parameters<typeof collectNotebookCacheEffects>[0][number]+ ) =>+ applyNotebookCacheEffects({+ queryClient,+ projectRef: PROJECT_REF,+ effects: collectNotebookCacheEffects([message], new Set()),+ })++ beforeEach(() => {+ seedMarkdownNotebook()+ })++ it('refetches and renders the updated cells after an assistant update_notebook tool call completes', async () => {+ const queryClient = new QueryClient()+ queryClient.setQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID), { id: NOTEBOOK_ID })+ mockUpdatedNotebookFetch()++ renderNotebookTab({ queryClient })++ expect(await screen.findByText('Original content')).toBeInTheDocument()++ await applyAssistantMessage(+ queryClient,+ createAssistantMessageWithUpdateNotebookTool({ id: NOTEBOOK_ID, name: 'Test notebook' })+ )++ expect(await screen.findByText('Updated by assistant')).toBeInTheDocument()+ expect(screen.queryByText('Original content')).not.toBeInTheDocument()+ })++ it('shows the updated cells on remount, when the query cache still holds the pre-eviction notebook', async () => {+ const queryClient = new QueryClient()+ queryClient.setQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID), {+ id: NOTEBOOK_ID,+ type: 'notebook',+ name: 'Test notebook',+ description: '',+ favorite: false,+ visibility: 'project',+ owner_id: 1,+ project_id: 1,+ inserted_at: '2024-01-01T00:00:00.000Z',+ updated_at: '2024-01-01T00:00:00.000Z',+ content: {+ schema_version: 1,+ cells: [{ _tag: 'markdown_cell', _id: 'cell-1', text: 'Original content' }],+ },+ })+ mockUpdatedNotebookFetch()++ // While the tab is unmounted (navigated away to a separate Explorer chat tab), the+ // assistant updates the notebook.+ await applyAssistantMessage(+ queryClient,+ createAssistantMessageWithUpdateNotebookTool({ id: NOTEBOOK_ID, name: 'Test notebook' })+ )++ // Simulate navigating back: the notebook tab mounts fresh.+ renderNotebookTab({ queryClient })++ expect(await screen.findByText('Updated by assistant')).toBeInTheDocument()+ expect(screen.queryByText('Original content')).not.toBeInTheDocument()+ })++ it('shows the not-found state after an assistant delete_notebook tool call completes', async () => {+ const queryClient = new QueryClient()+ queryClient.setQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID), { id: NOTEBOOK_ID })+ addAPIMock({+ method: 'get',+ path: '/platform/projects/:ref/content/item/:id',+ response: () =>+ HttpResponse.json<APIErrorBody>({ message: 'Notebook not found' }, { status: 404 }),+ })++ renderNotebookTab({ queryClient })++ expect(await screen.findByText('Original content')).toBeInTheDocument()++ await applyAssistantMessage(+ queryClient,+ createAssistantMessageWithDeleteNotebookTool({ id: NOTEBOOK_ID, name: 'Test notebook' })+ )++ expect(await screen.findByText('Notebook not found')).toBeInTheDocument()+ expect(screen.queryByText('Original content')).not.toBeInTheDocument()+ })++ it('saves normally without a conflict dialog when the notebook has not diverged', async () => {+ const saves = mockSave(() => HttpResponse.json({ id: NOTEBOOK_ID }))++ renderNotebookTab()++ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))++ await waitFor(() => expect(saves.count).toBe(1))+ expect(+ screen.queryByRole('dialog', { name: 'Notebook changed on the server' })+ ).not.toBeInTheDocument()+ })++ it.each([+ {+ type: 'updated' as const,+ description:+ 'This notebook changed on the server after your local changes. Saving will overwrite those changes.',+ saveLabel: 'Save anyway',+ },+ {+ type: 'deleted' as const,+ description:+ 'This notebook was deleted on the server after your local changes. Saving will recreate it.',+ saveLabel: 'Recreate',+ },+ ])('shows the $type conflict copy before saving', async ({ type, description, saveLabel }) => {+ seedDivergedNotebook(type)++ renderNotebookTab()++ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))++ const dialog = await screen.findByRole('dialog', { name: 'Notebook changed on the server' })+ expect(dialog).toHaveTextContent(description)+ expect(dialog).toHaveTextContent(saveLabel)+ expect(dialog).toHaveTextContent('Discard changes')+ })++ it('saves exactly once and clears the conflict only after a successful save', async () => {+ seedDivergedNotebook('updated')+ let resolveSave: (() => void) | undefined+ const savePromise = new Promise<void>((resolve) => {+ resolveSave = resolve+ })+ const saves = mockSave(async () => {+ await savePromise+ return HttpResponse.json({ id: NOTEBOOK_ID })+ })++ renderNotebookTab()++ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))+ expect(notebooksState.serverDivergedWhileDirty.get(NOTEBOOK_ID)).toBe('updated')+ await userEvent.click(await screen.findByRole('button', { name: 'Save anyway' }))++ await waitFor(() => expect(saves.count).toBe(1))+ expect(notebooksState.serverDivergedWhileDirty.get(NOTEBOOK_ID)).toBe('updated')+ resolveSave?.()+ await waitFor(() =>+ expect(notebooksState.serverDivergedWhileDirty.has(NOTEBOOK_ID)).toBe(false)+ )+ })++ it('keeps the conflict marker when saving anyway fails', async () => {+ seedDivergedNotebook('updated')+ const saves = mockSave(() => HttpResponse.json({ message: 'Save failed' }, { status: 500 }))++ renderNotebookTab()++ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))+ await userEvent.click(await screen.findByRole('button', { name: 'Save anyway' }))++ await waitFor(() => expect(saves.count).toBe(1))+ expect(notebooksState.serverDivergedWhileDirty.get(NOTEBOOK_ID)).toBe('updated')+ })++ it('omits existing cell IDs when saving anyway recreates an assistant-deleted notebook', async () => {+ seedDivergedNotebook('deleted')+ let sentBody: Record<string, unknown> | undefined+ addAPIMock({+ method: 'put',+ path: '/platform/projects/:ref/content',+ response: async ({ request }) => {+ sentBody = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ id: NOTEBOOK_ID })+ },+ })++ renderNotebookTab()++ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))+ await userEvent.click(await screen.findByRole('button', { name: 'Recreate' }))++ await waitFor(() => expect(sentBody).toBeDefined())+ const content = sentBody?.content as { cells: Array<Record<string, unknown>> }+ content.cells.forEach((cell) => expect(cell).not.toHaveProperty('_id'))+ })++ it('discards local changes without mutating and evicts the conflicted notebook', async () => {+ seedDivergedNotebook('updated')+ const queryClient = new QueryClient()+ queryClient.setQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID), { id: NOTEBOOK_ID })+ const saves = mockSave(() => HttpResponse.json({ id: NOTEBOOK_ID }))++ renderNotebookTab({ queryClient })++ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))+ await userEvent.click(await screen.findByRole('button', { name: 'Discard changes' }))++ await waitFor(() => expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeUndefined())+ expect(notebooksState.serverDivergedWhileDirty.has(NOTEBOOK_ID)).toBe(false)+ expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toBeUndefined()+ expect(saves.count).toBe(0)+ })++ it('closes the notebook tab when discarding edits after an assistant deletion', async () => {+ seedDivergedNotebook('deleted')+ const tabsState = createTabsState(PROJECT_REF)+ const tabId = createTabId('notebook', { id: NOTEBOOK_ID })+ tabsState.addTab({ id: tabId, type: 'notebook', metadata: { notebookId: NOTEBOOK_ID } })++ renderNotebookTab({ tabsState })++ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))+ await userEvent.click(await screen.findByRole('button', { name: 'Discard changes' }))++ await waitFor(() => expect(tabsState.tabsMap[tabId]).toBeUndefined())+ })++ it.each(['the close button', 'the backdrop'])(+ 'dismisses the conflict with %s without changing notebook state',+ async (dismissal) => {+ seedDivergedNotebook('updated')++ renderNotebookTab()++ await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))+ const dialog = await screen.findByRole('dialog', { name: 'Notebook changed on the server' })+ if (dismissal === 'the close button') {+ await userEvent.click(screen.getByRole('button', { name: 'Close' }))+ } else {+ fireEvent.pointerDown(dialog.parentElement!, { button: 0, ctrlKey: false })+ }++ await waitFor(() =>+ expect(+ screen.queryByRole('dialog', { name: 'Notebook changed on the server' })+ ).not.toBeInTheDocument()+ )+ expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeDefined()+ expect(notebooksState.serverDivergedWhileDirty.get(NOTEBOOK_ID)).toBe('updated')+ }+ )+})diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTabCoordinator.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTabCoordinator.test.tsxindex 2a167aa22e9..e5fd3d9732c 100644--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTabCoordinator.test.tsx+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTabCoordinator.test.tsx@@ -53,6 +53,15 @@ const renderCoordinator = (queryClient: QueryClient) => {return { tabsState, tabId }}+const persistLocalDraft = () =>+ persistNotebookDraft({+ projectRef: 'default',+ id: NOTEBOOK_ID,+ name: 'Test notebook',+ content: { schema_version: 1, cells: [createQueryCellSkeleton()] },+ baseUpdatedAt: null,+ })+afterEach(() => {delete notebooksState.notebooks[NOTEBOOK_ID]notebooksState.needsSaving.clear()@@ -60,20 +69,11 @@ afterEach(() => {})describe('ExplorerNotebookTabCoordinator', () => {- it('flushes a saved notebook from the store and evicts its cache entry on close', () => {- seedNotebook('saved')- const queryClient = new QueryClient()- queryClient.setQueryData(contentKeys.resource('default', NOTEBOOK_ID), { id: NOTEBOOK_ID })-- const { tabsState, tabId } = renderCoordinator(queryClient)- tabsState.closeTabs([tabId])-- expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeUndefined()- expect(queryClient.getQueryData(contentKeys.resource('default', NOTEBOOK_ID))).toBeUndefined()- })-- it('discards an unsaved notebook from the store and cache on confirmed close', () => {- seedNotebook('new', [createQueryCellSkeleton()])+ it.each([+ ['flushes a saved notebook', 'saved' as const, []],+ ['discards an unsaved notebook', 'new' as const, [createQueryCellSkeleton()]],+ ])('%s from the store and evicts its cache entry on close', (_, status, cells) => {+ seedNotebook(status, cells)const queryClient = new QueryClient()queryClient.setQueryData(contentKeys.resource('default', NOTEBOOK_ID), { id: NOTEBOOK_ID })@@ -109,13 +109,7 @@ describe('ExplorerNotebookTabCoordinator', () => {})it('asks for confirmation before closing a notebook with only a local draft, never loaded this session', () => {- persistNotebookDraft({- projectRef: 'default',- id: NOTEBOOK_ID,- name: 'Test notebook',- content: { schema_version: 1, cells: [createQueryCellSkeleton()] },- baseUpdatedAt: null,- })+ persistLocalDraft()const { tabsState, tabId } = renderCoordinator(new QueryClient())expect(tabsState.getCloseConfirmation([tabId])).toEqual({@@ -125,13 +119,7 @@ describe('ExplorerNotebookTabCoordinator', () => {})it('removes a notebook local draft on close, even if it was never loaded into the store', () => {- persistNotebookDraft({- projectRef: 'default',- id: NOTEBOOK_ID,- name: 'Test notebook',- content: { schema_version: 1, cells: [createQueryCellSkeleton()] },- baseUpdatedAt: null,- })+ persistLocalDraft()const { tabsState, tabId } = renderCoordinator(new QueryClient())tabsState.closeTabs([tabId])@@ -140,13 +128,7 @@ describe('ExplorerNotebookTabCoordinator', () => {})it('shows the status dot for a notebook with only a local draft, never loaded this session', () => {- persistNotebookDraft({- projectRef: 'default',- id: NOTEBOOK_ID,- name: 'Test notebook',- content: { schema_version: 1, cells: [createQueryCellSkeleton()] },- baseUpdatedAt: null,- })+ persistLocalDraft()const { tabsState, tabId } = renderCoordinator(new QueryClient())const StatusIndicator = tabsState.getTabStatusIndicator('notebook')!diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerQuery.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerQuery.test.tsxindex 7df4c9fc8e0..a6d7fc587fa 100644--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerQuery.test.tsx+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerQuery.test.tsx@@ -27,7 +27,6 @@ describe('ExplorerQuery', () => {const cell = screen.getByLabelText('Weekly signups query')expect(cell).toHaveAttribute('data-slot', 'explorer-query')expect(cell).toHaveAttribute('data-variant', 'embedded')- expect(cell).toHaveClass('rounded-md', 'border')expect(screen.getByRole('toolbar', { name: 'Explorer query toolbar' })).toBeInTheDocument()expect(cell.querySelector('[data-slot="explorer-query-editor"]')).toHaveTextContent('SQL editor'@@ -56,8 +55,7 @@ describe('ExplorerQuery', () => {const viewport = screen.getByLabelText('Explorer query tab')expect(viewport).toHaveAttribute('data-variant', 'viewport')expect(viewport).toHaveAttribute('data-density', 'compact')- expect(viewport).toHaveClass('h-full', 'min-h-0', 'custom-viewport')- expect(viewport).not.toHaveClass('rounded-md')+ expect(viewport).toHaveClass('custom-viewport')expect(viewportRef.current).toBe(viewport)})diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerToolbar.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerToolbar.test.tsxindex ff889ca523a..eead9e608ee 100644--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerToolbar.test.tsx+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerToolbar.test.tsx@@ -12,42 +12,16 @@ import {import { customRender as render } from '@/tests/lib/custom-render'describe('ExplorerToolbar', () => {- it('composes the resource icon, title, direct actions, and custom controls', () => {+ it('composes the icon, title, icon and labeled actions, and forwards refs and native props', () => {+ const actionRef = createRef<HTMLButtonElement>()+render(- <ExplorerToolbar aria-label="Explorer query toolbar">+ <ExplorerToolbar aria-label="Explorer query toolbar" data-density="compact"><ExplorerToolbarIcon>Q</ExplorerToolbarIcon><ExplorerToolbarTitle>Weekly signups</ExplorerToolbarTitle><ExplorerToolbarActions><span data-testid="source-menu">Database</span><ExplorerToolbarAction aria-label="Run cell" icon={<span>R</span>} />- </ExplorerToolbarActions>- </ExplorerToolbar>- )-- const toolbar = screen.getByRole('toolbar', { name: 'Explorer query toolbar' })- expect(toolbar).toHaveAttribute('data-slot', 'explorer-toolbar')- expect(toolbar.querySelector('[data-slot="explorer-toolbar-icon"]')).toHaveTextContent('Q')- expect(toolbar.querySelector('[data-slot="explorer-toolbar-title"]')).toHaveTextContent(- 'Weekly signups'- )- expect(within(toolbar).getByTestId('source-menu')).toBeInTheDocument()-- const runAction = within(toolbar).getByRole('button', { name: 'Run cell' })- expect(runAction).toHaveAttribute('data-slot', 'explorer-toolbar-action')- expect(runAction).toHaveAttribute('data-size', 'tiny')- })-- it('supports labeled actions and forwards refs and native props', () => {- const actionRef = createRef<HTMLButtonElement>()-- render(- <ExplorerToolbar- aria-label="Notebook toolbar"- className="custom-toolbar"- data-density="compact"- >- <ExplorerToolbarTitle>Authentication health</ExplorerToolbarTitle>- <ExplorerToolbarActions><ExplorerToolbarAction ref={actionRef} data-command="analyze">Analyze</ExplorerToolbarAction>@@ -55,15 +29,15 @@ describe('ExplorerToolbar', () => {</ExplorerToolbar>)- const toolbar = screen.getByRole('toolbar', { name: 'Notebook toolbar' })- const action = within(toolbar).getByRole('button', { name: 'Analyze' })-- expect(toolbar).toHaveClass('custom-toolbar')+ const toolbar = screen.getByRole('toolbar', { name: 'Explorer query toolbar' })expect(toolbar).toHaveAttribute('data-density', 'compact')- expect(toolbar.querySelector('[data-slot="explorer-toolbar-actions"]')).toHaveClass('gap-px')+ expect(toolbar).toHaveTextContent('Q')+ expect(toolbar).toHaveTextContent('Weekly signups')+ expect(within(toolbar).getByTestId('source-menu')).toBeInTheDocument()+ expect(within(toolbar).getByRole('button', { name: 'Run cell' })).toBeInTheDocument()++ const action = within(toolbar).getByRole('button', { name: 'Analyze' })expect(action).toHaveAttribute('data-command', 'analyze')- expect(action).not.toHaveClass('w-7')- expect(action).toHaveClass('text-tertiary-foreground', 'hover:text-foreground')expect(actionRef.current).toBe(action)})})diff --git a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsxindex 0910f7c752e..a7870539d86 100644--- a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx+++ b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx@@ -220,6 +220,28 @@ const createDraft = (})}+/**+ * Mocks the generic pg-meta query endpoint and returns the SQL of every executed query.+ * Background prefetches (intellisense keywords/functions/schemas/table-columns, event+ * triggers) hit the same endpoint, distinguished from an actual run by their non-empty+ * `key` search param — an executed query's `key` is `''`.+ */+const mockExecutedQueries = () => {+ const executedQueries: string[] = []+ addAPIMock({+ method: 'post',+ path: '/platform/pg-meta/:ref/query',+ response: async ({ request }) => {+ const key = new URL(request.url).searchParams.get('key')+ if (key !== '') return HttpResponse.json([])+ const { query } = (await request.json()) as { query: string }+ executedQueries.push(query)+ return HttpResponse.json([])+ },+ })+ return executedQueries+}+beforeEach(() => {testContext.track.mockClear()setupSqlEditorMocks()@@ -389,21 +411,7 @@ describe('QueryTab execution', () => {return HttpResponse.json<ReadReplicasData>([])},})- // `useAddDefinitions` fires its own background keywords/functions/schemas/table-columns- // fetches against this same generic pg-meta query endpoint (differentiated by the `key`- // search param) as soon as the editor mounts — those are expected and unrelated to the- // actual run. Only a request with no recognized intellisense `key` counts as an execution.- const INTELLISENSE_KEYS = ['keywords', 'database-functions', 'schemas', 'table-columns']- const requests: Request[] = []- addAPIMock({- method: 'post',- path: '/platform/pg-meta/:ref/query',- response: ({ request }) => {- const key = new URL(request.url).searchParams.get('key')- if (!key || !INTELLISENSE_KEYS.includes(key)) requests.push(request)- return HttpResponse.json([])- },- })+ const executedQueries = mockExecutedQueries()renderQueryTab()const runButton = await screen.findByRole('button', { name: 'Run' })@@ -416,7 +424,7 @@ describe('QueryTab execution', () => {expect(await screen.findByText('Error: Unable to run query: Connection string is missing')).toBeInTheDocument()- expect(requests).toHaveLength(0)+ expect(executedQueries).toHaveLength(0)})it('resolves a relative logs range before sending the request', async () => {@@ -483,23 +491,14 @@ describe('QueryTab execution', () => {renderQueryTab(tabsState)const sqlEditor = await screen.findByRole('textbox', { name: 'SQL editor' })- await userEvent.type(sqlEditor, ' where true')+ await userEvent.type(sqlEditor, 'x')await waitFor(() => expect(tabsState.tabsMap[tabId]?.isPreview).toBe(false))})it('blocks a destructive query behind a confirmation modal, then runs it once confirmed', async () => {createDraft({ _tag: 'database' }, 'delete from foo')- const executedQueries: string[] = []- addAPIMock({- method: 'post',- path: '/platform/pg-meta/:ref/query',- response: async ({ request }) => {- const { query } = (await request.json()) as { query: string }- if (query.trim().toLowerCase().startsWith('delete')) executedQueries.push(query)- return HttpResponse.json([])- },- })+ const executedQueries = mockExecutedQueries()renderQueryTab()const runButton = await screen.findByRole('button', { name: 'Run' })@@ -519,16 +518,7 @@ describe('QueryTab execution', () => {it('cancels a blocked query without running it', async () => {createDraft({ _tag: 'database' }, 'update foo set bar = 1')- const executedQueries: string[] = []- addAPIMock({- method: 'post',- path: '/platform/pg-meta/:ref/query',- response: async ({ request }) => {- const { query } = (await request.json()) as { query: string }- if (query.trim().toLowerCase().startsWith('update')) executedQueries.push(query)- return HttpResponse.json([])- },- })+ const executedQueries = mockExecutedQueries()renderQueryTab()const runButton = await screen.findByRole('button', { name: 'Run' })@@ -545,16 +535,7 @@ describe('QueryTab execution', () => {it('runs a CREATE TABLE query with RLS enabled once "Run and enable RLS" is chosen', async () => {createDraft({ _tag: 'database' }, 'create table foo (id int)')- const executedQueries: string[] = []- addAPIMock({- method: 'post',- path: '/platform/pg-meta/:ref/query',- response: async ({ request }) => {- const { query } = (await request.json()) as { query: string }- if (query.trim().toLowerCase().startsWith('create table')) executedQueries.push(query)- return HttpResponse.json([])- },- })+ const executedQueries = mockExecutedQueries()renderQueryTab()const runButton = await screen.findByRole('button', { name: 'Run' })@@ -575,18 +556,7 @@ describe('QueryTab execution', () => {createDraft({ _tag: 'database' }, 'select 1;\nselect 2;')testContext.selectedText = 'select 2;'- const executedQueries: string[] = []- addAPIMock({- method: 'post',- path: '/platform/pg-meta/:ref/query',- response: async ({ request }) => {- const key = new URL(request.url).searchParams.get('key')- if (key !== '') return HttpResponse.json([])- const { query } = (await request.json()) as { query: string }- executedQueries.push(query)- return HttpResponse.json([])- },- })+ const executedQueries = mockExecutedQueries()renderQueryTab()const runButton = await screen.findByRole('button', { name: 'Run' })@@ -602,21 +572,7 @@ describe('QueryTab execution', () => {createDraft({ _tag: 'database' }, 'select 1;\nselect 2;')testContext.selectedText = 'select 2;'- // Background prefetches (intellisense keywords/functions/schemas/table-columns, event- // triggers) hit this same generic pg-meta query endpoint, distinguished from an actual- // run by their non-empty `key` search param — an executed query's `key` is `''`.- const executedQueries: string[] = []- addAPIMock({- method: 'post',- path: '/platform/pg-meta/:ref/query',- response: async ({ request }) => {- const key = new URL(request.url).searchParams.get('key')- if (key !== '') return HttpResponse.json([])- const { query } = (await request.json()) as { query: string }- executedQueries.push(query)- return HttpResponse.json([])- },- })+ const executedQueries = mockExecutedQueries()renderQueryTab()const runButton = await screen.findByRole('button', { name: 'Run' })@@ -634,18 +590,7 @@ describe('QueryTab execution', () => {createDraft({ _tag: 'database' }, 'select 1;\nselect 2;')testContext.selectedText = 'select 2;'- const executedQueries: string[] = []- addAPIMock({- method: 'post',- path: '/platform/pg-meta/:ref/query',- response: async ({ request }) => {- const key = new URL(request.url).searchParams.get('key')- if (key !== '') return HttpResponse.json([])- const { query } = (await request.json()) as { query: string }- executedQueries.push(query)- return HttpResponse.json([])- },- })+ const executedQueries = mockExecutedQueries()renderQueryTab()await userEvent.click(await screen.findByRole('button', { name: 'More actions' }))diff --git a/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsxindex b487ee5903c..ede0a046bbb 100644--- a/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx+++ b/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx@@ -147,18 +147,6 @@ describe('useCreateQuery', () => {expect(mockPush).toHaveBeenCalledWith('/project/default/explorer/query/query-new')})- it('creates an empty draft when no sql or name is provided', () => {- const { result } = renderHook(() => useCreateQuery())-- expect(result.current.createQuery()).toBe('query-new')- expect(mockCreateDraft).toHaveBeenCalledWith({- id: 'query-new',- projectRef: 'default',- sql: undefined,- name: undefined,- })- })-it('forwards autoRun to the draft so its query tab can run itself once mounted', () => {const { result } = renderHook(() => useCreateQuery())diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionOverview.utils.test.ts b/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionOverview.utils.test.tsindex 8a56f8e64b8..d846a19e5be 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionOverview.utils.test.ts+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionOverview.utils.test.ts@@ -24,12 +24,6 @@ import {} from './EdgeFunctionOverview.utils'describe('EdgeFunctionOverview.utils', () => {- it('uses a full day interval for the 1 day option', () => {- expect(- EDGE_FUNCTION_CHART_INTERVALS.find((interval) => interval.key === '1day')?.startUnit- ).toBe('day')- })-it('builds invocation chart data and totals from combined stats', () => {const chartData = toEdgeFunctionChartData([{@@ -153,39 +147,28 @@ describe('EdgeFunctionOverview.utils', () => {})})- it('returns a snapped deploy annotation when updated_at falls within the selected window', () => {- const annotation = getInvocationUpdateAnnotation({- updatedAt: '2026-03-20T10:16:30.000Z',- invocationChartData: [- { timestamp: '2026-03-20T10:00:00.000Z', ok_count: 3, warning_count: 0, error_count: 0 },- { timestamp: '2026-03-20T10:15:00.000Z', ok_count: 5, warning_count: 1, error_count: 1 },- { timestamp: '2026-03-20T10:30:00.000Z', ok_count: 2, warning_count: 0, error_count: 0 },- ],- windowStart: new Date('2026-03-20T09:45:00.000Z'),- windowEnd: new Date('2026-03-20T10:45:00.000Z'),- })-- expect(annotation?.timestamp).toBe('2026-03-20T10:15:00.000Z')- expect(annotation?.position).toBeCloseTo(50)- expect(annotation?.updatedAt.toISOString()).toBe('2026-03-20T10:16:30.000Z')- })-- it('returns a deploy annotation for a numeric updated_at timestamp', () => {- const annotation = getInvocationUpdateAnnotation({- updatedAt: new Date('2026-03-20T10:16:30.000Z').valueOf(),- invocationChartData: [- { timestamp: '2026-03-20T10:00:00.000Z', ok_count: 3, warning_count: 0, error_count: 0 },- { timestamp: '2026-03-20T10:15:00.000Z', ok_count: 5, warning_count: 1, error_count: 1 },- { timestamp: '2026-03-20T10:30:00.000Z', ok_count: 2, warning_count: 0, error_count: 0 },- ],- windowStart: new Date('2026-03-20T09:45:00.000Z'),- windowEnd: new Date('2026-03-20T10:45:00.000Z'),- })+ it.each([+ ['an ISO string', '2026-03-20T10:16:30.000Z'],+ ['a numeric', new Date('2026-03-20T10:16:30.000Z').valueOf()],+ ])(+ 'returns a snapped deploy annotation for %s updated_at within the selected window',+ (_, updatedAt) => {+ const annotation = getInvocationUpdateAnnotation({+ updatedAt,+ invocationChartData: [+ { timestamp: '2026-03-20T10:00:00.000Z', ok_count: 3, warning_count: 0, error_count: 0 },+ { timestamp: '2026-03-20T10:15:00.000Z', ok_count: 5, warning_count: 1, error_count: 1 },+ { timestamp: '2026-03-20T10:30:00.000Z', ok_count: 2, warning_count: 0, error_count: 0 },+ ],+ windowStart: new Date('2026-03-20T09:45:00.000Z'),+ windowEnd: new Date('2026-03-20T10:45:00.000Z'),+ })- expect(annotation?.timestamp).toBe('2026-03-20T10:15:00.000Z')- expect(annotation?.position).toBeCloseTo(50)- expect(annotation?.updatedAt.toISOString()).toBe('2026-03-20T10:16:30.000Z')- })+ expect(annotation?.timestamp).toBe('2026-03-20T10:15:00.000Z')+ expect(annotation?.position).toBeCloseTo(50)+ expect(annotation?.updatedAt.toISOString()).toBe('2026-03-20T10:16:30.000Z')+ }+ )it('hides the deploy annotation when updated_at is outside the selected window', () => {const annotation = getInvocationUpdateAnnotation({diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.utils.test.ts b/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.utils.test.tsindex dc3d35d9df4..e62f632fc7d 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.utils.test.ts+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.utils.test.ts@@ -42,45 +42,23 @@ describe('EdgeFunctionRecentErrors.utils', () => {expect(getFunctionRuntimeLogsSql({ functionId: undefined, executionIds: ['abc'] })).toBe('')expect(getFunctionRuntimeLogsSql({ functionId: 'fn_123', executionIds: [] })).toBe('')- expect(- getFunctionRuntimeLogsSql({- functionId: "fn_'123",- executionIds: ['exec_1', "exec_'2"],- limit: 25,- })- ).toBe(`-- runtime logs for error groups-select- toUnixTimestamp64Micro(timestamp) as timestamp,- event_message,- log_attributes['level'] as level,- log_attributes['event_type'] as event_type,- log_attributes['function_id'] as function_id,- log_attributes['execution_id'] as execution_id-from logs-where- source = 'function_logs'- and log_attributes['function_id'] = 'fn_''123'- and log_attributes['execution_id'] in ('exec_1', 'exec_''2')-order by timestamp desc-limit 25`)+ const sql = getFunctionRuntimeLogsSql({+ functionId: "fn_'123",+ executionIds: ['exec_1', "exec_'2"],+ limit: 25,+ })+ expect(sql).toContain("source = 'function_logs'")+ expect(sql).toContain("log_attributes['function_id'] = 'fn_''123'")+ expect(sql).toContain("log_attributes['execution_id'] in ('exec_1', 'exec_''2')")+ expect(sql).toMatch(/limit 25$/)})it('builds recent error invocations SQL and escapes the function id', () => {- expect(getRecentErrorInvocationsSql("fn_'123", 25)).toBe(`-- errors since last deploy-select- toUnixTimestamp64Micro(timestamp) as timestamp,- event_message,- log_attributes['request.method'] as method,- log_attributes['response.status_code'] as status_code,- toFloat64OrZero(log_attributes['execution_time_ms']) as execution_time_ms,- log_attributes['execution_id'] as execution_id-from logs-where- source = 'function_edge_logs'- and log_attributes['function_id'] = 'fn_''123'- and toInt32OrZero(log_attributes['response.status_code']) >= 500-order by timestamp desc-limit 25`)+ const sql = getRecentErrorInvocationsSql("fn_'123", 25)+ expect(sql).toContain("source = 'function_edge_logs'")+ expect(sql).toContain("log_attributes['function_id'] = 'fn_''123'")+ expect(sql).toContain('>= 500')+ expect(sql).toMatch(/limit 25$/)})it('normalizes deploy timestamps and derives the logs query range', () => {diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionRecentInvocations.utils.test.ts b/apps/studio/components/interfaces/Functions/EdgeFunctionRecentInvocations.utils.test.tsindex e5809e2517b..572fcece2b6 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionRecentInvocations.utils.test.ts+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionRecentInvocations.utils.test.ts@@ -2,86 +2,35 @@ import { describe, expect, it } from 'vitest'import { parseEdgeFunctionEventMessage } from './EdgeFunctionRecentInvocations.utils'-describe('parseEdgeFunctionEventMessage', () => {- it('should strip method and status code when they match the structured fields', () => {- const message = 'POST | 200 | https://example.supabase.red/functions/v1/hello-world'- expect(parseEdgeFunctionEventMessage(message, 'POST', '200')).toBe(- 'https://example.supabase.red/functions/v1/hello-world'- )- })-- it('should strip method and status code for different HTTP methods', () => {- const message = 'GET | 404 | https://example.supabase.red/functions/v1/not-found'- expect(parseEdgeFunctionEventMessage(message, 'GET', '404')).toBe(- 'https://example.supabase.red/functions/v1/not-found'- )- })-- it('should strip method and status code for 500 errors', () => {- const message = 'POST | 500 | https://example.supabase.red/functions/v1/broken'- expect(parseEdgeFunctionEventMessage(message, 'POST', '500')).toBe(- 'https://example.supabase.red/functions/v1/broken'- )- })-- it('should preserve the rest of the message when it contains pipe separators', () => {- const message = 'POST | 200 | some | complex | message'- expect(parseEdgeFunctionEventMessage(message, 'POST', '200')).toBe('some | complex | message')- })+const URL_MESSAGE = 'POST | 200 | https://example.supabase.red/functions/v1/hello-world'- it('should return original message when method does not match', () => {- const message = 'POST | 200 | https://example.supabase.red/functions/v1/hello-world'- expect(parseEdgeFunctionEventMessage(message, 'GET', '200')).toBe(message)- })-- it('should return original message when status code does not match', () => {- const message = 'POST | 200 | https://example.supabase.red/functions/v1/hello-world'- expect(parseEdgeFunctionEventMessage(message, 'POST', '500')).toBe(message)- })-- it('should return original message when method is undefined', () => {- const message = 'POST | 200 | https://example.supabase.red/functions/v1/hello-world'- expect(parseEdgeFunctionEventMessage(message, undefined, '200')).toBe(message)- })-- it('should return original message when status code is undefined', () => {- const message = 'POST | 200 | https://example.supabase.red/functions/v1/hello-world'- expect(parseEdgeFunctionEventMessage(message, 'POST', undefined)).toBe(message)- })-- it('should return original message when both method and status code are undefined', () => {- const message = 'POST | 200 | https://example.supabase.red/functions/v1/hello-world'- expect(parseEdgeFunctionEventMessage(message, undefined, undefined)).toBe(message)- })-- it('should return original message when format has fewer than 3 parts', () => {- const message = 'some simple message'- expect(parseEdgeFunctionEventMessage(message, 'POST', '200')).toBe(message)- })-- it('should return original message when format has only 2 pipe-separated parts', () => {- const message = 'POST | 200'- expect(parseEdgeFunctionEventMessage(message, 'POST', '200')).toBe(message)- })-- it('should return empty string for empty input', () => {- expect(parseEdgeFunctionEventMessage('', 'POST', '200')).toBe('')- })-- it('should handle whitespace around parts correctly', () => {- const message = 'POST | 200 | https://example.supabase.red/functions/v1/hello-world'- expect(parseEdgeFunctionEventMessage(message, 'POST', '200')).toBe(- 'https://example.supabase.red/functions/v1/hello-world'- )- })-- it('should return original message when the message does not follow the expected format', () => {- const message = 'Error: function crashed unexpectedly'- expect(parseEdgeFunctionEventMessage(message, 'POST', '500')).toBe(message)- })-- it('should handle messages with extra whitespace in the URL portion', () => {- const message = 'DELETE | 204 | '- expect(parseEdgeFunctionEventMessage(message, 'DELETE', '204')).toBe('')+describe('parseEdgeFunctionEventMessage', () => {+ it.each([+ ['POST', '200', URL_MESSAGE, 'https://example.supabase.red/functions/v1/hello-world'],+ [+ 'GET',+ '404',+ 'GET | 404 | https://example.supabase.red/functions/v1/not-found',+ 'https://example.supabase.red/functions/v1/not-found',+ ],+ ['POST', '200', 'POST | 200 | some | complex | message', 'some | complex | message'],+ ['DELETE', '204', 'DELETE | 204 | ', ''],+ ])(+ 'strips the %s %s prefix when it matches the structured fields',+ (method, status, message, expected) => {+ expect(parseEdgeFunctionEventMessage(message, method, status)).toBe(expected)+ }+ )++ it.each([+ ['method does not match', URL_MESSAGE, 'GET', '200'],+ ['status code does not match', URL_MESSAGE, 'POST', '500'],+ ['method is undefined', URL_MESSAGE, undefined, '200'],+ ['status code is undefined', URL_MESSAGE, 'POST', undefined],+ ['the message is not pipe-separated', 'Error: function crashed unexpectedly', 'POST', '500'],+ ['the message has only 2 parts', 'POST | 200', 'POST', '200'],+ ['the message is empty', '', 'POST', '200'],+ ])('returns the original message when %s', (_, message, method, status) => {+ expect(parseEdgeFunctionEventMessage(message, method, status)).toBe(message)})})diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/AddNewSecretForm.test.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/AddNewSecretForm.test.tsxindex 4ab435cb0e0..d15fe0fe5e6 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/AddNewSecretForm.test.tsx+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/AddNewSecretForm.test.tsx@@ -11,23 +11,6 @@ import { addAPIMock } from '@/tests/lib/msw'const multilineValue = '-----BEGIN CERTIFICATE-----\nline2\nline3\n-----END CERTIFICATE-----'describe('AddNewSecretForm', () => {- test('renders the value field as a textarea so multiline pastes are preserved', () => {- addAPIMock({- method: 'get',- path: '/v1/projects/:ref/secrets',- response: () => HttpResponse.json<ProjectSecret[]>([]),- })-- customRender(<AddNewSecretForm />)-- const nameInput = screen.getByPlaceholderText('e.g. CLIENT_KEY')- expect(nameInput.tagName).toBe('INPUT')-- const textareas = screen.getAllByRole('textbox')- const valueTextarea = textareas.find((el) => el.tagName === 'TEXTAREA')- expect(valueTextarea).toBeDefined()- })-test('submits a multiline value with newlines intact', async () => {const requests: Array<{ ref: string | undefined; body: unknown }> = []addAPIMock({@@ -51,9 +34,12 @@ describe('AddNewSecretForm', () => {await userEvent.type(nameInput, 'SSL_CERT')+ // The value field must be a textarea so multiline pastes are preservedconst textareas = screen.getAllByRole('textbox')- const valueTextarea = textareas.find((el) => el.tagName === 'TEXTAREA')!- await userEvent.type(valueTextarea, multilineValue)+ const valueTextarea = textareas.find((el) => el.tagName === 'TEXTAREA')+ if (!valueTextarea) throw new Error('Expected the secret value field to be a textarea')+ await userEvent.click(valueTextarea)+ await userEvent.paste(multilineValue)fireEvent.click(saveButton)diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.utils.test.ts b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.utils.test.tsindex e16c8d5d2b9..8e84ff835bd 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.utils.test.ts+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/DefaultEdgeFunctionSecrets.utils.test.ts@@ -37,14 +37,7 @@ describe('getVisibleDefaultEdgeFunctionSecrets', () => {(secret) => secret.name)- it('always includes runtime secrets', () => {- const result = getVisibleDefaultEdgeFunctionSecrets(new Set())- for (const name of runtimeNames) {- expect(result.map((secret) => secret.name)).toContain(name)- }- })-- it('falls back to the full hardcoded list when API returned no static defaults', () => {+ it('falls back to the full hardcoded list (incl. runtime secrets) when API returned no static defaults', () => {const result = getVisibleDefaultEdgeFunctionSecrets(new Set())expect(result.map((secret) => secret.name)).toEqual([...staticNames, ...runtimeNames])})diff --git a/apps/studio/components/interfaces/Functions/FunctionsEmptyState.test.tsx b/apps/studio/components/interfaces/Functions/FunctionsEmptyState.test.tsxindex 3686e7e4a0c..22259ec8cf2 100644--- a/apps/studio/components/interfaces/Functions/FunctionsEmptyState.test.tsx+++ b/apps/studio/components/interfaces/Functions/FunctionsEmptyState.test.tsx@@ -53,7 +53,7 @@ describe('FunctionsEmptyState', () => {expect(screen.getByText('Start with a template')).toBeInTheDocument()})- it('hides the templates section on self-hosted (Docker mode)', () => {+ it('hides the templates section and shows the manual card on self-hosted (Docker mode)', () => {mockIsPlatform.value = falsemockUseDeploymentMode.mockReturnValue({isPlatform: false,@@ -64,6 +64,7 @@ describe('FunctionsEmptyState', () => {render(<FunctionsEmptyState />)expect(screen.queryByText('Start with a template')).not.toBeInTheDocument()+ expect(screen.getByText('Self-Hosted')).toBeInTheDocument()})it('hides the templates section on CLI mode', () => {@@ -78,17 +79,4 @@ describe('FunctionsEmptyState', () => {expect(screen.queryByText('Start with a template')).not.toBeInTheDocument()})-- it('renders the self-hosted manual card when isSelfHosted', () => {- mockIsPlatform.value = false- mockUseDeploymentMode.mockReturnValue({- isPlatform: false,- isCli: false,- isSelfHosted: true,- })-- render(<FunctionsEmptyState />)-- expect(screen.getByText('Self-Hosted')).toBeInTheDocument()- })})diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.constants.test.ts b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.constants.test.tsindex 10d6b4005d5..a3356edb8ef 100644--- a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.constants.test.ts+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.constants.test.ts@@ -2,83 +2,38 @@ import { describe, expect, it } from 'vitest'import { FormSchema } from './CreateCronJobSheet.constants'-describe('CreateCronJobSheet FormSchema', () => {- it('rejects incomplete http_request hostnames', () => {- const result = FormSchema.safeParse({- name: 'Send webhook',- supportsSeconds: false,- schedule: '* * * * *',- values: {- type: 'http_request' as const,- method: 'POST' as const,- endpoint: 'https://webhook',- timeoutMs: 1000,- httpHeaders: [],- snippet: '',- },- })-- expect(result.success).toBe(false)- if (!result.success) {- expect(- result.error.issues.some((issue) => issue.message === 'Please provide a valid URL')- ).toBe(true)- }- })-- it('rejects http_request URLs without an explicit protocol', () => {- const result = FormSchema.safeParse({- name: 'Send webhook',- supportsSeconds: false,- schedule: '* * * * *',- values: {- type: 'http_request' as const,- method: 'POST' as const,- endpoint: 'hooks.example.com/webhook',- timeoutMs: 1000,- httpHeaders: [],- snippet: '',- },- })-- expect(result.success).toBe(false)- if (!result.success) {- expect(- result.error.issues.some(- (issue) => issue.message === 'Please prefix your URL with http:// or https://'- )- ).toBe(true)- }- })-- it('rejects key-only http_request headers', () => {- const result = FormSchema.safeParse({- name: 'Send webhook',- supportsSeconds: false,- schedule: '* * * * *',- values: {- type: 'http_request' as const,- method: 'POST' as const,- endpoint: 'https://hooks.example.com/webhook',- timeoutMs: 1000,- httpHeaders: [{ name: 'X-Test', value: '' }],- snippet: '',- },- })-- expect(result.success).toBe(false)- if (!result.success) {- expect(- result.error.issues.some((issue) => issue.message === 'Header value is required')- ).toBe(true)- }- })+const httpRequest = (overrides: {+ endpoint?: string+ httpHeaders?: { name: string; value: string }[]+}) => ({+ type: 'http_request' as const,+ method: 'POST' as const,+ endpoint: 'https://hooks.example.com/webhook',+ timeoutMs: 1000,+ httpHeaders: [],+ snippet: '',+ ...overrides,+})- it('rejects value-only edge function headers', () => {- const result = FormSchema.safeParse({- name: 'Invoke edge function',- supportsSeconds: false,- schedule: '* * * * *',+describe('CreateCronJobSheet FormSchema', () => {+ it.each([+ {+ case: 'incomplete http_request hostnames',+ values: httpRequest({ endpoint: 'https://webhook' }),+ message: 'Please provide a valid URL',+ },+ {+ case: 'http_request URLs without an explicit protocol',+ values: httpRequest({ endpoint: 'hooks.example.com/webhook' }),+ message: 'Please prefix your URL with http:// or https://',+ },+ {+ case: 'key-only http_request headers',+ values: httpRequest({ httpHeaders: [{ name: 'X-Test', value: '' }] }),+ message: 'Header value is required',+ },+ {+ case: 'value-only edge function headers',values: {type: 'edge_function' as const,method: 'POST' as const,@@ -87,13 +42,17 @@ describe('CreateCronJobSheet FormSchema', () => {httpHeaders: [{ name: '', value: 'test-value' }],snippet: '',},+ message: 'Header name is required',+ },+ ])('rejects $case', ({ values, message }) => {+ const result = FormSchema.safeParse({+ name: 'Job',+ supportsSeconds: false,+ schedule: '* * * * *',+ values,})expect(result.success).toBe(false)- if (!result.success) {- expect(result.error.issues.some((issue) => issue.message === 'Header name is required')).toBe(- true- )- }+ expect(result.error?.issues.map((issue) => issue.message)).toContain(message)})})diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.tsindex d563d799b29..22873fd273e 100644--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts@@ -25,8 +25,10 @@ describe('buildCronUpdateQuery', () => {})describe('parseCronJobCommand', () => {- it('should return a default object when the command is null', () => {- expect(parseCronJobCommand('', 'random_project_ref')).toStrictEqual({+ const REF = 'random_project_ref'++ it('should return a default object when the command is empty', () => {+ expect(parseCronJobCommand('', REF)).toStrictEqual({httpBody: '',method: 'POST',snippet: '',@@ -35,133 +37,55 @@ describe('parseCronJobCommand', () => {})})- it('should return a default object when the command is random', () => {- const command = 'some random text'- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- snippet: 'some random text',- type: 'sql_snippet',- })- })-- it('should return a sql function command when the command is SELECT auth.jwt ()', () => {- const command = 'SELECT auth.jwt ()'- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- type: 'sql_function',- schema: 'auth',- functionName: 'jwt',- snippet: command,- })- })-- it('should return a sql function command when the command is SELECT auth.jwt () and ends with ;', () => {- const command = 'SELECT auth.jwt ();'- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- type: 'sql_function',- schema: 'auth',- functionName: 'jwt',- snippet: command,- })- })-- it('should return a sql function command when the function name contains an underscore', () => {- const command = 'SELECT random_schema.function_1()'- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- type: 'sql_function',+ it.each([+ { command: 'SELECT auth.jwt ()', schema: 'auth', functionName: 'jwt' },+ { command: 'SELECT auth.jwt ();', schema: 'auth', functionName: 'jwt' },+ {+ command: 'SELECT random_schema.function_1()',schema: 'random_schema',functionName: 'function_1',- snippet: command,- })- })-- it('should return a sql function command for lowercase select', () => {- const command = 'select lowercase.issue ()'- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({+ },+ { command: 'select lowercase.issue ()', schema: 'lowercase', functionName: 'issue' },+ ])('parses "$command" as a sql function', ({ command, schema, functionName }) => {+ expect(parseCronJobCommand(command, REF)).toStrictEqual({type: 'sql_function',- schema: 'lowercase',- functionName: 'issue',- snippet: command,- })- })-- it('should return a sql snippet command when the command is SELECT public.test_fn(1, 2)', () => {- const command = 'SELECT public.test_fn(1, 2)'- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- type: 'sql_snippet',+ schema,+ functionName,snippet: command,})})- it('should return a sql snippet command when the command is using a SQL function from the search path', () => {- const command = 'SELECT test_cron_function()'- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({+ it.each([+ { case: 'random text', command: 'some random text' },+ { case: 'a function call with arguments', command: 'SELECT public.test_fn(1, 2)' },+ { case: 'a function from the search path', command: 'SELECT test_cron_function()' },+ { case: 'a missing schema and function name', command: 'SELECT .()' },+ { case: 'a missing function name', command: 'SELECT schema.()' },+ {+ case: 'an HTTP request in positional notation',+ command: `SELECT net.http_post( 'https://webhook.site/dacc2028-a588-462c-9597-c8968e61d0fa', '{"message":"Hello from Supabase"}'::jsonb, '{}'::jsonb, '{"Content-Type":"application/json"}'::jsonb );`,+ },+ ])('falls back to a sql snippet for $case', ({ command }) => {+ expect(parseCronJobCommand(command, REF)).toStrictEqual({type: 'sql_snippet',snippet: command,})})- it('should return a sql snippet command when the command is SELECT .()', () => {- const command = 'SELECT .()'- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- type: 'sql_snippet',- snippet: command,- })- })-- it('should return a sql snippet command when the command is SELECT schema.()', () => {- const command = 'SELECT schema.()'- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- type: 'sql_snippet',- snippet: command,- })- })-- it('should return a edge function config when the command posts to its own supabase.co project', () => {- const command = `select net.http_post( url:='https://random_project_ref.supabase.co/functions/v1/_', headers:=jsonb_build_object('Authorization', 'Bearer something'), body:='', timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- edgeFunctionName: 'https://random_project_ref.supabase.co/functions/v1/_',- method: 'POST',- httpHeaders: [- {- name: 'Authorization',- value: 'Bearer something',- },- ],- httpBody: '',- timeoutMs: 5000,- type: 'edge_function',- snippet: command,- })- })-- it('should fall back to the pg_net default timeout when timeout_milliseconds is missing', () => {- const command = `select net.http_post( url:='https://random_project_ref.supabase.co/functions/v1/_', headers:=jsonb_build_object('Authorization', 'Bearer something'), body:='' );`- expect(parseCronJobCommand(command, 'random_project_ref')).toMatchObject({- type: 'edge_function',- timeoutMs: 5000,- })- })-- it('should fall back to the pg_net default timeout for http requests without timeout_milliseconds', () => {- const command = `select net.http_get( url:='https://example.com/api' );`- expect(parseCronJobCommand(command, 'random_project_ref')).toMatchObject({- type: 'http_request',- method: 'GET',- endpoint: 'https://example.com/api',- timeoutMs: 5000,- })- })-- it('should return a edge function config when the body is missing', () => {- const command = `select net.http_post( url:='https://random_project_ref.supabase.co/functions/v1/_', headers:=jsonb_build_object('Authorization', 'Bearer something'), timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({+ it.each([+ {+ case: 'with a body',+ command: `select net.http_post( url:='https://random_project_ref.supabase.co/functions/v1/_', headers:=jsonb_build_object('Authorization', 'Bearer something'), body:='', timeout_milliseconds:=5000 );`,+ },+ {+ case: 'without a body',+ command: `select net.http_post( url:='https://random_project_ref.supabase.co/functions/v1/_', headers:=jsonb_build_object('Authorization', 'Bearer something'), timeout_milliseconds:=5000 );`,+ },+ ])('returns an edge function config when posting to its own project $case', ({ command }) => {+ expect(parseCronJobCommand(command, REF)).toStrictEqual({edgeFunctionName: 'https://random_project_ref.supabase.co/functions/v1/_',method: 'POST',- httpHeaders: [- {- name: 'Authorization',- value: 'Bearer something',- },- ],+ httpHeaders: [{ name: 'Authorization', value: 'Bearer something' }],httpBody: '',timeoutMs: 5000,type: 'edge_function',@@ -169,334 +93,206 @@ describe('parseCronJobCommand', () => {})})- it('should return an edge function config for a self-hosted function URL', () => {- const command = `select net.http_post( url:='http://kong:8000/functions/v1/_', headers:=jsonb_build_object('Authorization', 'Bearer something'), timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'default', undefined, false)).toMatchObject({- edgeFunctionName: 'http://kong:8000/functions/v1/_',- type: 'edge_function',- })- })-- it('should return an edge function config for a self-hosted public function URL', () => {- const command = `select net.http_post( url:='https://default.supabase.localhost/functions/v1/_', headers:=jsonb_build_object('Authorization', 'Bearer something'), timeout_milliseconds:=5000 );`- expect(- parseCronJobCommand(command, 'default', 'https://default.supabase.localhost/rest/v1/', false)- ).toMatchObject({- edgeFunctionName: 'https://default.supabase.localhost/functions/v1/_',+ it.each([+ {+ case: 'edge function',+ command: `select net.http_post( url:='https://random_project_ref.supabase.co/functions/v1/_', headers:=jsonb_build_object('Authorization', 'Bearer something'), body:='' );`,+ expected: { type: 'edge_function' },+ },+ {+ case: 'http request',+ command: `select net.http_get( url:='https://example.com/api' );`,+ expected: { type: 'http_request', method: 'GET', endpoint: 'https://example.com/api' },+ },+ ])(+ 'falls back to the pg_net default timeout for an $case without timeout_milliseconds',+ ({ command, expected }) => {+ expect(parseCronJobCommand(command, REF)).toMatchObject({ ...expected, timeoutMs: 5000 })+ }+ )++ it.each([+ {+ case: 'self-hosted function URL',+ url: 'http://kong:8000/functions/v1/_',+ restUrl: undefined,+ },+ {+ case: 'self-hosted public function URL',+ url: 'https://default.supabase.localhost/functions/v1/_',+ restUrl: 'https://default.supabase.localhost/rest/v1/',+ },+ ])('returns an edge function config for a $case', ({ url, restUrl }) => {+ const command = `select net.http_post( url:='${url}', headers:=jsonb_build_object('Authorization', 'Bearer something'), timeout_milliseconds:=5000 );`+ expect(parseCronJobCommand(command, 'default', restUrl, false)).toMatchObject({+ edgeFunctionName: url,type: 'edge_function',})})- it("should return an HTTP request config when there's a query parameter or hash in the URL (also handles edge function)", () => {- const command = `select net.http_post( url:='https://random_project_ref.supabase.co/functions/v1/_?first=1#second=2', headers:=jsonb_build_object('Authorization', 'Bearer something'), timeout_milliseconds:=5000 )`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({+ it.each([+ {+ case: 'an own-project function URL with a query or hash',+ command: `select net.http_post( url:='https://random_project_ref.supabase.co/functions/v1/_?first=1#second=2', headers:=jsonb_build_object('Authorization', 'Bearer something'), timeout_milliseconds:=5000 )`,endpoint: 'https://random_project_ref.supabase.co/functions/v1/_?first=1#second=2',- method: 'POST',- httpHeaders: [- {- name: 'Authorization',- value: 'Bearer something',- },- ],- httpBody: '',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should return an HTTP request config when the command posts to another supabase.co project', () => {- const command = `select net.http_post( url:='https://another_project_ref.supabase.co/functions/v1/_', headers:=jsonb_build_object(), body:='', timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({+ httpHeaders: [{ name: 'Authorization', value: 'Bearer something' }],+ },+ {+ case: "another project's function URL",+ command: `select net.http_post( url:='https://another_project_ref.supabase.co/functions/v1/_', headers:=jsonb_build_object(), body:='', timeout_milliseconds:=5000 );`,endpoint: 'https://another_project_ref.supabase.co/functions/v1/_',- method: 'POST',- httpHeaders: [],- httpBody: '',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should return an HTTP request config with POST method, empty headers and a body as string', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object(), body:='hello', timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',- httpHeaders: [],+ },+ {+ case: 'a string body',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object(), body:='hello', timeout_milliseconds:=5000 );`,httpBody: 'hello',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should return an HTTP request config with POST method, some headers and empty body', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('fst', '1', 'snd', 'O''Reilly'), body:='', timeout_milliseconds:=1000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'headers with an escaped quote',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('fst', '1', 'snd', 'O''Reilly'), body:='', timeout_milliseconds:=1000 );`,httpHeaders: [{ name: 'fst', value: '1' },{ name: 'snd', value: "O'Reilly" },],- httpBody: '',timeoutMs: 1000,- type: 'http_request',- snippet: command,- })- })-- it('should keep a jsonb_build_object header value that contains a comma intact', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('Accept', 'application/json, text/plain'), timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'a header value containing a comma',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('Accept', 'application/json, text/plain'), timeout_milliseconds:=5000 );`,httpHeaders: [{ name: 'Accept', value: 'application/json, text/plain' }],- httpBody: '',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should not shift later jsonb_build_object headers when an earlier value contains a comma', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('Accept', 'application/json, text/plain', 'Authorization', 'Bearer abc'), timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'a later header after a comma-containing value',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('Accept', 'application/json, text/plain', 'Authorization', 'Bearer abc'), timeout_milliseconds:=5000 );`,httpHeaders: [{ name: 'Accept', value: 'application/json, text/plain' },{ name: 'Authorization', value: 'Bearer abc' },],- httpBody: '',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should keep a jsonb_build_object header value that contains parentheses intact', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('User-Agent', 'Mozilla/5.0 (compatible)'), timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'a header value containing parentheses',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('User-Agent', 'Mozilla/5.0 (compatible)'), timeout_milliseconds:=5000 );`,httpHeaders: [{ name: 'User-Agent', value: 'Mozilla/5.0 (compatible)' }],- httpBody: '',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should keep an escaped quote inside a comma-containing jsonb_build_object value', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('X-Company', 'O''Reilly, Inc'), timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'an escaped quote inside a comma-containing header value',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('X-Company', 'O''Reilly, Inc'), timeout_milliseconds:=5000 );`,httpHeaders: [{ name: 'X-Company', value: "O'Reilly, Inc" }],- httpBody: '',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should unescape backslashes in an E-prefixed jsonb_build_object header value', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('X-Custom', E'value\\\\here'), timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'backslashes in an E-prefixed header value',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('X-Custom', E'value\\\\here'), timeout_milliseconds:=5000 );`,httpHeaders: [{ name: 'X-Custom', value: 'value\\here' }],- httpBody: '',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should keep later jsonb_build_object headers when an earlier value contains parentheses', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('User-Agent', 'Mozilla/5.0 (compatible)', 'Accept', 'application/json'), timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'a later header after a parentheses-containing value',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('User-Agent', 'Mozilla/5.0 (compatible)', 'Accept', 'application/json'), timeout_milliseconds:=5000 );`,httpHeaders: [{ name: 'User-Agent', value: 'Mozilla/5.0 (compatible)' },{ name: 'Accept', value: 'application/json' },],- httpBody: '',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should parse jsonb_build_object headers when there is whitespace before the opening parenthesis', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object ('Accept', 'application/json'), timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'whitespace before the jsonb_build_object parenthesis',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object ('Accept', 'application/json'), timeout_milliseconds:=5000 );`,httpHeaders: [{ name: 'Accept', value: 'application/json' }],- httpBody: '',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should not let a comma inside a jsonb_build_object value swallow the following body argument', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('Accept', 'application/json, text/plain'), body:='{"key": "value"}', timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'a comma-containing header value followed by a body',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object('Accept', 'application/json, text/plain'), body:='{"key": "value"}', timeout_milliseconds:=5000 );`,httpHeaders: [{ name: 'Accept', value: 'application/json, text/plain' }],httpBody: '{"key": "value"}',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should return an HTTP request config with GET method and empty body', () => {- const command = `select net.http_get( url:='https://example.com/api/endpoint', headers:=jsonb_build_object(), timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',+ },+ {+ case: 'a GET request',+ command: `select net.http_get( url:='https://example.com/api/endpoint', headers:=jsonb_build_object(), timeout_milliseconds:=5000 );`,method: 'GET',- httpHeaders: [],- httpBody: '',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should return an HTTP request config with POST method and a body as JSON object', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object(), body:='{"key": "value"}', timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',- httpHeaders: [],+ },+ {+ case: 'a JSON body',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:=jsonb_build_object(), body:='{"key": "value"}', timeout_milliseconds:=5000 );`,httpBody: '{"key": "value"}',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should return an HTTP request config with POST method, plain JSON headers and plain JSON body', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:='{"fst": "1", "snd": "2"}',body:='{"key": "value"}',timeout_milliseconds:=5000);`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'plain JSON headers and body',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:='{"fst": "1", "snd": "2"}',body:='{"key": "value"}',timeout_milliseconds:=5000);`,httpHeaders: [{ name: 'fst', value: '1' },{ name: 'snd', value: '2' },],httpBody: '{"key": "value"}',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should return an HTTP request config with POST method, plain JSON headers and plain JSON body with escaped SQL strings and ::jsonb typecasting', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', headers:='{"X-Name":"O''Reilly"}'::jsonb,body:='{"message":"hello there","name":"O''Reilly"}'::jsonb,timeout_milliseconds:=5000);`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'plain JSON with escaped SQL strings and ::jsonb casts',+ command: `select net.http_post( url:='https://example.com/api/endpoint', headers:='{"X-Name":"O''Reilly"}'::jsonb,body:='{"message":"hello there","name":"O''Reilly"}'::jsonb,timeout_milliseconds:=5000);`,httpHeaders: [{ name: 'X-Name', value: "O'Reilly" }],httpBody: `{"message":"hello there","name":"O'Reilly"}`,- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should return an HTTP request config with POST method, escape-string headers and body with backslashes', () => {- const command = String.raw`select net.http_post( url:='https://example.com/api/endpoint', headers:=E'{"Content-Type":"application/json","X-Regex":"^\\\\d+$"}'::jsonb,body:=E'{"path":"C:\\\\tmp","regex":"^\\\\d+$"}',timeout_milliseconds:=1000);`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'escape-string headers and body with backslashes',+ command: String.raw`select net.http_post( url:='https://example.com/api/endpoint', headers:=E'{"Content-Type":"application/json","X-Regex":"^\\\\d+$"}'::jsonb,body:=E'{"path":"C:\\\\tmp","regex":"^\\\\d+$"}',timeout_milliseconds:=1000);`,httpHeaders: [{ name: 'Content-Type', value: 'application/json' },{ name: 'X-Regex', value: String.raw`^\d+$` },],httpBody: String.raw`{"path":"C:\\tmp","regex":"^\\d+$"}`,timeoutMs: 1000,- type: 'http_request',- snippet: command,- })- })-- it('should parse a POST body without swallowing later quoted arguments', () => {- const command = `select net.http_post( url:='https://example.com/api/endpoint', body:='{"payload":"ok"}'::jsonb, headers:='{"Authorization":"Bearer demo"}'::jsonb, timeout_milliseconds:=5000 );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- endpoint: 'https://example.com/api/endpoint',- method: 'POST',+ },+ {+ case: 'a body before later quoted arguments',+ command: `select net.http_post( url:='https://example.com/api/endpoint', body:='{"payload":"ok"}'::jsonb, headers:='{"Authorization":"Bearer demo"}'::jsonb, timeout_milliseconds:=5000 );`,httpHeaders: [{ name: 'Authorization', value: 'Bearer demo' }],httpBody: '{"payload":"ok"}',- timeoutMs: 5000,- type: 'http_request',- snippet: command,- })- })-- it('should return SQL snippet type if the command is an HTTP request that cannot be parsed properly due to positional notation', () => {- const command = `SELECT net.http_post( 'https://webhook.site/dacc2028-a588-462c-9597-c8968e61d0fa', '{"message":"Hello from Supabase"}'::jsonb, '{}'::jsonb, '{"Content-Type":"application/json"}'::jsonb );`- expect(parseCronJobCommand(command, 'random_project_ref')).toStrictEqual({- type: 'sql_snippet',- snippet: command,- })- })-- // Array of test cases for secondsPattern- const secondsPatternTests = [- { description: '10 seconds', command: '10 seconds' },- { description: '30 seconds', command: '30 seconds' },- ]-- // Run tests for secondsPattern- secondsPatternTests.forEach(({ description, command }) => {- it(`should match the regex for a secondsPattern with "${description}"`, () => {- expect(command).toMatch(secondsPattern)- })- })-- // Array of test cases for cronPattern- const cronPatternTests = [- { description: 'every hour', command: '0 * * * *' },- { description: 'every day at midnight', command: '0 0 * * *' },- { description: 'every Monday at 9 AM', command: '0 9 * * 1' },- { description: 'every 15th of the month at noon', command: '0 12 15 * *' },- { description: 'every January 1st at 3 AM', command: '0 3 1 1 *' },- { description: 'every 30 minutes', command: '30 * * * *' },- { description: 'every weekday at 6 PM', command: '0 18 * * 1-5' },- { description: 'every weekend at 10 AM', command: '0 10 * * 0,6' },- { description: 'every quarter hour', command: '*/15 * * * *' },- { description: 'twice daily at 8 AM and 8 PM', command: '0 8,20 * * *' },- { description: 'last day of every month at midnight (pg_cron $ syntax)', command: '0 0 $ * *' },- { description: 'last day of every month at noon (pg_cron $ syntax)', command: '0 12 $ * *' },- ]-- const cronPatternRejectTests = [- { description: '$ in minute field', command: '$ * * * *' },- { description: '$ in hour field', command: '* $ * * *' },- { description: '$ in month field', command: '* * * $ *' },- { description: '$ in day-of-week field', command: '* * * * $' },- ]+ },+ ])(+ 'returns an HTTP request config for $case',+ ({+ command,+ endpoint = 'https://example.com/api/endpoint',+ method = 'POST',+ httpHeaders = [],+ httpBody = '',+ timeoutMs = 5000,+ }) => {+ expect(parseCronJobCommand(command, REF)).toStrictEqual({+ endpoint,+ method,+ httpHeaders,+ httpBody,+ timeoutMs,+ type: 'http_request',+ snippet: command,+ })+ }+ )+})- cronPatternRejectTests.forEach(({ description, command }) => {- it(`should not match the regex for a cronPattern with "${description}"`, () => {+describe('schedule patterns', () => {+ it.each(['10 seconds', '30 seconds'])('secondsPattern matches "%s"', (command) => {+ expect(command).toMatch(secondsPattern)+ })++ it.each([+ '0 * * * *',+ '0 9 * * 1',+ '0 12 15 * *',+ '0 3 1 1 *',+ '0 18 * * 1-5',+ '0 10 * * 0,6',+ '*/15 * * * *',+ '0 8,20 * * *',+ // pg_cron's last-day-of-month syntax+ '0 0 $ * *',+ ])('cronPattern matches "%s"', (command) => {+ expect(command).toMatch(cronPattern)+ })++ it.each(['$ * * * *', '* $ * * *', '* * * $ *', '* * * * $'])(+ 'cronPattern rejects $ outside the day-of-month field ("%s")',+ (command) => {expect(command).not.toMatch(cronPattern)- })- })-- // Replace the single cronPattern test with forEach- cronPatternTests.forEach(({ description, command }) => {- it(`should match the regex for a cronPattern with "${description}"`, () => {- expect(command).toMatch(cronPattern)- })- })+ }+ )})describe('formatCronJobColumns', () => {diff --git a/apps/studio/components/interfaces/Integrations/DataApi/DataApi.utils.test.ts b/apps/studio/components/interfaces/Integrations/DataApi/DataApi.utils.test.tsindex a94fceac858..1006f266611 100644--- a/apps/studio/components/interfaces/Integrations/DataApi/DataApi.utils.test.ts+++ b/apps/studio/components/interfaces/Integrations/DataApi/DataApi.utils.test.ts@@ -81,30 +81,11 @@ describe('getApiEndpoint', () => {})).toBe('')})-- it('returns database restUrl for a replica database selection', () => {- expect(- getApiEndpoint({- selectedDatabaseId: 'replica-2',- projectRef: 'project-ref',- resolvedEndpoint: 'https://project-ref.supabase.co',- loadBalancers: undefined,- selectedDatabase: makeDatabase(- 'replica-2',- 'https://replica-2.supabase.co/rest/v1/'- ) as Database,- })- ).toBe('https://replica-2.supabase.co/rest/v1/')- })})describe('buildEntityMaps', () => {- it('returns empty maps for undefined paths', () => {- expect(buildEntityMaps(undefined)).toEqual({ resources: {}, rpcs: {} })- })-- it('returns empty maps for empty paths', () => {- expect(buildEntityMaps({})).toEqual({ resources: {}, rpcs: {} })+ it.each([undefined, {}])('returns empty maps for %j paths', (paths) => {+ expect(buildEntityMaps(paths)).toEqual({ resources: {}, rpcs: {} })})it('skips the root path', () => {@@ -114,25 +95,6 @@ describe('buildEntityMaps', () => {expect(buildEntityMaps(paths)).toEqual({ resources: {}, rpcs: {} })})- it('classifies non-rpc paths as resources', () => {- const paths: ProjectJsonSchemaPaths = {- '/users': { get: {} as ProjectJsonSchemaPaths[string]['get'] },- '/posts': { get: {} as ProjectJsonSchemaPaths[string]['get'] },- }- const result = buildEntityMaps(paths)- expect(Object.keys(result.resources)).toEqual(['users', 'posts'])- expect(result.rpcs).toEqual({})- })-- it('classifies rpc/ paths as rpcs', () => {- const paths: ProjectJsonSchemaPaths = {- '/rpc/my_function': { post: {} as ProjectJsonSchemaPaths[string]['post'] },- }- const result = buildEntityMaps(paths)- expect(result.resources).toEqual({})- expect(Object.keys(result.rpcs)).toEqual(['my_function'])- })-it('enriches entities with displayName and camelCase', () => {const paths: ProjectJsonSchemaPaths = {'/user_profiles': { get: {} as ProjectJsonSchemaPaths[string]['get'] },@@ -152,7 +114,7 @@ describe('buildEntityMaps', () => {})})- it('handles mixed resources and rpcs', () => {+ it('classifies rpc/ paths as rpcs and other paths as resources', () => {const paths: ProjectJsonSchemaPaths = {'/': { get: {} as ProjectJsonSchemaPaths[string]['get'] },'/users': { get: {} as ProjectJsonSchemaPaths[string]['get'] },diff --git a/apps/studio/components/interfaces/Integrations/GraphQL/pgGraphqlSchemaComment.test.ts b/apps/studio/components/interfaces/Integrations/GraphQL/pgGraphqlSchemaComment.test.tsindex cf5360219c1..6319d3b3258 100644--- a/apps/studio/components/interfaces/Integrations/GraphQL/pgGraphqlSchemaComment.test.ts+++ b/apps/studio/components/interfaces/Integrations/GraphQL/pgGraphqlSchemaComment.test.ts@@ -8,28 +8,8 @@ import {} from './pgGraphqlSchemaComment'describe('parseSchemaComment', () => {- it('returns no directive for null', () => {- expect(parseSchemaComment(null)).toEqual({- options: {},- hasDirective: false,- isMalformed: false,- prefix: '',- suffix: '',- })- })-- it('returns no directive for undefined', () => {- expect(parseSchemaComment(undefined)).toEqual({- options: {},- hasDirective: false,- isMalformed: false,- prefix: '',- suffix: '',- })- })-- it('returns no directive for empty string', () => {- expect(parseSchemaComment('')).toEqual({+ it.each([null, undefined, ''])('returns no directive for %j', (comment) => {+ expect(parseSchemaComment(comment)).toEqual({options: {},hasDirective: false,isMalformed: false,@@ -48,17 +28,9 @@ describe('parseSchemaComment', () => {})})- it('parses a directive with introspection: true', () => {- expect(parseSchemaComment('@graphql({"introspection": true})')).toMatchObject({- options: { introspection: true },- hasDirective: true,- isMalformed: false,- })- })-- it('parses a directive with introspection: false', () => {- expect(parseSchemaComment('@graphql({"introspection": false})')).toMatchObject({- options: { introspection: false },+ it.each([true, false])('parses a directive with introspection: %s', (introspection) => {+ expect(parseSchemaComment(`@graphql({"introspection": ${introspection}})`)).toMatchObject({+ options: { introspection },hasDirective: true,isMalformed: false,})@@ -139,21 +111,16 @@ describe('parseSchemaComment', () => {})})- it('treats invalid JSON as malformed', () => {- expect(parseSchemaComment('@graphql({not valid json})')).toMatchObject({- options: {},- hasDirective: true,- isMalformed: true,- })- })-- it('treats trailing-comma JSON as malformed', () => {- expect(parseSchemaComment('@graphql({"introspection": true,})')).toMatchObject({- options: {},- hasDirective: true,- isMalformed: true,- })- })+ it.each(['@graphql({not valid json})', '@graphql({"introspection": true,})'])(+ 'treats invalid JSON %j as malformed',+ (comment) => {+ expect(parseSchemaComment(comment)).toMatchObject({+ options: {},+ hasDirective: true,+ isMalformed: true,+ })+ }+ )it('ignores incomplete @graphql with no closing paren', () => {expect(parseSchemaComment('@graphql({"introspection": true}')).toEqual({@@ -186,20 +153,8 @@ describe('parseSchemaComment', () => {})describe('buildSchemaCommentWith', () => {- it('produces a directive when comment is null', () => {- expect(buildSchemaCommentWith(null, { introspection: true })).toBe(- '@graphql({"introspection":true})'- )- })-- it('produces a directive when comment is undefined', () => {- expect(buildSchemaCommentWith(undefined, { introspection: true })).toBe(- '@graphql({"introspection":true})'- )- })-- it('produces a directive when comment is empty', () => {- expect(buildSchemaCommentWith('', { introspection: true })).toBe(+ it.each([null, undefined, ''])('produces a directive when comment is %j', (comment) => {+ expect(buildSchemaCommentWith(comment, { introspection: true })).toBe('@graphql({"introspection":true})')})@@ -253,14 +208,6 @@ describe('buildSchemaCommentWith', () => {buildSchemaCommentWith('prefix @graphql({not valid json}) suffix', { introspection: true })).toBe('prefix @graphql({"introspection":true}) suffix')})-- it('supports disabling introspection', () => {- expect(- buildSchemaCommentWith('@graphql({"introspection": true, "max_rows": 100})', {- introspection: false,- })- ).toBe('@graphql({"introspection":false,"max_rows":100})')- })})describe('isIntrospectionEnabled', () => {@@ -283,12 +230,8 @@ describe('isIntrospectionEnabled', () => {describe('isPgGraphqlIntrospectionOptIn', () => {it.each([['1.6.0', true],- ['1.6.1', true],- ['1.7.0', true],['2.0.0', true],['1.5.9', false],- ['1.5.0', false],- ['1.0.0', false],['0.9.0', false],])('version %s returns %s', (version, expected) => {expect(isPgGraphqlIntrospectionOptIn(version)).toBe(expected)diff --git a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTab.test.tsx b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTab.test.tsxindex 25a2a547042..10b67a6bd97 100644--- a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTab.test.tsx+++ b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTab.test.tsx@@ -74,26 +74,21 @@ describe('IntegrationOverviewTab', () => {])})- it('does not disable actions when hideRequiredExtensionsSection is true and extensions are uninstalled', () => {- customRender(- <IntegrationOverviewTab- hideRequiredExtensionsSection- actions={<button tabIndex={0}>Enable webhooks</button>}- />- )+ it.each([+ { hideRequiredExtensionsSection: true, isDisabled: 'false' },+ { hideRequiredExtensionsSection: false, isDisabled: 'true' },+ ])(+ 'with uninstalled extensions and hideRequiredExtensionsSection=$hideRequiredExtensionsSection, aria-disabled is $isDisabled',+ ({ hideRequiredExtensionsSection, isDisabled }) => {+ customRender(+ <IntegrationOverviewTab+ hideRequiredExtensionsSection={hideRequiredExtensionsSection}+ actions={<button tabIndex={0}>Enable integration</button>}+ />+ )- const actionsArea = screen.getByText('Enable webhooks').closest('[aria-disabled]')- expect(actionsArea).toHaveAttribute('aria-disabled', 'false')- expect(actionsArea).not.toHaveClass('opacity-25')- })-- it('disables actions when extensions are uninstalled and hideRequiredExtensionsSection is false', () => {- customRender(- <IntegrationOverviewTab actions={<button tabIndex={0}>Enable integration</button>} />- )-- const actionsArea = screen.getByText('Enable integration').closest('[aria-disabled]')- expect(actionsArea).toHaveAttribute('aria-disabled', 'true')- expect(actionsArea).toHaveClass('opacity-25')- })+ const actionsArea = screen.getByText('Enable integration').closest('[aria-disabled]')+ expect(actionsArea).toHaveAttribute('aria-disabled', isDisabled)+ }+ )})diff --git a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet.test.tsx b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet.test.tsxindex 7fcde7fc422..08a1906e73d 100644--- a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet.test.tsx+++ b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet.test.tsx@@ -74,33 +74,22 @@ describe('InstallIntegrationSheet', () => {mockExecuteSql.mockReset()})- it('install button is disabled when extensions are missing even if installationCommand exists', async () => {- mockExtensions.mockReturnValue([])-- customRender(- <InstallIntegrationSheet- integration={createIntegration({- installationCommand: vi.fn().mockResolvedValue(undefined),- })}- />- )-- await userEvent.click(screen.getByRole('button', { name: 'Install integration' }))- expect(getInstallButton()).toBeDisabled()- })-- it('install button is disabled when extensions are missing and no installationCommand', async () => {- mockExtensions.mockReturnValue([])-- customRender(- <InstallIntegrationSheet- integration={createIntegration({ installationCommand: undefined })}- />- )-- await userEvent.click(screen.getByRole('button', { name: 'Install integration' }))- expect(getInstallButton()).toBeDisabled()- })+ it.each([+ { case: 'with', installationCommand: vi.fn().mockResolvedValue(undefined) },+ { case: 'without', installationCommand: undefined },+ ])(+ 'install button is disabled when extensions are missing, $case an installationCommand',+ async ({ installationCommand }) => {+ mockExtensions.mockReturnValue([])++ customRender(+ <InstallIntegrationSheet integration={createIntegration({ installationCommand })} />+ )++ await userEvent.click(screen.getByRole('button', { name: 'Install integration' }))+ expect(getInstallButton()).toBeDisabled()+ }+ )it('uses installationCommand instead of SQL when provided', async () => {mockExtensions.mockReturnValue([diff --git a/apps/studio/components/interfaces/Integrations/Integration/MarketplaceIntegrationSettingsTab.test.tsx b/apps/studio/components/interfaces/Integrations/Integration/MarketplaceIntegrationSettingsTab.test.tsxindex 7b418d66e5f..42bda55b884 100644--- a/apps/studio/components/interfaces/Integrations/Integration/MarketplaceIntegrationSettingsTab.test.tsx+++ b/apps/studio/components/interfaces/Integrations/Integration/MarketplaceIntegrationSettingsTab.test.tsx@@ -140,7 +140,7 @@ const mockProjectResources = ({describe('MarketplaceIntegrationSettingsTab', () => {describe('section visibility follows the integration definition', () => {- test('renders the secret API key section when the integration declares a secret key prefix', async () => {+ test('renders the secret API key section with a Remove action and generic warning when the integration declares a secret key prefix', async () => {setIntegration({ secretKeyPrefix: 'custom_' })mockProjectResources({ apiKeys: [secretApiKey('custom_metrics_key')] })@@ -148,6 +148,13 @@ describe('MarketplaceIntegrationSettingsTab', () => {expect(await screen.findByRole('heading', { name: 'Secret API key' })).toBeInTheDocument()expect(screen.getByText('custom_metrics_key')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Remove' })).toBeInTheDocument()+ // No integration-specific override, so the generic removal warning is used.+ expect(+ screen.getByText(+ 'Removing this key takes effect immediately and can interrupt the integration.'+ )+ ).toBeInTheDocument()})test('does not render a secret API key section when the integration declares no prefix, even if secret keys exist', async () => {@@ -212,29 +219,6 @@ describe('MarketplaceIntegrationSettingsTab', () => {})describe('resource section states', () => {- test('a present resource shows the Connected badge and a Remove action', async () => {- setIntegration({ secretKeyPrefix: 'custom_' })- mockProjectResources({ apiKeys: [secretApiKey('custom_key')] })-- customRender(<MarketplaceIntegrationSettingsTab />)-- expect(await screen.findByText('custom_key')).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Remove' })).toBeInTheDocument()- })-- test('uses the generic removal warning when the integration has no override copy', async () => {- setIntegration({ secretKeyPrefix: 'custom_' })- mockProjectResources({ apiKeys: [secretApiKey('custom_key')] })-- customRender(<MarketplaceIntegrationSettingsTab />)-- expect(- await screen.findByText(- 'Removing this key takes effect immediately and can interrupt the integration.'- )- ).toBeInTheDocument()- })-test('uses the integration-specific removal warning override when one is defined', async () => {setIntegration({ id: 'grafana', name: 'Grafana' })mockProjectResources({ apiKeys: [secretApiKey('grafana_cloud_integration_metrics')] })diff --git a/apps/studio/components/interfaces/Integrations/Warehouse/OverviewTab.test.tsx b/apps/studio/components/interfaces/Integrations/Warehouse/OverviewTab.test.tsxindex 1de3cd2281b..5183ae043ff 100644--- a/apps/studio/components/interfaces/Integrations/Warehouse/OverviewTab.test.tsx+++ b/apps/studio/components/interfaces/Integrations/Warehouse/OverviewTab.test.tsx@@ -275,22 +275,7 @@ describe('WarehouseOverviewTab', () => {})- test('keeps the table picker available after setup fails', async () => {- mockProject()- mockSetupStatus({- setup_status: 'error',- steps: [{ name: 'warehouse_copy', status: 'error', message: 'Failed to copy public.orders' }],- tables: [{ schema: 'public', name: 'orders', copy_name: 'public.orders', state: 'error' }],- })-- customRender(<WarehouseOverviewTab />)-- expect(await screen.findByText('Replicated tables picker')).toBeInTheDocument()- expect(screen.getByText('Picker error: Failed to copy public.orders')).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Submit initial tables' })).toBeInTheDocument()- })-- test('shows the latest error when retrying setup fails', async () => {+ test('keeps the table picker available after setup fails and shows the latest retry error', async () => {mockProject()mockSetupStatus({setup_status: 'error',@@ -306,7 +291,8 @@ describe('WarehouseOverviewTab', () => {customRender(<WarehouseOverviewTab />)- await userEvent.click(await screen.findByRole('button', { name: 'Submit initial tables' }))+ expect(await screen.findByText('Picker error: Initial setup failed')).toBeInTheDocument()+ await userEvent.click(screen.getByRole('button', { name: 'Submit initial tables' }))expect(await screen.findByText('Picker error: Retry could not be started')).toBeInTheDocument()expect(screen.queryByText('Picker error: Initial setup failed')).not.toBeInTheDocument()@@ -358,7 +344,7 @@ describe('WarehouseOverviewTab', () => {expect(headings).toEqual(['Status', 'Tables', 'Connect', 'Disable'])})- test('tracks initial setup but not table selection edits as enablement', async () => {+ test('tracks initial setup as enablement', async () => {mockSetupStatus({ setup_status: 'not_started' })addAPIMock({method: 'post',@@ -394,9 +380,9 @@ describe('WarehouseOverviewTab', () => {expect(mockTrack).not.toHaveBeenCalledWith('warehouse_enabled', expect.anything())})- test('preserves copied Warehouse data by default after confirmation', async () => {+ test('preserves copied data by default, resets the option on reopen, and tracks what was replicated', async () => {mockSetupStatus({ setup_status: 'complete' })- mockReplicatedTableQueries()+ const { publicationRequests } = mockReplicatedTableQueries()const deleteRequests: (string | null)[] = []addAPIMock({method: 'delete',@@ -410,32 +396,31 @@ describe('WarehouseOverviewTab', () => {customRender(<WarehouseOverviewTab />)await userEvent.click(await screen.findByRole('button', { name: 'Disable Warehouse' }))- expect(deleteRequests).toEqual([])-- const dialog = await screen.findByRole('alertdialog')+ let dialog = await screen.findByRole('alertdialog')expect(dialog).toHaveTextContent('Deletes the copied data and its storage permanently')expect(within(dialog).getByRole('checkbox')).not.toBeChecked()expect(screen.queryByPlaceholderText('Type the project ref to confirm')).not.toBeInTheDocument()- fireEvent.click(within(dialog).getByRole('button', { name: 'Disable Warehouse' }))-- await waitFor(() => expect(deleteRequests).toEqual(['false']))- })-- test('resets the copied data option when the confirmation is reopened', async () => {- mockSetupStatus({ setup_status: 'complete' })- mockReplicatedTableQueries()- customRender(<WarehouseOverviewTab />)-- await userEvent.click(await screen.findByRole('button', { name: 'Disable Warehouse' }))- const dialog = await screen.findByRole('alertdialog')await userEvent.click(within(dialog).getByRole('checkbox'))expect(within(dialog).getByRole('checkbox')).toBeChecked()await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())+ expect(deleteRequests).toEqual([])await userEvent.click(screen.getByRole('button', { name: 'Disable Warehouse' }))- expect(within(await screen.findByRole('alertdialog')).getByRole('checkbox')).not.toBeChecked()+ dialog = await screen.findByRole('alertdialog')+ expect(within(dialog).getByRole('checkbox')).not.toBeChecked()+ await waitFor(() => expect(publicationRequests).toEqual(['supabase_warehouse']))++ fireEvent.click(within(dialog).getByRole('button', { name: 'Disable Warehouse' }))++ await waitFor(() => expect(deleteRequests).toEqual(['false']))+ await waitFor(() =>+ expect(mockTrack).toHaveBeenCalledWith('warehouse_disabled', {+ schemaTargetCount: 1,+ tableTargetCount: 1,+ })+ )})test('shows disable progress and polls until Warehouse can be enabled again', async () => {@@ -451,13 +436,18 @@ describe('WarehouseOverviewTab', () => {steps: [],}),})- customRender(<WarehouseOverviewTab />)- expect(await screen.findByText('Warehouse is being disabled')).toBeInTheDocument()- expect(screen.queryByRole('button', { name: 'Disable Warehouse' })).not.toBeInTheDocument()- status = 'disabled'- expect(- await screen.findByText('Replicated tables picker', {}, { timeout: 5000 })- ).toBeInTheDocument()+ vi.useFakeTimers({ shouldAdvanceTime: true })+ try {+ customRender(<WarehouseOverviewTab />)+ expect(await screen.findByText('Warehouse is being disabled')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Disable Warehouse' })).not.toBeInTheDocument()+ status = 'disabled'+ // The panel polls every 3s while disabling.+ await vi.advanceTimersByTimeAsync(3000)+ expect(await screen.findByText('Replicated tables picker')).toBeInTheDocument()+ } finally {+ vi.useRealTimers()+ }})test.each([false, true])(@@ -489,32 +479,6 @@ describe('WarehouseOverviewTab', () => {})- test('tracks how much was being replicated when Warehouse is disabled', async () => {- mockSetupStatus({ setup_status: 'complete' })- const { publicationRequests } = mockReplicatedTableQueries()- addAPIMock({- method: 'delete',- path: '/platform/warehouse/:ref',- response: () =>- HttpResponse.json<WarehouseDeleteResponse>({ status: 'accepted' }, { status: 202 }),- })-- customRender(<WarehouseOverviewTab />)-- await userEvent.click(await screen.findByRole('button', { name: 'Disable Warehouse' }))- const dialog = await screen.findByRole('alertdialog')- await waitFor(() => expect(publicationRequests).toEqual(['supabase_warehouse']))-- fireEvent.click(within(dialog).getByRole('button', { name: 'Disable Warehouse' }))-- await waitFor(() =>- expect(mockTrack).toHaveBeenCalledWith('warehouse_disabled', {- schemaTargetCount: 1,- tableTargetCount: 1,- })- )- })-test('shows a disable error and allows retrying from the open confirmation', async () => {mockSetupStatus({ setup_status: 'complete' })mockReplicatedTableQueries()diff --git a/apps/studio/components/interfaces/Integrations/Warehouse/Warehouse.utils.test.ts b/apps/studio/components/interfaces/Integrations/Warehouse/Warehouse.utils.test.tsindex 199ebf879bb..fa24da9b223 100644--- a/apps/studio/components/interfaces/Integrations/Warehouse/Warehouse.utils.test.ts+++ b/apps/studio/components/interfaces/Integrations/Warehouse/Warehouse.utils.test.ts@@ -15,46 +15,32 @@ import {import { WAREHOUSE_METADATA_SCHEMA } from '@/lib/warehouse'describe('WarehouseModePanel.utils:isSelectableWarehouseSchema', () => {- test('excludes information_schema', () => {- expect(isSelectableWarehouseSchema('information_schema')).toBe(false)- })-- test('excludes any schema starting with pg_', () => {- expect(isSelectableWarehouseSchema('pg_catalog')).toBe(false)- expect(isSelectableWarehouseSchema('pg_toast')).toBe(false)- })-- test('excludes Supabase infrastructure schemas', () => {- // Replicating secrets or internal bookkeeping into a warehouse is never intended- expect(isSelectableWarehouseSchema('vault')).toBe(false)- expect(isSelectableWarehouseSchema('pgsodium')).toBe(false)- expect(isSelectableWarehouseSchema('realtime')).toBe(false)- expect(isSelectableWarehouseSchema('_realtime')).toBe(false)- expect(isSelectableWarehouseSchema('cron')).toBe(false)- expect(isSelectableWarehouseSchema('supabase_migrations')).toBe(false)- expect(isSelectableWarehouseSchema('extensions')).toBe(false)- })-- test('includes public and other user schemas', () => {- expect(isSelectableWarehouseSchema('public')).toBe(true)- expect(isSelectableWarehouseSchema('analytics')).toBe(true)- })-- test('includes auth and storage, which hold product data users replicate', () => {- expect(isSelectableWarehouseSchema('auth')).toBe(true)- expect(isSelectableWarehouseSchema('storage')).toBe(true)- })-- test("excludes the Warehouse's own DuckLake catalog schema", () => {- // Replicating the catalog that describes the Warehouse would feed it its own metadata- expect(isSelectableWarehouseSchema(WAREHOUSE_METADATA_SCHEMA)).toBe(false)- expect(isSelectableWarehouseSchema('ducklake')).toBe(false)- })-- test('includes schemas whose names merely resemble the catalog schema', () => {- expect(isSelectableWarehouseSchema('ducklake_staging')).toBe(true)- expect(isSelectableWarehouseSchema('my_ducklake')).toBe(true)- })+ // Replicating system catalogs, secrets, internal bookkeeping, or the Warehouse's own DuckLake+ // catalog into a warehouse is never intended.+ test.each([+ 'information_schema',+ 'pg_catalog',+ 'pg_toast',+ 'vault',+ 'pgsodium',+ 'realtime',+ '_realtime',+ 'cron',+ 'supabase_migrations',+ 'extensions',+ WAREHOUSE_METADATA_SCHEMA,+ 'ducklake',+ ])('excludes %s', (schema) => {+ expect(isSelectableWarehouseSchema(schema)).toBe(false)+ })++ // auth and storage hold product data users replicate; ducklake_* merely resemble the catalog.+ test.each(['public', 'analytics', 'auth', 'storage', 'ducklake_staging', 'my_ducklake'])(+ 'includes %s',+ (schema) => {+ expect(isSelectableWarehouseSchema(schema)).toBe(true)+ }+ )})describe('WarehouseModePanel.utils:buildSelectionFromPublicationTables', () => {@@ -71,27 +57,6 @@ describe('WarehouseModePanel.utils:buildSelectionFromPublicationTables', () => {).toEqual({ 'public.orders': true, 'auth.users': true })})- test('produces a fully checked schema when every table of that schema is published', () => {- const schemaTables = ['orders', 'customers']- const selection = buildSelectionFromPublicationTables(- schemaTables.map((name) => ({ schema: 'public', name }))- )- const selectedCount = schemaTables.filter(- (name) => selection[getSchemaTableKey('public', name)]- ).length-- expect(getSchemaCheckedState({ selectedCount, totalCount: schemaTables.length })).toBe(true)- })-- test('produces an indeterminate schema when only some of its tables are published', () => {- const selection = buildSelectionFromPublicationTables([{ schema: 'public', name: 'orders' }])- const selectedCount = ['orders', 'customers'].filter(- (name) => selection[getSchemaTableKey('public', name)]- ).length-- expect(getSchemaCheckedState({ selectedCount, totalCount: 2 })).toBe('indeterminate')- })-test('round-trips through buildWarehouseSetupTargets as a schema target when fully published', () => {const schemas: SchemaWithTables[] = [{ schema: 'public', tables: ['orders', 'customers'] }]const selection = buildSelectionFromPublicationTables([@@ -106,22 +71,19 @@ describe('WarehouseModePanel.utils:buildSelectionFromPublicationTables', () => {})describe('WarehouseModePanel.utils:getSchemaCheckedState', () => {- test('is unchecked when nothing is selected', () => {- expect(getSchemaCheckedState({ selectedCount: 0, totalCount: 3 })).toBe(false)- })-- test('is indeterminate when only some tables are selected', () => {- expect(getSchemaCheckedState({ selectedCount: 1, totalCount: 3 })).toBe('indeterminate')- expect(getSchemaCheckedState({ selectedCount: 2, totalCount: 3 })).toBe('indeterminate')- })-- test('is checked when every table is selected', () => {- expect(getSchemaCheckedState({ selectedCount: 3, totalCount: 3 })).toBe(true)- })-- test('is unchecked for an empty schema rather than checked', () => {- expect(getSchemaCheckedState({ selectedCount: 0, totalCount: 0 })).toBe(false)- })+ test.each([+ { selectedCount: 0, totalCount: 3, expected: false },+ { selectedCount: 1, totalCount: 3, expected: 'indeterminate' },+ { selectedCount: 2, totalCount: 3, expected: 'indeterminate' },+ { selectedCount: 3, totalCount: 3, expected: true },+ // An empty schema is unchecked rather than checked+ { selectedCount: 0, totalCount: 0, expected: false },+ ])(+ '$selectedCount of $totalCount selected is $expected',+ ({ selectedCount, totalCount, expected }) => {+ expect(getSchemaCheckedState({ selectedCount, totalCount })).toBe(expected)+ }+ )})describe('WarehouseModePanel.utils:getSchemaTableKey', () => {@@ -176,45 +138,25 @@ describe('WarehouseModePanel.utils:hasSelectionChanged', () => {})describe('WarehouseModePanel.utils:buildWarehouseSetupTargets', () => {- test('returns an empty array for an empty selection', () => {- const schemas: SchemaWithTables[] = [{ schema: 'public', tables: ['orders', 'customers'] }]- expect(buildWarehouseSetupTargets({}, schemas)).toEqual([])- })-- test('returns an empty array when there are no schemas', () => {- expect(buildWarehouseSetupTargets({ 'public.orders': true }, [])).toEqual([])- })-- test('emits a schema target when every table in that schema is selected', () => {- const schemas: SchemaWithTables[] = [{ schema: 'public', tables: ['orders', 'customers'] }]- const selection: SchemaTableSelection = {- 'public.orders': true,- 'public.customers': true,- }- expect(buildWarehouseSetupTargets(selection, schemas)).toEqual([- { type: 'schema', schema: 'public' },- ])- })-- test('emits per-table targets when only some tables in a schema are selected', () => {- const schemas: SchemaWithTables[] = [{ schema: 'public', tables: ['orders', 'customers'] }]- const selection: SchemaTableSelection = {- 'public.orders': true,- 'public.customers': false,- }- expect(buildWarehouseSetupTargets(selection, schemas)).toEqual([- { type: 'table', schema: 'public', name: 'orders' },- ])- })-- test('skips schemas with no tables', () => {- const schemas: SchemaWithTables[] = [{ schema: 'empty_schema', tables: [] }]- expect(buildWarehouseSetupTargets({ 'empty_schema.foo': true }, schemas)).toEqual([])- })-- test('skips schemas with no selected tables', () => {- const schemas: SchemaWithTables[] = [{ schema: 'public', tables: ['orders'] }]- expect(buildWarehouseSetupTargets({ 'public.orders': false }, schemas)).toEqual([])+ test.each<{ case: string; selection: SchemaTableSelection; schemas: SchemaWithTables[] }>([+ {+ case: 'an empty selection',+ selection: {},+ schemas: [{ schema: 'public', tables: ['orders', 'customers'] }],+ },+ { case: 'no schemas', selection: { 'public.orders': true }, schemas: [] },+ {+ case: 'a schema with no tables',+ selection: { 'empty_schema.foo': true },+ schemas: [{ schema: 'empty_schema', tables: [] }],+ },+ {+ case: 'a schema with no selected tables',+ selection: { 'public.orders': false },+ schemas: [{ schema: 'public', tables: ['orders'] }],+ },+ ])('returns no targets for $case', ({ selection, schemas }) => {+ expect(buildWarehouseSetupTargets(selection, schemas)).toEqual([])})test('ignores selection keys that reference tables outside the given schemas', () => {@@ -228,7 +170,7 @@ describe('WarehouseModePanel.utils:buildWarehouseSetupTargets', () => {])})- test('handles multiple schemas with a mix of full, partial, and no selection', () => {+ test('emits schema targets for fully selected schemas and table targets for partial ones', () => {const schemas: SchemaWithTables[] = [{ schema: 'public', tables: ['orders', 'customers'] },{ schema: 'auth', tables: ['users', 'sessions'] },diff --git a/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSchemaTablePicker.test.tsx b/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSchemaTablePicker.test.tsxindex 9114df170a5..064be20f7d4 100644--- a/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSchemaTablePicker.test.tsx+++ b/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSchemaTablePicker.test.tsx@@ -47,52 +47,26 @@ const SCHEMAS: SchemasData = [{ id: 2, name: 'analytics', owner: 'postgres', comment: null },]+const createTable = (id: number, schema: string, name: string): TablesData[number] => ({+ id,+ schema,+ name,+ rls_enabled: false,+ rls_forced: false,+ replica_identity: 'DEFAULT',+ bytes: 1024,+ size: '1024 bytes',+ live_rows_estimate: 10,+ dead_rows_estimate: 0,+ comment: null,+ primary_keys: [],+ relationships: [],+})+const TABLES: TablesData = [- {- id: 1,- schema: 'public',- name: 'orders',- rls_enabled: false,- rls_forced: false,- replica_identity: 'DEFAULT',- bytes: 1024,- size: '1024 bytes',- live_rows_estimate: 10,- dead_rows_estimate: 0,- comment: null,- primary_keys: [],- relationships: [],- },- {- id: 2,- schema: 'public',- name: 'customers',- rls_enabled: false,- rls_forced: false,- replica_identity: 'DEFAULT',- bytes: 1024,- size: '1024 bytes',- live_rows_estimate: 10,- dead_rows_estimate: 0,- comment: null,- primary_keys: [],- relationships: [],- },- {- id: 3,- schema: 'analytics',- name: 'events',- rls_enabled: false,- rls_forced: false,- replica_identity: 'DEFAULT',- bytes: 1024,- size: '1024 bytes',- live_rows_estimate: 10,- dead_rows_estimate: 0,- comment: null,- primary_keys: [],- relationships: [],- },+ createTable(1, 'public', 'orders'),+ createTable(2, 'public', 'customers'),+ createTable(3, 'analytics', 'events'),]const SOURCES: ReplicationSourcesResponse = {@@ -267,43 +241,25 @@ describe('WarehouseSchemaTablePicker', () => {customRender(<WarehousePickerHarness />)fireEvent.click(await screen.findByRole('combobox', { name: 'Select tables to replicate' }))- await userEvent.type(screen.getByPlaceholderText('Search schemas and tables...'), 'analytics')+ const search = screen.getByPlaceholderText('Search schemas and tables...')+ fireEvent.change(search, { target: { value: 'analytics' } })expect(screen.getByText('events')).toBeInTheDocument()expect(screen.queryByText('orders')).not.toBeInTheDocument()expect(screen.queryByText('customers')).not.toBeInTheDocument()- await userEvent.clear(screen.getByPlaceholderText('Search schemas and tables...'))- await userEvent.type(screen.getByPlaceholderText('Search schemas and tables...'), 'public.ord')-- expect(screen.getByText('orders')).toBeInTheDocument()- expect(screen.queryByText('customers')).not.toBeInTheDocument()- expect(screen.queryByText('events')).not.toBeInTheDocument()-- await userEvent.clear(screen.getByPlaceholderText('Search schemas and tables...'))- await userEvent.type(screen.getByPlaceholderText('Search schemas and tables...'), 'orders')-- expect(screen.getByText('orders')).toBeInTheDocument()- expect(screen.queryByText('customers')).not.toBeInTheDocument()- expect(screen.queryByText('events')).not.toBeInTheDocument()+ for (const query of ['public.ord', 'orders']) {+ fireEvent.change(search, { target: { value: query } })+ expect(screen.getByText('orders')).toBeInTheDocument()+ expect(screen.queryByText('customers')).not.toBeInTheDocument()+ expect(screen.queryByText('events')).not.toBeInTheDocument()+ }})- test('wraps selected table badges and shows an overflow count past the limit', async () => {- const manyTables: TablesData = Array.from({ length: 12 }, (_, index) => ({- id: index + 1,- schema: 'public',- name: `table_${String(index + 1).padStart(2, '0')}`,- rls_enabled: false,- rls_forced: false,- replica_identity: 'DEFAULT',- bytes: 1024,- size: '1024 bytes',- live_rows_estimate: 10,- dead_rows_estimate: 0,- comment: null,- primary_keys: [],- relationships: [],- }))+ test('shows selected table badges with an overflow count past the limit', async () => {+ const manyTables: TablesData = Array.from({ length: 12 }, (_, index) =>+ createTable(index + 1, 'public', `table_${String(index + 1).padStart(2, '0')}`)+ )mockPickerQueries({isEditing: false,@@ -320,7 +276,6 @@ describe('WarehouseSchemaTablePicker', () => {fireEvent.click(trigger)expect(screen.getByText('12 tables selected')).toBeInTheDocument()- expect(trigger.firstElementChild).toHaveClass('flex-wrap')expect(trigger).toHaveTextContent('public.table_01')expect(trigger).toHaveTextContent('public.table_10')expect(trigger).toHaveTextContent('+2')diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.test.ts b/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.test.tsindex c8b0fe58795..8b7903a8f27 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.test.ts+++ b/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.test.ts@@ -44,7 +44,7 @@ const stripe_wrapper = {}describe('getWrapperCreationFormSchema', () => {- it('should build a schema that validates tables mode', () => {+ it('should build a schema that validates tables mode and wrapper specific options', () => {const schema = getWrapperCreationFormSchema(stripe_wrapper)const result = schema.safeParse({ mode: 'tables' })@@ -57,6 +57,14 @@ describe('getWrapperCreationFormSchema', () => {expect(result.error?.issues.find((issue) => issue.path.some((p) => p === 'tables'))).toBeDefined()+ // Required wrapper option+ expect(+ result.error?.issues.find((issue) => issue.path.some((p) => p === 'api_key_id'))+ ).toBeDefined()+ // Optional wrapper option+ expect(+ result.error?.issues.find((issue) => issue.path.some((p) => p === 'api_url'))+ ).toBeUndefined()})it('should build a schema that validates schema mode', () => {@@ -76,20 +84,6 @@ describe('getWrapperCreationFormSchema', () => {result.error?.issues.find((issue) => issue.path.some((p) => p === 'target_schema'))).toBeDefined()})-- it('should build a schema that validates wrapper specific options', () => {- const schema = getWrapperCreationFormSchema(stripe_wrapper)- const result = schema.safeParse({ mode: 'tables' })- expect(result.success).toEqual(false)- // Required option- expect(- result.error?.issues.find((issue) => issue.path.some((p) => p === 'api_key_id'))- ).toBeDefined()- // Optional option- expect(- result.error?.issues.find((issue) => issue.path.some((p) => p === 'api_url'))- ).toBeUndefined()- })})describe('getEditionFormSchema', () => {@@ -213,7 +207,8 @@ describe('getTableFormSchema', () => {// ─── getRequiredExtensionsToInstall ──────────────────────────────────────────describe('getRequiredExtensionsToInstall', () => {- const wrappers = { name: 'wrappers', installed_version: null }+ type Extension = { name: string; installed_version: string | null }+ const wrappers: Extension = { name: 'wrappers', installed_version: null }const vault = { name: 'supabase_vault', installed_version: null }const wrappersInstalled = { name: 'wrappers', installed_version: '0.4.1' }const vaultInstalled = { name: 'supabase_vault', installed_version: '0.2.8' }@@ -223,17 +218,16 @@ describe('getRequiredExtensionsToInstall', () => {expect(getRequiredExtensionsToInstall(undefined, ['wrappers'])).toBeNull()})- it('returns empty array when required list is empty', () => {- expect(getRequiredExtensionsToInstall([wrappers], [])).toEqual([])- })-- it('returns empty array when all required extensions are already installed', () => {- expect(- getRequiredExtensionsToInstall(- [wrappersInstalled, vaultInstalled],- ['wrappers', 'supabase_vault']- )- ).toEqual([])+ it.each<{ case: string; extensions: Extension[]; required: string[] }>([+ { case: 'the required list is empty', extensions: [wrappers], required: [] },+ {+ case: 'all required extensions are already installed',+ extensions: [wrappersInstalled, vaultInstalled],+ required: ['wrappers', 'supabase_vault'],+ },+ { case: 'the extensions list is empty', extensions: [], required: ['wrappers'] },+ ])('returns an empty array when $case', ({ extensions, required }) => {+ expect(getRequiredExtensionsToInstall(extensions, required)).toEqual([])})it('returns extensions that are required but not installed', () => {@@ -255,10 +249,6 @@ describe('getRequiredExtensionsToInstall', () => {expect(result).toHaveLength(1)expect(result![0].name).toBe('wrappers')})-- it('returns empty array when extensions list is empty', () => {- expect(getRequiredExtensionsToInstall([], ['wrappers'])).toEqual([])- })})// ─── hasForeignSchemaSupport ──────────────────────────────────────────────────@@ -268,23 +258,14 @@ describe('hasForeignSchemaSupport', () => {expect(hasForeignSchemaSupport(undefined)).toBe(false)})- it('returns false when installed_version is null (not installed)', () => {- expect(hasForeignSchemaSupport({ installed_version: null })).toBe(false)- })-- it('returns false for version below 0.5.0', () => {- expect(hasForeignSchemaSupport({ installed_version: '0.4.9' })).toBe(false)- expect(hasForeignSchemaSupport({ installed_version: '0.3.0' })).toBe(false)- expect(hasForeignSchemaSupport({ installed_version: '0.1.0' })).toBe(false)- })-- it('returns true for exactly version 0.5.0', () => {- expect(hasForeignSchemaSupport({ installed_version: '0.5.0' })).toBe(true)- })-- it('returns true for version above 0.5.0', () => {- expect(hasForeignSchemaSupport({ installed_version: '0.6.0' })).toBe(true)- expect(hasForeignSchemaSupport({ installed_version: '0.5.1' })).toBe(true)- expect(hasForeignSchemaSupport({ installed_version: '1.0.0' })).toBe(true)+ it.each([+ [null, false],+ ['0.1.0', false],+ ['0.4.9', false],+ ['0.5.0', true],+ ['0.5.1', true],+ ['1.0.0', true],+ ])('installed_version %s returns %s', (installed_version, expected) => {+ expect(hasForeignSchemaSupport({ installed_version })).toBe(expected)})})diff --git a/apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/action-panel.test.tsx b/apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/action-panel.test.tsxindex 9589e6730e7..ca7945de590 100644--- a/apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/action-panel.test.tsx+++ b/apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/action-panel.test.tsx@@ -33,7 +33,6 @@ describe('ActionPanel', () => {expect.objectContaining({id: SHORTCUT_IDS.JWT_KEYS_CREATE_STANDBY,onTrigger: onClick,- side: 'bottom',options: { enabled: true },}),undefineddiff --git a/apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/create-key-dialog.test.tsx b/apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/create-key-dialog.test.tsxindex 582d8a4b9c2..70904df3e09 100644--- a/apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/create-key-dialog.test.tsx+++ b/apps/studio/components/interfaces/JwtSecrets/jwt-secret-keys-table/create-key-dialog.test.tsx@@ -39,7 +39,6 @@ describe('CreateKeyDialog', () => {id: SHORTCUT_IDS.JWT_KEYS_SUBMIT_STANDBY,onTrigger: expect.any(Function),options: { enabled: true },- side: 'top',}),undefined)diff --git a/apps/studio/components/interfaces/Linter/Linter.utils.test.tsx b/apps/studio/components/interfaces/Linter/Linter.utils.test.tsxindex 936184275d6..a40064cd6bc 100644--- a/apps/studio/components/interfaces/Linter/Linter.utils.test.tsx+++ b/apps/studio/components/interfaces/Linter/Linter.utils.test.tsx@@ -1,5 +1,3 @@-import { RulerIcon } from 'lucide-react'-import { isValidElement } from 'react'import { describe, expect, it } from 'vitest'import { lintInfoMap, parseLinterLevel } from './Linter.utils'@@ -75,10 +73,7 @@ describe('Linter.utils lintInfoMap pitr_archiving_stale entry', () => {const info = lintInfoMap.find((entry) => entry.name === 'pitr_archiving_stale')expect(info, 'expected pitr_archiving_stale in lintInfoMap').toBeDefined()- expect(info!.title).toBe('PITR archiving may be broken')- expect(isValidElement(info!.icon) && info!.icon.type).toBe(RulerIcon)expect(info!.category).toBe('security')- expect(info!.linkText).toBe('View settings')// metadata is unused by this entry's link(), and every field on Lint['metadata'] is optional, so {} needs no castexpect(info!.link({ projectRef, metadata: {} })).toBe('/project/abc/database/backups/pitr')expect(info!.docsLink).toContain('/guides/platform/backups#point-in-time-recovery')diff --git a/apps/studio/components/interfaces/LogDrains/LogDrainDestinationSheetForm.test.tsx b/apps/studio/components/interfaces/LogDrains/LogDrainDestinationSheetForm.test.tsxindex 741027c76e7..e2af08270b8 100644--- a/apps/studio/components/interfaces/LogDrains/LogDrainDestinationSheetForm.test.tsx+++ b/apps/studio/components/interfaces/LogDrains/LogDrainDestinationSheetForm.test.tsx@@ -72,6 +72,22 @@ const renderForm = (props?: Partial<ComponentProps<typeof LogDrainDestinationShereturn { onOpenChange, onSubmit }}+type User = ReturnType<typeof userEvent.setup>++const fillInput = async (user: User, input: HTMLElement, value: string) => {+ await user.click(input)+ await user.paste(value)+}++const fillRequiredFields = async (user: User) => {+ await fillInput(user, screen.getByPlaceholderText('My Destination'), 'Webhook sink')+ await fillInput(+ user,+ screen.getByPlaceholderText('https://example.com/log-drain'),+ 'https://logs.example.com/ingest'+ )+}+const submitForm = () =>fireEvent.submit(document.getElementById('log-drain-destination-form') as HTMLFormElement)@@ -100,9 +116,7 @@ describe('LogDrainDestinationSheetForm', () => {expect(mockShortcut).toHaveBeenCalledWith(expect.objectContaining({id: SHORTCUT_IDS.LOG_DRAINS_SAVE_DESTINATION,- onTrigger: expect.any(Function),options: { enabled: true },- side: 'top',}),undefined)@@ -115,7 +129,7 @@ describe('LogDrainDestinationSheetForm', () => {await screen.findByRole('dialog')- await user.type(screen.getByPlaceholderText('My Destination'), 'existing-drain')+ await fillInput(user, screen.getByPlaceholderText('My Destination'), 'existing-drain')submitForm()await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Log drain name already exists'))@@ -129,14 +143,10 @@ describe('LogDrainDestinationSheetForm', () => {await screen.findByRole('dialog')- await user.type(screen.getByPlaceholderText('My Destination'), 'Webhook sink')- await user.type(- screen.getByPlaceholderText('https://example.com/log-drain'),- 'https://logs.example.com/ingest'- )+ await fillRequiredFields(user)submitForm()- await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))+ await waitFor(() => expect(onSubmit).toHaveBeenCalled())expect(onSaveClick).toHaveBeenCalledWith('webhook')})@@ -157,18 +167,14 @@ describe('LogDrainDestinationSheetForm', () => {await screen.findByRole('dialog')- await user.type(screen.getByPlaceholderText('My Destination'), 'Webhook sink')- await user.type(- screen.getByPlaceholderText('https://example.com/log-drain'),- 'https://logs.example.com/ingest'- )+ await fillRequiredFields(user)await user.click(screen.getByRole('button', { name: 'Add a new header' }))const headerNameInputs = screen.getAllByPlaceholderText('Header name')const headerValueInputs = screen.getAllByPlaceholderText('Header value')- await user.type(headerNameInputs[0], 'X-API-Key')- await user.type(headerValueInputs[0], 'secret-key')+ await fillInput(user, headerNameInputs[0], 'X-API-Key')+ await fillInput(user, headerValueInputs[0], 'secret-key')submitForm()@@ -190,21 +196,17 @@ describe('LogDrainDestinationSheetForm', () => {await screen.findByRole('dialog')- await user.type(screen.getByPlaceholderText('My Destination'), 'Webhook sink')- await user.type(- screen.getByPlaceholderText('https://example.com/log-drain'),- 'https://logs.example.com/ingest'- )+ await fillRequiredFields(user)await user.click(screen.getByRole('button', { name: 'Add a new header' }))await user.click(screen.getByRole('button', { name: 'Add a new header' }))const headerNameInputs = screen.getAllByPlaceholderText('Header name')const headerValueInputs = screen.getAllByPlaceholderText('Header value')- await user.type(headerNameInputs[0], 'X-Custom')- await user.type(headerValueInputs[0], 'one')- await user.type(headerNameInputs[1], 'X-Custom')- await user.type(headerValueInputs[1], 'two')+ await fillInput(user, headerNameInputs[0], 'X-Custom')+ await fillInput(user, headerValueInputs[0], 'one')+ await fillInput(user, headerNameInputs[1], 'X-Custom')+ await fillInput(user, headerValueInputs[1], 'two')submitForm()@@ -218,11 +220,7 @@ describe('LogDrainDestinationSheetForm', () => {await screen.findByRole('dialog')- await user.type(screen.getByPlaceholderText('My Destination'), 'Webhook sink')- await user.type(- screen.getByPlaceholderText('https://example.com/log-drain'),- 'https://logs.example.com/ingest'- )+ await fillRequiredFields(user)await user.click(screen.getByRole('button', { name: 'Add a new header' }))submitForm()@@ -237,49 +235,26 @@ describe('LogDrainDestinationSheetForm', () => {expect(screen.queryByText('undefined')).not.toBeInTheDocument()})- it('shows an inline value error when a header key is entered without a value', async () => {- const user = userEvent.setup()- const { onSubmit } = renderForm()-- await screen.findByRole('dialog')+ it.each([+ ['value', 'Header name', 'X-Draft-Only', 'Header value is required'],+ ['key', 'Header value', 'draft-value', 'Header name is required'],+ ])(+ 'shows an inline %s error when only one side of a header is entered',+ async (_, placeholder, value, message) => {+ const user = userEvent.setup()+ const { onSubmit } = renderForm()- await user.type(screen.getByPlaceholderText('My Destination'), 'Webhook sink')- await user.type(- screen.getByPlaceholderText('https://example.com/log-drain'),- 'https://logs.example.com/ingest'- )- await user.click(screen.getByRole('button', { name: 'Add a new header' }))+ await screen.findByRole('dialog')- const headerNameInputs = screen.getAllByPlaceholderText('Header name')- await user.type(headerNameInputs[0], 'X-Draft-Only')+ await fillRequiredFields(user)+ await user.click(screen.getByRole('button', { name: 'Add a new header' }))+ await fillInput(user, screen.getByPlaceholderText(placeholder), value)- submitForm()+ submitForm()- expect(await screen.findByText('Header value is required')).toBeInTheDocument()- expect(onSubmit).not.toHaveBeenCalled()- expect(screen.queryByText('undefined')).not.toBeInTheDocument()- })-- it('shows an inline key error when a header value is entered without a key', async () => {- const user = userEvent.setup()- const { onSubmit } = renderForm()-- await screen.findByRole('dialog')-- await user.type(screen.getByPlaceholderText('My Destination'), 'Webhook sink')- await user.type(- screen.getByPlaceholderText('https://example.com/log-drain'),- 'https://logs.example.com/ingest'- )- await user.click(screen.getByRole('button', { name: 'Add a new header' }))-- const headerValueInputs = screen.getAllByPlaceholderText('Header value')- await user.type(headerValueInputs[0], 'draft-value')-- submitForm()-- expect(await screen.findByText('Header name is required')).toBeInTheDocument()- expect(onSubmit).not.toHaveBeenCalled()- expect(screen.queryByText('undefined')).not.toBeInTheDocument()- })+ expect(await screen.findByText(message)).toBeInTheDocument()+ expect(onSubmit).not.toHaveBeenCalled()+ expect(screen.queryByText('undefined')).not.toBeInTheDocument()+ }+ )})diff --git a/apps/studio/components/interfaces/LogDrains/LogDrains.utils.test.ts b/apps/studio/components/interfaces/LogDrains/LogDrains.utils.test.tsindex 5874e2915e2..40b3ce294cd 100644--- a/apps/studio/components/interfaces/LogDrains/LogDrains.utils.test.ts+++ b/apps/studio/components/interfaces/LogDrains/LogDrains.utils.test.ts@@ -11,45 +11,28 @@ import {} from './LogDrains.utils'describe('getHeadersSectionDescription', () => {- it('returns webhook description for webhook type', () => {- const result = getHeadersSectionDescription('webhook')- expect(result).toBe('Set custom headers when draining logs to the Endpoint URL')+ it.each(['webhook', 'loki', 'otlp'] as const)('returns a description for %s', (type) => {+ expect(getHeadersSectionDescription(type)).not.toBe('')})- it('returns loki description for loki type', () => {- const result = getHeadersSectionDescription('loki')- expect(result).toBe('Set custom headers when draining logs to the Loki HTTP(S) endpoint')- })-- it('returns otlp description for otlp type', () => {- const result = getHeadersSectionDescription('otlp')- expect(result).toBe(- 'Set custom headers for OTLP authentication (e.g., Authorization, X-API-Key)'- )- })-- it('returns empty string for unsupported types', () => {- expect(getHeadersSectionDescription('datadog')).toBe('')- expect(getHeadersSectionDescription('s3')).toBe('')- expect(getHeadersSectionDescription('sentry')).toBe('')+ it.each(['datadog', 's3', 'sentry'] as const)('returns an empty string for %s', (type) => {+ expect(getHeadersSectionDescription(type)).toBe('')})})describe('getDefaultHeadersByType', () => {- it('does not return a default Content-Type header for webhook destinations', () => {- expect(getDefaultHeadersByType('webhook')).toEqual({})- })-it('returns the protobuf content type header for OTLP destinations', () => {expect(getDefaultHeadersByType('otlp')).toEqual({'Content-Type': 'application/x-protobuf',})})- it('returns an empty object for destinations without default headers', () => {- expect(getDefaultHeadersByType('loki')).toEqual({})- expect(getDefaultHeadersByType('datadog')).toEqual({})- })+ it.each(['webhook', 'loki', 'datadog'] as const)(+ 'returns no default headers (incl. Content-Type) for %s',+ (type) => {+ expect(getDefaultHeadersByType(type)).toEqual({})+ }+ )})describe('headerRecordToRows', () => {@@ -162,174 +145,74 @@ describe('logDrainHeaderEntriesSchema', () => {})})+// URL parsing rules are covered in lib/validation/http-url.test.ts; these check the OTLP schema+// wiring (messages, defaults, type literal).describe('otlpConfigSchema', () => {- describe('valid OTLP configurations', () => {- it('accepts valid HTTPS endpoint with all fields', () => {- const config = {- type: 'otlp' as const,- endpoint: 'https://otlp.example.com:4318/v1/logs',- protocol: 'http/protobuf',- gzip: true,- headers: { Authorization: 'Bearer token' },- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(true)- if (result.success) {- expect(result.data).toEqual(config)- }- })-- it('accepts HTTP endpoint (for testing environments)', () => {- const config = {- type: 'otlp' as const,- endpoint: 'http://localhost:4318/v1/logs',- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(true)- })-- it('applies default values for optional fields', () => {- const config = {- type: 'otlp' as const,- endpoint: 'https://otlp.example.com/v1/logs',- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(true)- if (result.success) {- expect(result.data.protocol).toBe('http/protobuf')- expect(result.data.gzip).toBe(true)- }- })-- it('accepts empty headers object', () => {- const config = {- type: 'otlp' as const,- endpoint: 'https://otlp.example.com/v1/logs',- headers: {},- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(true)- })-- it('accepts multiple custom headers', () => {- const config = {- type: 'otlp' as const,- endpoint: 'https://otlp.example.com/v1/logs',- headers: {- Authorization: 'Bearer token',- 'X-API-Key': 'secret-key',- 'X-Custom-Header': 'custom-value',- },- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(true)- })+ it('accepts a full configuration unchanged', () => {+ const config = {+ type: 'otlp' as const,+ endpoint: 'https://otlp.example.com:4318/v1/logs',+ protocol: 'http/protobuf',+ gzip: true,+ headers: { Authorization: 'Bearer token' },+ }+ const result = otlpConfigSchema.safeParse(config)+ expect(result.success).toBe(true)+ if (result.success) {+ expect(result.data).toEqual(config)+ }})- describe('invalid OTLP configurations', () => {- it('rejects empty endpoint', () => {- const config = {- type: 'otlp' as const,- endpoint: '',- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(false)- if (!result.success) {- expect(result.error.issues[0].message).toContain('OTLP endpoint is required')- }- })-- it('rejects endpoint without protocol', () => {- const config = {- type: 'otlp' as const,- endpoint: 'otlp.example.com/v1/logs',- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(false)- if (!result.success) {- expect(result.error.issues[0].message).toContain('must start with http:// or https://')- }- })-- it('rejects endpoint with invalid protocol', () => {- const config = {- type: 'otlp' as const,- endpoint: 'ftp://otlp.example.com/v1/logs',- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(false)- })-- it('rejects endpoint with ws:// protocol', () => {- const config = {- type: 'otlp' as const,- endpoint: 'ws://otlp.example.com/v1/logs',- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(false)- })-- it('rejects endpoint with an incomplete hostname', () => {- const config = {- type: 'otlp' as const,- endpoint: 'https://webhook',- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(false)- if (!result.success) {- expect(result.error.issues[0].message).toContain('must be a valid URL')- }- })-- it('rejects wrong type field', () => {- const config = {- type: 'webhook' as const,- endpoint: 'https://otlp.example.com/v1/logs',- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(false)- })+ it.each([+ 'http://localhost:4318/v1/logs',+ 'https://otlp.example.com/v1/logs?tenant=123',+ 'https://user:[email protected]/v1/logs',+ ])('accepts endpoint %s', (endpoint) => {+ expect(otlpConfigSchema.safeParse({ type: 'otlp', endpoint }).success).toBe(true)})- describe('edge cases', () => {- it('accepts endpoint with port number', () => {- const config = {- type: 'otlp' as const,- endpoint: 'https://otlp.example.com:4318/v1/logs',- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(true)+ it('applies default values for optional fields', () => {+ const result = otlpConfigSchema.safeParse({+ type: 'otlp',+ endpoint: 'https://otlp.example.com/v1/logs',})+ expect(result.success).toBe(true)+ if (result.success) {+ expect(result.data.protocol).toBe('http/protobuf')+ expect(result.data.gzip).toBe(true)+ }+ })- it('accepts endpoint with query parameters', () => {- const config = {- type: 'otlp' as const,- endpoint: 'https://otlp.example.com/v1/logs?tenant=123',- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(true)+ it('allows gzip to be explicitly false', () => {+ const result = otlpConfigSchema.safeParse({+ type: 'otlp',+ endpoint: 'https://otlp.example.com/v1/logs',+ gzip: false,})+ expect(result.success).toBe(true)+ if (result.success) {+ expect(result.data.gzip).toBe(false)+ }+ })- it('accepts endpoint with authentication in URL', () => {- const config = {- type: 'otlp' as const,- endpoint: 'https://user:[email protected]/v1/logs',- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(true)- })+ it.each([+ ['', 'OTLP endpoint is required'],+ ['otlp.example.com/v1/logs', 'must start with http:// or https://'],+ ['ws://otlp.example.com/v1/logs', undefined],+ ['https://webhook', 'must be a valid URL'],+ ])('rejects endpoint %j', (endpoint, message) => {+ const result = otlpConfigSchema.safeParse({ type: 'otlp', endpoint })+ expect(result.success).toBe(false)+ if (!result.success && message) {+ expect(result.error.issues[0].message).toContain(message)+ }+ })- it('allows gzip to be explicitly false', () => {- const config = {- type: 'otlp' as const,- endpoint: 'https://otlp.example.com/v1/logs',- gzip: false,- }- const result = otlpConfigSchema.safeParse(config)- expect(result.success).toBe(true)- if (result.success) {- expect(result.data.gzip).toBe(false)- }+ it('rejects wrong type field', () => {+ const result = otlpConfigSchema.safeParse({+ type: 'webhook',+ endpoint: 'https://otlp.example.com/v1/logs',})+ expect(result.success).toBe(false)})})diff --git a/apps/studio/components/interfaces/MCP/Secrets/McpSecrets.params.test.ts b/apps/studio/components/interfaces/MCP/Secrets/McpSecrets.params.test.tsindex 1c0b2438802..e3079da37db 100644--- a/apps/studio/components/interfaces/MCP/Secrets/McpSecrets.params.test.ts+++ b/apps/studio/components/interfaces/MCP/Secrets/McpSecrets.params.test.ts@@ -3,14 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { buildSecretsSignInPath, parseSecretsParams } from './McpSecrets.params'describe('parseSecretsParams', () => {- it('reads the project ref and secret name', () => {- const params = parseSecretsParams({ ref: 'abcdefghijklmnopqrst', name: 'OPENAI_API_KEY' })-- expect(params.ref).toBe('abcdefghijklmnopqrst')- expect(params.name).toBe('OPENAI_API_KEY')- })-- it('ignores params it has never seen rather than rejecting them', () => {+ it('reads the project ref and secret name, ignoring params it has never seen', () => {const params = parseSecretsParams({ref: 'abcdefghijklmnopqrst',name: 'OPENAI_API_KEY',diff --git a/apps/studio/components/interfaces/MCP/Secrets/McpSecretsCard.test.tsx b/apps/studio/components/interfaces/MCP/Secrets/McpSecretsCard.test.tsxindex 9337338c95c..389daae8412 100644--- a/apps/studio/components/interfaces/MCP/Secrets/McpSecretsCard.test.tsx+++ b/apps/studio/components/interfaces/MCP/Secrets/McpSecretsCard.test.tsx@@ -34,7 +34,8 @@ describe('McpSecretsCard', () => {const user = userEvent.setup()const { rerender } = renderCard({ status: 'form', request })- await user.type(secretField(), 'sk-for-the-first-request')+ await user.click(secretField())+ await user.paste('sk-for-the-first-request')await user.click(screen.getByRole('button', { name: 'Show secret value' }))expect(secretField().value).toBe('sk-for-the-first-request')expect(secretField().type).toBe('text')@@ -58,7 +59,8 @@ describe('McpSecretsCard', () => {const user = userEvent.setup()const { rerender } = renderCard({ status: 'form', request })- await user.type(secretField(), 'sk-for-project-a')+ await user.click(secretField())+ await user.paste('sk-for-project-a')rerender(<McpSecretsCard@@ -80,7 +82,8 @@ describe('McpSecretsCard', () => {const user = userEvent.setup()const { rerender } = renderCard({ status: 'form', request })- await user.type(secretField(), 'sk-still-being-typed')+ await user.click(secretField())+ await user.paste('sk-still-being-typed')rerender(<McpSecretsCard@@ -110,7 +113,8 @@ describe('McpSecretsCard', () => {expect(liveRegion).toHaveAttribute('aria-live', 'polite')expect(liveRegion).toBeEmptyDOMElement()- await user.type(secretField(), 'not-a-real-prefix')+ await user.click(secretField())+ await user.paste('not-a-real-prefix')await waitFor(() => expect(liveRegion).toHaveTextContent(/usually start with sk-/))expect(screen.getByRole('status')).toBe(liveRegion)@@ -149,7 +153,8 @@ describe('McpSecretsCard', () => {/>)- await user.type(secretField(), ' sk-padded ')+ await user.click(secretField())+ await user.paste(' sk-padded ')fireEvent.click(screen.getByRole('button', { name: 'Save' }))await waitFor(() => expect(onSave).toHaveBeenCalledWith(' sk-padded '))diff --git a/apps/studio/components/interfaces/MCP/Secrets/useSecretRequest.test.ts b/apps/studio/components/interfaces/MCP/Secrets/useSecretRequest.test.tsindex edbbb383f6a..4b5bfe785a7 100644--- a/apps/studio/components/interfaces/MCP/Secrets/useSecretRequest.test.ts+++ b/apps/studio/components/interfaces/MCP/Secrets/useSecretRequest.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { act, waitFor } from '@testing-library/react'import { delay, HttpResponse } from 'msw'import { beforeEach, describe, expect, it } from 'vitest'@@ -18,7 +19,7 @@ const paramsFor = (ref: string, name: string): SecretsParams => ({dev: { state: undefined },})-const WRITE_DELAY_MS = 120+const WRITE_DELAY_MS = 50const PROJECT: components['schemas']['ProjectDetailResponse_Output'] = {cloud_provider: 'AWS',diff --git a/apps/studio/components/interfaces/Observability/DatabaseInfrastructureMetric.test.tsx b/apps/studio/components/interfaces/Observability/DatabaseInfrastructureMetric.test.tsxindex 664f637ff6a..e5fc7de2be4 100644--- a/apps/studio/components/interfaces/Observability/DatabaseInfrastructureMetric.test.tsx+++ b/apps/studio/components/interfaces/Observability/DatabaseInfrastructureMetric.test.tsx@@ -91,21 +91,19 @@ function card(label: string) {}describe('DatabaseInfrastructureSection batched metrics', () => {- it.each([false, true])(- 'renders all metrics from one request (errors field: %s)',- async (includeErrors) => {- const requests = mockMetrics(undefined, includeErrors)- renderMetrics()+ // Responses with an `errors` field are exercised by the isolation cases below+ it('renders all metrics from one request without an errors field', async () => {+ const requests = mockMetrics(undefined, false)+ renderMetrics()- expect(await card('CPU').findByText('25%')).toBeInTheDocument()- expect(await card('Memory').findByText('60%')).toBeInTheDocument()- expect(await card('Disk IO balance').findByText('99%')).toBeInTheDocument()- expect(await card('Disk Usage').findByText('50%')).toBeInTheDocument()- expect(await card('Peak Connections').findByText('12/100')).toBeInTheDocument()- expect(requests).toHaveLength(1)- expect(requests[0].sort()).toEqual(Object.keys(values).sort())- }- )+ expect(await card('CPU').findByText('25%')).toBeInTheDocument()+ expect(await card('Memory').findByText('60%')).toBeInTheDocument()+ expect(await card('Disk IO balance').findByText('99%')).toBeInTheDocument()+ expect(await card('Disk Usage').findByText('50%')).toBeInTheDocument()+ expect(await card('Peak Connections').findByText('12/100')).toBeInTheDocument()+ expect(requests).toHaveLength(1)+ expect(requests[0].sort()).toEqual(Object.keys(values).sort())+ })it.each([['disk_io_budget', 'Disk IO balance'],diff --git a/apps/studio/components/interfaces/Observability/DatabaseInfrastructureSection.utils.test.ts b/apps/studio/components/interfaces/Observability/DatabaseInfrastructureSection.utils.test.tsindex 9fc2ae19310..41d9df5fa5d 100644--- a/apps/studio/components/interfaces/Observability/DatabaseInfrastructureSection.utils.test.ts+++ b/apps/studio/components/interfaces/Observability/DatabaseInfrastructureSection.utils.test.ts@@ -88,55 +88,6 @@ describe('parseInfrastructureMetrics', () => {})})- it('handles string values in metrics', () => {- const mockResponse: InfraMonitoringMultiResponse = {- data: [],- series: {- avg_cpu_usage: { format: 'percent', total: 150, totalAverage: '50.5', yAxisLimit: 100 },- ram_usage: { format: 'bytes', total: 180, totalAverage: '60.8', yAxisLimit: 100 },- disk_fs_used_system: {- format: 'bytes',- total: 20,- totalAverage: '20.4',- yAxisLimit: 100,- },- disk_fs_used_wal: {- format: 'bytes',- total: 10,- totalAverage: '10.2',- yAxisLimit: 100,- },- pg_database_size: {- format: 'bytes',- total: 30,- totalAverage: '30.5',- yAxisLimit: 100,- },- disk_fs_size: {- format: 'bytes',- total: 200,- totalAverage: '200.0',- yAxisLimit: 100,- },- disk_io_budget: {- format: 'percent',- total: 210,- totalAverage: '70.2',- yAxisLimit: 100,- },- },- }-- const result = parseInfrastructureMetrics(mockResponse)-- expect(result).toEqual({- cpu: { current: 50.5, max: 100 },- ram: { current: 60.8, max: 100 },- disk: { current: 30.55, max: 100 },- diskIo: { current: 70.2, max: 100 },- })- })-it('uses average remaining balance in the selected window rather than consumed IO or its lowest sample', () => {const response: InfraMonitoringMultiResponse = {data: [@@ -258,20 +209,14 @@ describe('parseConnectionsData', () => {expect(result).toEqual({ peak: 7, max: 100 })})- it('skips missing values when computing peak', () => {- const mockInfraData = buildResponse([5, undefined, 7, undefined])-- const result = parseConnectionsData(mockInfraData, { maxConnections: 100 })-- expect(result).toEqual({ peak: 7, max: 100 })- })-- it('skips empty-string values when computing peak', () => {- const mockInfraData = buildResponse(['5', '', '7', ''])-- const result = parseConnectionsData(mockInfraData, { maxConnections: 100 })-- expect(result).toEqual({ peak: 7, max: 100 })+ it.each([+ ['missing', [5, undefined, 7, undefined]],+ ['empty-string', ['5', '', '7', '']],+ ])('skips %s values when computing peak', (_, values) => {+ expect(parseConnectionsData(buildResponse(values), { maxConnections: 100 })).toEqual({+ peak: 7,+ max: 100,+ })})it('returns peak connections even when maxConnectionsData is undefined', () => {diff --git a/apps/studio/components/interfaces/Observability/ObservabilityOverview.utils.test.ts b/apps/studio/components/interfaces/Observability/ObservabilityOverview.utils.test.tsindex 4a0e63b1827..5a290265b93 100644--- a/apps/studio/components/interfaces/Observability/ObservabilityOverview.utils.test.ts+++ b/apps/studio/components/interfaces/Observability/ObservabilityOverview.utils.test.ts@@ -7,243 +7,59 @@ import {getHealthStatus,} from './ObservabilityOverview.utils'-describe('calculateErrorRate', () => {- it('returns 0 when total is 0', () => {- const data: LogsBarChartDatum[] = [- { timestamp: '2024-01-15T12:00:00Z', ok_count: 0, warning_count: 0, error_count: 0 },- ]-- expect(calculateErrorRate(data)).toBe(0)- })-- it('calculates correct error rate', () => {- const data: LogsBarChartDatum[] = [- { timestamp: '2024-01-15T12:00:00Z', ok_count: 80, warning_count: 10, error_count: 10 },- ]-- expect(calculateErrorRate(data)).toBe(10)- })-- it('calculates error rate across multiple data points', () => {- const data: LogsBarChartDatum[] = [- { timestamp: '2024-01-15T12:00:00Z', ok_count: 50, warning_count: 25, error_count: 25 },- { timestamp: '2024-01-15T12:01:00Z', ok_count: 50, warning_count: 25, error_count: 25 },- ]-- expect(calculateErrorRate(data)).toBe(25)- })-- it('handles high error rates', () => {- const data: LogsBarChartDatum[] = [- { timestamp: '2024-01-15T12:00:00Z', ok_count: 10, warning_count: 10, error_count: 80 },- ]-- expect(calculateErrorRate(data)).toBe(80)- })+const datum = (ok: number, warning: number, error: number): LogsBarChartDatum => ({+ timestamp: '2024-01-15T12:00:00Z',+ ok_count: ok,+ warning_count: warning,+ error_count: error,+})- it('handles empty array', () => {- expect(calculateErrorRate([])).toBe(0)+describe('calculateErrorRate', () => {+ it.each([+ ['an empty array', [], 0],+ ['zero total', [datum(0, 0, 0)], 0],+ ['a single data point', [datum(80, 10, 10)], 10],+ ['multiple data points', [datum(50, 25, 25), datum(50, 25, 25)], 25],+ ])('handles %s', (_, data, expected) => {+ expect(calculateErrorRate(data)).toBe(expected)})})describe('calculateSuccessRate', () => {- it('returns 0 when total is 0', () => {- const data: LogsBarChartDatum[] = [- { timestamp: '2024-01-15T12:00:00Z', ok_count: 0, warning_count: 0, error_count: 0 },- ]-- expect(calculateSuccessRate(data)).toBe(0)- })-- it('calculates correct success rate', () => {- const data: LogsBarChartDatum[] = [- { timestamp: '2024-01-15T12:00:00Z', ok_count: 80, warning_count: 10, error_count: 10 },- ]-- expect(calculateSuccessRate(data)).toBe(80)- })-- it('returns 100% for all successful requests', () => {- const data: LogsBarChartDatum[] = [- { timestamp: '2024-01-15T12:00:00Z', ok_count: 100, warning_count: 0, error_count: 0 },- ]-- expect(calculateSuccessRate(data)).toBe(100)- })-- it('calculates success rate across multiple data points', () => {- const data: LogsBarChartDatum[] = [- { timestamp: '2024-01-15T12:00:00Z', ok_count: 70, warning_count: 15, error_count: 15 },- { timestamp: '2024-01-15T12:01:00Z', ok_count: 70, warning_count: 15, error_count: 15 },- ]-- expect(calculateSuccessRate(data)).toBe(70)- })-- it('handles empty array', () => {- expect(calculateSuccessRate([])).toBe(0)+ it.each([+ ['an empty array', [], 0],+ ['zero total', [datum(0, 0, 0)], 0],+ ['a single data point', [datum(80, 10, 10)], 80],+ ['all successful requests', [datum(100, 0, 0)], 100],+ ['multiple data points', [datum(70, 15, 15), datum(70, 15, 15)], 70],+ ])('handles %s', (_, data, expected) => {+ expect(calculateSuccessRate(data)).toBe(expected)})})describe('getHealthStatus', () => {- describe('unknown status', () => {- it('returns unknown when total is 0', () => {- const result = getHealthStatus(0, 0)-- expect(result).toEqual({- status: 'unknown',- color: 'muted',- })- })-- it('returns unknown when total is below 100', () => {- const result = getHealthStatus(5, 50)-- expect(result).toEqual({- status: 'unknown',- color: 'muted',- })- })-- it('returns unknown when total is exactly 99', () => {- const result = getHealthStatus(10, 99)-- expect(result).toEqual({- status: 'unknown',- color: 'muted',- })- })-- it('returns unknown even with high error rate when total is low', () => {- const result = getHealthStatus(50, 20)-- expect(result).toEqual({- status: 'unknown',- color: 'muted',- })- })+ it.each([+ [0, 0],+ [10, 99],+ // a high error rate is still unknown below the minimum sample size+ [50, 20],+ ])('returns unknown for error rate %s with only %s requests', (errorRate, total) => {+ expect(getHealthStatus(errorRate, total)).toEqual({ status: 'unknown', color: 'muted' })})- describe('error status', () => {- it('returns error when error rate is exactly 1%', () => {- const result = getHealthStatus(1, 100)-- expect(result).toEqual({- status: 'error',- color: 'destructive',- })- })-- it('returns error when error rate is above 1%', () => {- const result = getHealthStatus(5, 100)-- expect(result).toEqual({- status: 'error',- color: 'destructive',- })- })-- it('returns error when error rate is 10%', () => {- const result = getHealthStatus(10, 200)-- expect(result).toEqual({- status: 'error',- color: 'destructive',- })- })-- it('returns error for very high error rates', () => {- const result = getHealthStatus(90, 1000)-- expect(result).toEqual({- status: 'error',- color: 'destructive',- })- })+ it.each([+ [1, 100],+ [5, 100],+ [90, 1000],+ ])('returns error for error rate %s%% over %s requests', (errorRate, total) => {+ expect(getHealthStatus(errorRate, total)).toEqual({ status: 'error', color: 'destructive' })})- describe('healthy status', () => {- it('returns healthy when error rate is 0% with sufficient data', () => {- const result = getHealthStatus(0, 100)-- expect(result).toEqual({- status: 'healthy',- color: 'brand',- })- })-- it('returns healthy when error rate is below 1%', () => {- const result = getHealthStatus(0.5, 100)-- expect(result).toEqual({- status: 'healthy',- color: 'brand',- })- })-- it('returns healthy when error rate is just below 1%', () => {- const result = getHealthStatus(0.99, 100)-- expect(result).toEqual({- status: 'healthy',- color: 'brand',- })- })-- it('returns healthy with 0% error rate and large total', () => {- const result = getHealthStatus(0, 10000)-- expect(result).toEqual({- status: 'healthy',- color: 'brand',- })- })- })-- describe('edge cases', () => {- it('handles fractional error rates correctly', () => {- const result = getHealthStatus(0.99, 1000)-- expect(result).toEqual({- status: 'healthy',- color: 'brand',- })- })-- it('returns unknown for very small total values', () => {- const result = getHealthStatus(10, 1)-- expect(result).toEqual({- status: 'unknown',- color: 'muted',- })- })-- it('handles very large total values', () => {- const result = getHealthStatus(0.5, 1000000)-- expect(result).toEqual({- status: 'healthy',- color: 'brand',- })- })-- it('returns healthy when total is exactly 100 and error rate is 0', () => {- const result = getHealthStatus(0, 100)-- expect(result).toEqual({- status: 'healthy',- color: 'brand',- })- })-- it('returns error when total is exactly 100 and error rate is 1%', () => {- const result = getHealthStatus(1, 100)-- expect(result).toEqual({- status: 'error',- color: 'destructive',- })- })+ it.each([+ [0, 100],+ [0.99, 100],+ [0.5, 1000000],+ ])('returns healthy for error rate %s%% over %s requests', (errorRate, total) => {+ expect(getHealthStatus(errorRate, total)).toEqual({ status: 'healthy', color: 'brand' })})})diff --git a/apps/studio/components/interfaces/Observability/useServiceHealthMetrics.test.ts b/apps/studio/components/interfaces/Observability/useServiceHealthMetrics.test.tsindex ecc27af0f78..6b732db0196 100644--- a/apps/studio/components/interfaces/Observability/useServiceHealthMetrics.test.ts+++ b/apps/studio/components/interfaces/Observability/useServiceHealthMetrics.test.ts@@ -49,23 +49,22 @@ describe('extractServiceRows', () => {expect(extractServiceRows([], 'db')).toEqual([])})- it('preserves the timestamp from each row', () => {+ it('maps each row independently, preserving its timestamp', () => {const rows = [- makeRow({ timestamp: '2026-05-20T09:00:00' }),- makeRow({ timestamp: '2026-05-20T10:00:00' }),+ makeRow({+ timestamp: '2026-05-20T09:00:00',+ postgres_logs: { ok: 100, warning: 0, error: 0, total: 100 },+ }),+ makeRow({+ timestamp: '2026-05-20T10:00:00',+ postgres_logs: { ok: 50, warning: 5, error: 10, total: 65 },+ }),]const result = extractServiceRows(rows, 'db')- expect(result.map((r) => r.timestamp)).toEqual(['2026-05-20T09:00:00', '2026-05-20T10:00:00'])- })-- it('handles multiple rows and maps each independently', () => {- const rows = [- makeRow({ postgres_logs: { ok: 100, warning: 0, error: 0, total: 100 } }),- makeRow({ postgres_logs: { ok: 50, warning: 5, error: 10, total: 65 } }),- ]- const result = extractServiceRows(rows, 'db')- expect(result[0]).toMatchObject({ ok_count: 100, warning_count: 0, error_count: 0 })- expect(result[1]).toMatchObject({ ok_count: 50, warning_count: 5, error_count: 10 })+ expect(result).toEqual([+ { timestamp: '2026-05-20T09:00:00', ok_count: 100, warning_count: 0, error_count: 0 },+ { timestamp: '2026-05-20T10:00:00', ok_count: 50, warning_count: 5, error_count: 10 },+ ])})it('defaults to 0 when the service field is missing from the row', () => {diff --git a/apps/studio/components/interfaces/Observability/useServiceHealthMetrics.utils.test.ts b/apps/studio/components/interfaces/Observability/useServiceHealthMetrics.utils.test.tsindex 5faf3138bad..b1076b4a659 100644--- a/apps/studio/components/interfaces/Observability/useServiceHealthMetrics.utils.test.ts+++ b/apps/studio/components/interfaces/Observability/useServiceHealthMetrics.utils.test.ts@@ -1,4 +1,3 @@-import dayjs from 'dayjs'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { LogsBarChartDatum } from '../ProjectHome/ProjectUsage.metrics'@@ -20,40 +19,14 @@ describe('calculateDateRange', () => {vi.useRealTimers()})- it('calculates correct date range for 1hr interval', () => {- const result = calculateDateRange('1hr')-- expect(result.startDate).toBe('2024-01-15T11:00:00.000Z')- expect(result.endDate).toBe('2024-01-15T12:00:00.000Z')- })-- it('calculates correct date range for 1day interval', () => {- const result = calculateDateRange('1day')-- expect(result.startDate).toBe('2024-01-14T12:00:00.000Z')- expect(result.endDate).toBe('2024-01-15T12:00:00.000Z')- })-- it('calculates correct date range for 7day interval', () => {- const result = calculateDateRange('7day')-- expect(result.startDate).toBe('2024-01-08T12:00:00.000Z')- expect(result.endDate).toBe('2024-01-15T12:00:00.000Z')- })-- it('returns ISO format strings', () => {- const result = calculateDateRange('1hr')-- expect(dayjs(result.startDate).isValid()).toBe(true)- expect(dayjs(result.endDate).isValid()).toBe(true)- })-- it('end date is always after start date', () => {- const intervals: Array<'1hr' | '1day' | '7day'> = ['1hr', '1day', '7day']-- intervals.forEach((interval) => {- const result = calculateDateRange(interval)- expect(dayjs(result.endDate).isAfter(dayjs(result.startDate))).toBe(true)+ it.each([+ ['1hr', '2024-01-15T11:00:00.000Z'],+ ['1day', '2024-01-14T12:00:00.000Z'],+ ['7day', '2024-01-08T12:00:00.000Z'],+ ] as const)('calculates the date range for the %s interval', (interval, startDate) => {+ expect(calculateDateRange(interval)).toEqual({+ startDate,+ endDate: '2024-01-15T12:00:00.000Z',})})})@@ -109,16 +82,6 @@ describe('transformToBarChartData', () => {expect(result).toEqual([])})-- it('preserves timestamp values', () => {- const rawData = [- { timestamp: '2024-01-15T12:00:00Z', ok_count: 10, warning_count: 0, error_count: 0 },- ]-- const result = transformToBarChartData(rawData)-- expect(result[0].timestamp).toBe('2024-01-15T12:00:00Z')- })})describe('calculateHealthMetrics', () => {@@ -174,27 +137,14 @@ describe('calculateHealthMetrics', () => {})})- it('returns 0 error rate when total is 0', () => {- const eventChartData: LogsBarChartDatum[] = [- { timestamp: '2024-01-15T12:00:00Z', ok_count: 0, warning_count: 0, error_count: 0 },- ]-- const result = calculateHealthMetrics(eventChartData)-- expect(result).toEqual({- total: 0,- errorRate: 0,- successRate: 0,- errorCount: 0,- warningCount: 0,- okCount: 0,- })- })-- it('handles empty array', () => {- const result = calculateHealthMetrics([])-- expect(result).toEqual({+ it.each([+ [+ 'zero total',+ [{ timestamp: '2024-01-15T12:00:00Z', ok_count: 0, warning_count: 0, error_count: 0 }],+ ],+ ['an empty array', []],+ ])('returns zeroed metrics for %s', (_, eventChartData: LogsBarChartDatum[]) => {+ expect(calculateHealthMetrics(eventChartData)).toEqual({total: 0,errorRate: 0,successRate: 0,@@ -222,17 +172,6 @@ describe('calculateHealthMetrics', () => {okCount: 100,})})-- it('calculates correct error rate for high error scenario', () => {- const eventChartData: LogsBarChartDatum[] = [- { timestamp: '2024-01-15T12:00:00Z', ok_count: 10, warning_count: 10, error_count: 80 },- ]-- const result = calculateHealthMetrics(eventChartData)-- expect(result.errorRate).toBe(80)- expect(result.successRate).toBe(10)- })})describe('calculateAggregatedMetrics', () => {@@ -266,20 +205,6 @@ describe('calculateAggregatedMetrics', () => {})})- it('handles single service', () => {- const services = [{ total: 100, errorCount: 10, warningCount: 5 }]-- const result = calculateAggregatedMetrics(services)-- expect(result).toEqual({- totalRequests: 100,- totalErrors: 10,- totalWarnings: 5,- overallErrorRate: 15,- overallSuccessRate: 85,- })- })-it('handles services with zero metrics', () => {const services = [{ total: 0, errorCount: 0, warningCount: 0 },@@ -297,23 +222,6 @@ describe('calculateAggregatedMetrics', () => {})})- it('calculates correct rates when all requests are successful', () => {- const services = [- { total: 100, errorCount: 0, warningCount: 0 },- { total: 200, errorCount: 0, warningCount: 0 },- ]-- const result = calculateAggregatedMetrics(services)-- expect(result).toEqual({- totalRequests: 300,- totalErrors: 0,- totalWarnings: 0,- overallErrorRate: 0,- overallSuccessRate: 100,- })- })-it('calculates correct rates when all requests fail', () => {const services = [{ total: 100, errorCount: 100, warningCount: 0 },diff --git a/apps/studio/components/interfaces/Observability/useSlowQueriesCount.test.ts b/apps/studio/components/interfaces/Observability/useSlowQueriesCount.test.tsindex 42b27b654f8..3db87e21d1e 100644--- a/apps/studio/components/interfaces/Observability/useSlowQueriesCount.test.ts+++ b/apps/studio/components/interfaces/Observability/useSlowQueriesCount.test.ts@@ -3,19 +3,14 @@ import { describe, expect, it } from 'vitest'import { buildSlowQueriesCountSql } from './useSlowQueriesCount'describe('buildSlowQueriesCountSql', () => {- it('checks pg_extension before querying pg_stat_statements', () => {+ it('guards on the pg_stat_statements extension and returns 0 when it is missing', () => {const sql = buildSlowQueriesCountSql()expect(sql).toContain('pg_extension')expect(sql).toContain("extname = 'pg_stat_statements'")+ expect(sql).toContain('ELSE 0')})- it('returns 0 when extension is not installed', () => {- expect(buildSlowQueriesCountSql()).toContain('ELSE 0')- })-- it('still queries pg_stat_statements when extension exists', () => {- const sql = buildSlowQueriesCountSql()- expect(sql).toContain('pg_stat_statements')- expect(sql).toContain('total_exec_time + total_plan_time > 1000')+ it('counts queries slower than 1s from pg_stat_statements', () => {+ expect(buildSlowQueriesCountSql()).toContain('total_exec_time + total_plan_time > 1000')})})diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.test.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.test.tsxindex cdd43999302..6177a8365ef 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.test.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.test.tsx@@ -149,7 +149,7 @@ describe('BillingEmail', () => {const emailInput = await screen.findByPlaceholderText('Email')await userEvent.clear(emailInput)- await userEvent.type(emailInput, '[email protected]')+ await userEvent.paste('[email protected]')fireEvent.click(await screen.findByRole('button', { name: 'Save' }))@@ -239,7 +239,7 @@ describe('BillingEmail', () => {await waitFor(() => expect(emailInput).toHaveValue('[email protected]'))await userEvent.clear(emailInput)- await userEvent.type(emailInput, '[email protected]')+ await userEvent.paste('[email protected]')// Simulate an unrelated refetch of the same shared customer-profile query (e.g. triggered// by another section, or a background refetch) returning newer server data.diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanCards.utils.test.ts b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanCards.utils.test.tsindex eafa53800ca..45bab03d39e 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanCards.utils.test.ts+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanCards.utils.test.ts@@ -3,22 +3,14 @@ import { describe, expect, it } from 'vitest'import { getPlanCardsEntryAnimation } from './PlanCards.utils'describe('getPlanCardsEntryAnimation', () => {- it('staggers the cards after the container delay', () => {- const animation = getPlanCardsEntryAnimation(0.4)+ it.each([0, 0.4])('staggers the cards after a container delay of %s', (entryDelay) => {+ const animation = getPlanCardsEntryAnimation(entryDelay)expect(animation.container.initial).toBe('hidden')expect(animation.container.animate).toBe('visible')- expect(animation.card).toBeDefined()const visible = animation.container.variants.visible as { transition: Record<string, number> }- expect(visible.transition.delayChildren).toBeCloseTo(0.6)- expect(visible.transition.staggerChildren).toBe(0.08)- })-- it('animates with a zero delay', () => {- const animation = getPlanCardsEntryAnimation(0)-- expect(animation.container.initial).toBe('hidden')- expect(animation.card).toBeDefined()+ expect(visible.transition.delayChildren).toBeGreaterThan(entryDelay)+ expect(visible.transition.staggerChildren).toBeGreaterThan(0)})})diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.roleValidation.test.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.roleValidation.test.tsxdeleted file mode 100644index 06a36328029..00000000000--- a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.roleValidation.test.tsx+++ /dev/null@@ -1,142 +0,0 @@-import { fireEvent, screen } from '@testing-library/react'-import { describe, expect, test, vi } from 'vitest'--import { OAuthAppsAuthorizeScreen } from './OAuthAppsAuthorizeScreen'-import {- getMockOAuthAppsAuthorizeRequest,- OAUTH_APPS_MOCK_SCENARIOS,-} from '@/data/oauth-apps/mocks'-import { customRender } from '@/tests/lib/custom-render'--function renderScreen(authId: string) {- return customRender(- <OAuthAppsAuthorizeScreen- authId={authId}- request={getMockOAuthAppsAuthorizeRequest(authId)}- navigate={vi.fn()}- />- )-}--const READ_ONLY_PROJECTS = ['fabrikam-api', 'fabrikam-jobs']-const WRITABLE_PROJECT = 'northwind-cms'--async function selectProjects(names: string[]) {- fireEvent.click(await screen.findByRole('combobox'))- names.forEach((name) => fireEvent.click(screen.getByText(name)))-}--function authorize() {- fireEvent.click(screen.getByRole('button', { name: /Authorize Vercel/ }))-}--function deselectFlagged() {- fireEvent.click(screen.getByRole('button', { name: 'Deselect 2 projects' }))-}--async function submitTwoBlockedAndOneAllowed() {- renderScreen(OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation)-- await selectProjects([...READ_ONLY_PROJECTS, WRITABLE_PROJECT])- authorize()-- return screen.findByText("Couldn't authorize 2 projects")-}--describe('OAuthAppsAuthorizeScreen post-submit role validation', () => {- test('surfaces the failure banner naming the blocked project count', async () => {- expect(await submitTwoBlockedAndOneAllowed()).toBeInTheDocument()- expect(- screen.getByText(- 'Vercel needs write access but your role is read-only on the projects highlighted. Deselect them to continue.'- )- ).toBeInTheDocument()- })-- test('counts the blocked projects against the submitted selection', async () => {- await submitTwoBlockedAndOneAllowed()-- expect(screen.getByText(/2 of 3\s+projects unavailable/)).toBeInTheDocument()- })-- test('turns the primary action into the deselect shortcut', async () => {- await submitTwoBlockedAndOneAllowed()-- expect(screen.getByRole('button', { name: 'Deselect 2 projects' })).toBeInTheDocument()- expect(screen.queryByRole('button', { name: /Authorize Vercel/ })).not.toBeInTheDocument()- })-- test('marks the rejected projects in the dropdown', async () => {- await submitTwoBlockedAndOneAllowed()-- const marks = screen.getAllByText('- Unavailable')- expect(marks).toHaveLength(READ_ONLY_PROJECTS.length)- })-- test('keeps the dropdown marks after the projects are deselected', async () => {- await submitTwoBlockedAndOneAllowed()-- deselectFlagged()-- expect(screen.getAllByText('- Unavailable')).toHaveLength(READ_ONLY_PROJECTS.length)- })-- test('drops the inline deselect link beneath the picker', async () => {- await submitTwoBlockedAndOneAllowed()-- expect(screen.queryByText('Deselect projects')).not.toBeInTheDocument()- })-- test('deselecting the blocked projects clears the whole failure treatment', async () => {- await submitTwoBlockedAndOneAllowed()-- deselectFlagged()-- expect(screen.queryByText("Couldn't authorize 2 projects")).not.toBeInTheDocument()- expect(screen.queryByText(/projects unavailable/)).not.toBeInTheDocument()- expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeInTheDocument()- })-- test('retrying with only writable projects reaches the success screen', async () => {- await submitTwoBlockedAndOneAllowed()-- deselectFlagged()- authorize()-- expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()- })-- test('a selection of only writable projects never triggers validation', async () => {- renderScreen(OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation)-- await selectProjects([WRITABLE_PROJECT])- authorize()-- expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()- })-- test('a preselected read-only project still produces the post-submit banner', async () => {- customRender(- <OAuthAppsAuthorizeScreen- authId={OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation}- request={getMockOAuthAppsAuthorizeRequest(OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation)}- projectRef="fabrikamapi1"- navigate={vi.fn()}- />- )-- await screen.findByText('fabrikam-api')- authorize()-- expect(await screen.findByText("Couldn't authorize 1 project")).toBeInTheDocument()- })-- test('a request outside the role-validated set approves read-only projects', async () => {- renderScreen(OAUTH_APPS_MOCK_SCENARIOS.vercelDeveloper)-- await selectProjects([READ_ONLY_PROJECTS[0]])- authorize()-- expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()- })-})diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.test.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.test.tsxindex 25a48fee5ad..db45552951a 100644--- a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.test.tsx+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.test.tsx@@ -58,32 +58,21 @@ function toggleProjectOption(projectName: string) {}describe('OAuthAppsAuthorizeScreen', () => {- test('disables authorize and states the constraint while nothing is selected', async () => {+ test('requires at least one selected project before authorizing', async () => {renderScreen()expect(await screen.findByRole('button', { name: /Authorize Vercel/ })).toBeDisabled()expect(screen.getByText('Must select at least one project to authorize.')).toBeInTheDocument()- })-- test('enables authorize and drops the constraint once a project is selected', async () => {- renderScreen()-- await screen.findByRole('combobox')- selectProject('northwind-storefront')+ fireEvent.click(screen.getByRole('combobox'))+ toggleProjectOption('northwind-storefront')expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()expect(screen.queryByText('Must select at least one project to authorize.')).not.toBeInTheDocument()- })- test('re-disables authorize when the last project is deselected', async () => {- renderScreen()-- fireEvent.click(await screen.findByRole('combobox'))+ // Deselecting the last project re-disables ittoggleProjectOption('northwind-storefront')- toggleProjectOption('northwind-storefront')-expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeDisabled()expect(screen.getByText('Must select at least one project to authorize.')).toBeInTheDocument()})@@ -110,17 +99,6 @@ describe('OAuthAppsAuthorizeScreen', () => {).toBeInTheDocument()})- test('renders the success screen after the approve mutation resolves', async () => {- renderScreen()-- await screen.findByRole('combobox')- selectProject('northwind-storefront')- fireEvent.click(screen.getByRole('button', { name: /Authorize Vercel/ }))-- expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()- expect(screen.getByText('You can return to Vercel to continue')).toBeInTheDocument()- })-test('success screen shows exactly the submitted projects and scopes', async () => {renderScreen()@@ -128,10 +106,10 @@ describe('OAuthAppsAuthorizeScreen', () => {selectProject('northwind-cms')fireEvent.click(screen.getByRole('button', { name: /Authorize Vercel/ }))- await screen.findByText('Vercel is connected')+ expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()+ expect(screen.getByText('You can return to Vercel to continue')).toBeInTheDocument()expect(screen.getByText('northwind-cms')).toBeInTheDocument()- expect(screen.queryByText('northwind-storefront, northwind-cms')).not.toBeInTheDocument()expect(screen.queryByText('northwind-storefront')).not.toBeInTheDocument()expect(screen.getByText('Permissions granted')).toBeInTheDocument()@@ -155,7 +133,7 @@ describe('OAuthAppsAuthorizeScreen', () => {expect(screen.getByText(/admin@example\.com/)).toBeInTheDocument()})- test('tells the member an organization-bound grant is shared, exactly once', async () => {+ test('tells the member an organization-bound grant is shared, exactly once, without the member-bound copy', async () => {renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.kemalBot })expect(await screen.findAllByText('Want this scoped to one member?')).toHaveLength(1)@@ -165,52 +143,27 @@ describe('OAuthAppsAuthorizeScreen', () => {)).toHaveLength(1)expect(screen.queryByText(/This grant acts as you/)).not.toBeInTheDocument()- })-- test('keeps the no-admin-approval footer line for a member-bound grant', async () => {- renderScreen()-- expect(- await screen.findByText(/No admin approval is needed if your role permits this access/)- ).toBeInTheDocument()- })-- test('drops the no-admin-approval footer line for an organization-bound grant', async () => {- renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.kemalBot })-- await screen.findByText('Permissions requested')expect(screen.queryByText(/No admin approval is needed/)).not.toBeInTheDocument()expect(screen.getByText(/This authorization will appear in Authorized apps/)).toBeInTheDocument()})- test('shows no shared-grant messaging for a member-bound grant', async () => {+ test('shows the member-bound copy for a member-bound grant that picks projects', async () => {renderScreen()- await screen.findByText('Permissions requested')expect(- screen.queryByText('This grant is shared with the whole organization')- ).not.toBeInTheDocument()- expect(screen.queryByText(/This grant acts as you/)).toBeInTheDocument()- })-- test('says the grant covers future projects when there is no picker', async () => {- renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects })-- expect(await screen.findByText('All projects, including future ones')).toBeInTheDocument()- })-- test('does not claim future projects when the member picks them', async () => {- renderScreen()-- await screen.findByText('Permissions requested')+ await screen.findByText(/No admin approval is needed if your role permits this access/)+ ).toBeInTheDocument()+ expect(screen.getByText(/This grant acts as you/)).toBeInTheDocument()+ expect(screen.queryByText('Want this scoped to one member?')).not.toBeInTheDocument()expect(screen.queryByText('This grant covers every project')).not.toBeInTheDocument()})- test('authorizes an app that hides the picker, with nothing selected', async () => {+ test('authorizes an app that hides the picker, covering future projects', async () => {renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects })+ expect(await screen.findByText('All projects, including future ones')).toBeInTheDocument()expect(await enabledAuthorizeButton()).toBeEnabled()expect(screen.queryByRole('combobox')).not.toBeInTheDocument()expect(@@ -218,23 +171,15 @@ describe('OAuthAppsAuthorizeScreen', () => {).not.toBeInTheDocument()})- test('does not demand projects from an empty org when the app is org-wide', async () => {+ test('an org-wide app in an empty org authorizes and reports an all-projects grant', async () => {renderScreen({authId: OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects,organizationSlug: 'contoso-labs',})- expect(await enabledAuthorizeButton()).toBeEnabled()+ const authorizeButton = await enabledAuthorizeButton()expect(screen.queryByText(/No projects in/)).not.toBeInTheDocument()- })-- test('reports an all-projects grant as such rather than listing projects', async () => {- renderScreen({- authId: OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects,- organizationSlug: 'contoso-labs',- })-- fireEvent.click(await enabledAuthorizeButton())+ fireEvent.click(authorizeButton)expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()expect(screen.getByText('All projects, including ones created later')).toBeInTheDocument()@@ -248,21 +193,16 @@ describe('OAuthAppsAuthorizeScreen', () => {expect(screen.getAllByRole('option').length).toBeGreaterThan(MAX_SELECTED_PROJECTS)})- test('re-consent preselects the still-live projects from the existing grant', async () => {+ test('re-consent preselects and submits only the still-live projects from the existing grant', async () => {renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelReconsent })expect(await screen.findByText('tailspin-shop')).toBeInTheDocument()- expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()expect(screen.queryByText('Must select at least one project to authorize.')).not.toBeInTheDocument()- })-- test('re-consent submits only the still-live preselected projects', async () => {- renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelReconsent })-- await screen.findByText('tailspin-shop')- fireEvent.click(screen.getByRole('button', { name: /Authorize Vercel/ }))+ const authorizeButton = screen.getByRole('button', { name: /Authorize Vercel/ })+ expect(authorizeButton).toBeEnabled()+ fireEvent.click(authorizeButton)await screen.findByText('Vercel is connected')@@ -281,28 +221,18 @@ describe('OAuthAppsAuthorizeScreen', () => {expect(screen.getByText('Must select at least one project to authorize.')).toBeInTheDocument()})- test('offers the all-projects choice only when project scoping is optional', async () => {+ test('optional project scoping offers an all-projects choice that authorizes without a selection', async () => {renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelOptionalProjects })expect(await screen.findByText('All current and future projects')).toBeInTheDocument()- })-- test('choosing all projects enables authorize without a selection', async () => {- renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelOptionalProjects })-- expect(await screen.findByRole('button', { name: /Authorize Vercel/ })).toBeDisabled()+ expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeDisabled()fireEvent.click(screen.getByRole('checkbox'))- expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()expect(screen.queryByRole('combobox')).not.toBeInTheDocument()- })-- test('an all-projects approval reports the grant as all projects', async () => {- renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelOptionalProjects })-- fireEvent.click(await screen.findByRole('checkbox'))- fireEvent.click(screen.getByRole('button', { name: /Authorize Vercel/ }))+ const authorizeButton = screen.getByRole('button', { name: /Authorize Vercel/ })+ expect(authorizeButton).toBeEnabled()+ fireEvent.click(authorizeButton)expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()expect(screen.getByText('All projects, including ones created later')).toBeInTheDocument()@@ -315,11 +245,11 @@ describe('OAuthAppsAuthorizeScreen', () => {expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()})- test('a dynamic client renders the same required picker as an authored app', async () => {+ test('a dynamic client is unscoped, with no optional all-projects choice', async () => {renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.dynamicMcpClient })+ expect(await screen.findByText('All projects, including future ones')).toBeInTheDocument()expect(screen.queryByText('All current and future projects')).not.toBeInTheDocument()- expect(screen.queryByText(/registered automatically/)).not.toBeInTheDocument()})test('preselects the project named by the project_ref param', async () => {@@ -367,42 +297,106 @@ describe('OAuthAppsAuthorizeScreen', () => {expect(screen.getByRole('combobox')).not.toHaveTextContent('tailspin-warehouse')})- test('reconsent shows the permissions differences', async () => {+ test('reconsent shows the permissions differences, with previous permissions collapsed', async () => {renderScreen({authId: OAUTH_APPS_MOCK_SCENARIOS.vercelReconsent,})await screen.findByText('Already granted (2)')- await screen.findByText((_, element) => element?.textContent == 'Environment (New)', {- selector: 'span',- })- await screen.findByText(- (_, element) => element?.textContent == 'Analytics (Upgraded from Read)',- { selector: 'span' }- )- await screen.findByText(- (_, element) => element?.textContent == 'Secrets (Demoted from Read-write)',- { selector: 'span' }- )- await screen.findByText((_, element) => element?.textContent == 'Edge Functions (New)', {- selector: 'span',- })- await screen.findByText((_, element) => element?.textContent == 'Storage (New)', {- selector: 'span',- })- await screen.findByText((_, element) => element?.textContent == 'Rest (Read)', {- selector: 'span',- })+ const findSpanWithText = (text: string) =>+ screen.findByText((_, element) => element?.textContent == text, { selector: 'span' })+ await findSpanWithText('Environment (New)')+ await findSpanWithText('Analytics (Upgraded from Read)')+ await findSpanWithText('Secrets (Demoted from Read-write)')+ await findSpanWithText('Edge Functions (New)')+ await findSpanWithText('Storage (New)')+ await findSpanWithText('Rest (Read)')++ expect(screen.queryByText('Database')).toBeNull()+ fireEvent.click(screen.getByText('Already granted (2)'))+ await screen.findByText('Database')+ })+})++describe('OAuthAppsAuthorizeScreen post-submit role validation', () => {+ const READ_ONLY_PROJECTS = ['fabrikam-api', 'fabrikam-jobs']+ const WRITABLE_PROJECT = 'northwind-cms'++ const selectProjects = async (names: string[]) => {+ fireEvent.click(await screen.findByRole('combobox'))+ names.forEach((name) => fireEvent.click(screen.getByText(name)))+ }++ const authorize = () => fireEvent.click(screen.getByRole('button', { name: /Authorize Vercel/ }))++ const deselectFlagged = () =>+ fireEvent.click(screen.getByRole('button', { name: 'Deselect 2 projects' }))++ const submitTwoBlockedAndOneAllowed = async () => {+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation })+ await selectProjects([...READ_ONLY_PROJECTS, WRITABLE_PROJECT])+ authorize()+ return screen.findByText("Couldn't authorize 2 projects")+ }++ test('flags the projects the role cannot grant after submit', async () => {+ expect(await submitTwoBlockedAndOneAllowed()).toBeInTheDocument()+ expect(+ screen.getByText(+ 'Vercel needs write access but your role is read-only on the projects highlighted. Deselect them to continue.'+ )+ ).toBeInTheDocument()+ // Counted against the submitted selection+ expect(screen.getByText(/2 of 3\s+projects unavailable/)).toBeInTheDocument()+ // The primary action turns into the deselect shortcut, replacing the inline link+ expect(screen.getByRole('button', { name: 'Deselect 2 projects' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: /Authorize Vercel/ })).not.toBeInTheDocument()+ expect(screen.queryByText('Deselect projects')).not.toBeInTheDocument()+ // The rejected projects are marked in the dropdown+ expect(screen.getAllByText('- Unavailable')).toHaveLength(READ_ONLY_PROJECTS.length)+ })++ test('deselecting the blocked projects clears the failure treatment and the retry succeeds', async () => {+ await submitTwoBlockedAndOneAllowed()++ deselectFlagged()++ expect(screen.queryByText("Couldn't authorize 2 projects")).not.toBeInTheDocument()+ expect(screen.queryByText(/projects unavailable/)).not.toBeInTheDocument()+ // The dropdown marks outlive the deselection+ expect(screen.getAllByText('- Unavailable')).toHaveLength(READ_ONLY_PROJECTS.length)++ authorize()+ expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()})- test('reconsent shows the previous permissions hidden by default', async () => {+ test('a selection of only writable projects never triggers validation', async () => {+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation })++ await selectProjects([WRITABLE_PROJECT])+ authorize()++ expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()+ })++ test('a preselected read-only project still produces the post-submit banner', async () => {renderScreen({- authId: OAUTH_APPS_MOCK_SCENARIOS.vercelReconsent,+ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation,+ projectRef: 'fabrikamapi1',})- await screen.findByText('Already granted (2)')- expect(screen.queryByText('Database')).toBeNull()- fireEvent.click(await screen.findByText('Already granted (2)'))- await screen.findByText('Database')+ await screen.findByText('fabrikam-api')+ authorize()++ expect(await screen.findByText("Couldn't authorize 1 project")).toBeInTheDocument()+ })++ test('a request outside the role-validated set approves read-only projects', async () => {+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelDeveloper })++ await selectProjects([READ_ONLY_PROJECTS[0]])+ authorize()++ expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()})})diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ProjectMultiSelect.test.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ProjectMultiSelect.test.tsxindex b82302f29f3..43a8428fbca 100644--- a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ProjectMultiSelect.test.tsx+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ProjectMultiSelect.test.tsx@@ -29,6 +29,10 @@ describe('ProjectMultiSelect', () => {customRender(<ProjectMultiSelect projects={PROJECTS} selectedRefs={[]} onChange={vi.fn()} />)expect(screen.getByRole('combobox')).toHaveTextContent('Select projects...')+ expect(+ screen.queryByText('Must select at least one project to authorize.')+ ).not.toBeInTheDocument()+ expect(screen.queryByText('0/10')).not.toBeInTheDocument()})test('renders a single selected project by name in the trigger', () => {@@ -92,14 +96,6 @@ describe('ProjectMultiSelect', () => {expect(onChange).toHaveBeenCalledWith([])})- test('does not render an error message by default', () => {- customRender(<ProjectMultiSelect projects={PROJECTS} selectedRefs={[]} onChange={vi.fn()} />)-- expect(- screen.queryByText('Must select at least one project to authorize.')- ).not.toBeInTheDocument()- })-test('renders the error message when the error prop is set', () => {customRender(<ProjectMultiSelect@@ -111,6 +107,7 @@ describe('ProjectMultiSelect', () => {)expect(screen.getByText('Must select at least one project to authorize.')).toBeInTheDocument()+ expect(screen.queryByText(CAP_HELPER_TEXT)).not.toBeInTheDocument()})test('search filters the visible project rows', () => {@@ -136,27 +133,23 @@ describe('ProjectMultiSelect', () => {expect(screen.queryByText(/select all/i)).not.toBeInTheDocument()})- test('hides the counter until something is selected', () => {- customRender(<ProjectMultiSelect projects={PROJECTS} selectedRefs={[]} onChange={vi.fn()} />)-- expect(screen.queryByText('0/10')).not.toBeInTheDocument()- })-- test('hides the counter below eight selected', () => {- customRender(- <ProjectMultiSelect projects={MANY_PROJECTS} selectedRefs={refsUpTo(7)} onChange={vi.fn()} />- )-- expect(screen.queryByText('7/10')).not.toBeInTheDocument()- })-- test('shows the counter from eight selected onward', () => {- customRender(- <ProjectMultiSelect projects={MANY_PROJECTS} selectedRefs={refsUpTo(8)} onChange={vi.fn()} />- )-- expect(screen.getByText('8/10')).toBeInTheDocument()- })+ test.each([+ { count: 7, isCounterShown: false },+ { count: 8, isCounterShown: true },+ ])(+ 'shows the counter from eight selected onward ($count selected)',+ ({ count, isCounterShown }) => {+ customRender(+ <ProjectMultiSelect+ projects={MANY_PROJECTS}+ selectedRefs={refsUpTo(count)}+ onChange={vi.fn()}+ />+ )++ expect(screen.queryByText(`${count}/10`) !== null).toBe(isCounterShown)+ }+ )test('at nine selected the cap is not yet reached and a tenth can be added', () => {const onChange = vi.fn()@@ -226,18 +219,4 @@ describe('ProjectMultiSelect', () => {'true')})-- test('the required-selection error still renders at the cap boundary', () => {- customRender(- <ProjectMultiSelect- projects={PROJECTS}- selectedRefs={[]}- onChange={vi.fn()}- error="Must select at least one project to authorize."- />- )-- expect(screen.getByText('Must select at least one project to authorize.')).toBeInTheDocument()- expect(screen.queryByText(CAP_HELPER_TEXT)).not.toBeInTheDocument()- })})diff --git a/apps/studio/components/interfaces/Organization/Usage/UsageBranchFilter.test.tsx b/apps/studio/components/interfaces/Organization/Usage/UsageBranchFilter.test.tsxindex 09f6cb643d0..11ca6c523e0 100644--- a/apps/studio/components/interfaces/Organization/Usage/UsageBranchFilter.test.tsx+++ b/apps/studio/components/interfaces/Organization/Usage/UsageBranchFilter.test.tsx@@ -151,7 +151,8 @@ describe('UsageBranchFilter', () => {await user.click(screen.getByLabelText('Filter by branch'))const search = await screen.findByPlaceholderText('Find branch...')- await user.type(search, 'nonexistent-branch')+ await user.click(search)+ await user.paste('nonexistent-branch')expect(await screen.findByText('No branches found')).toBeInTheDocument()expect(screen.queryAllByRole('option')).toHaveLength(0)diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.test.tsx b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.test.tsxindex a7697289415..7e0130e1bae 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.test.tsx+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.test.tsx@@ -45,6 +45,15 @@ const renderEndpointSheet = (const submitForm = () =>fireEvent.submit(document.getElementById('platform-webhook-endpoint-form')!)+const fillInput = async (+ user: ReturnType<typeof userEvent.setup>,+ input: HTMLElement,+ value: string+) => {+ await user.click(input)+ await user.paste(value)+}+const getUrlInput = () => screen.getByPlaceholderText('https://api.example.com/webhooks/supabase')const findEventTypeCheckbox = (eventType: string) =>@@ -73,52 +82,24 @@ describe('PlatformWebhooksEndpointSheet', () => {expect(onSubmit).not.toHaveBeenCalled()})- it('blocks submit when the endpoint URL is malformed', async () => {- const user = userEvent.setup()- const { onSubmit } = renderEndpointSheet()-- await user.type(getUrlInput(), 'https://not a url')- await user.click(await findEventTypeCheckbox('project.updated'))- submitForm()-- expect(await screen.findByText('Please provide a valid URL')).toBeInTheDocument()- expect(onSubmit).not.toHaveBeenCalled()- })-- it('blocks submit when the endpoint URL uses an incomplete hostname', async () => {- const user = userEvent.setup()- const { onSubmit } = renderEndpointSheet()-- await user.type(getUrlInput(), 'https://webhook')- await user.click(await findEventTypeCheckbox('project.updated'))- submitForm()-- expect(await screen.findByText('Please provide a valid URL')).toBeInTheDocument()- expect(onSubmit).not.toHaveBeenCalled()- })-- it('blocks submit when the endpoint URL does not include a protocol', async () => {+ // URL parsing rules are covered in lib/validation/http-url.test.ts; this only checks the form+ // surfaces the sheet-specific messages.+ it.each([+ ['is malformed', 'https://not a url', 'Please provide a valid URL'],+ [+ 'has no protocol',+ 'hooks.example.com/billing',+ 'Please prefix your URL with http:// or https://',+ ],+ ])('blocks submit when the endpoint URL %s', async (_, url, message) => {const user = userEvent.setup()const { onSubmit } = renderEndpointSheet()- await user.type(getUrlInput(), 'hooks.example.com/billing')+ await fillInput(user, getUrlInput(), url)await user.click(await findEventTypeCheckbox('project.updated'))submitForm()- expect(- await screen.findByText('Please prefix your URL with http:// or https://')- ).toBeInTheDocument()- expect(onSubmit).not.toHaveBeenCalled()- })-- it('shows an error when no event types are selected', async () => {- const user = userEvent.setup()- const { onSubmit } = renderEndpointSheet()-- await user.type(getUrlInput(), 'https://hooks.example.com/billing')- submitForm()-- expect(await screen.findByText('Select at least one event type')).toBeInTheDocument()+ expect(await screen.findByText(message)).toBeInTheDocument()expect(onSubmit).not.toHaveBeenCalled()})@@ -126,7 +107,7 @@ describe('PlatformWebhooksEndpointSheet', () => {const user = userEvent.setup()const { onSubmit } = renderEndpointSheet()- await user.type(getUrlInput(), 'https://hooks.example.com/billing')+ await fillInput(user, getUrlInput(), 'https://hooks.example.com/billing')submitForm()expect(await screen.findByText('Select at least one event type')).toBeInTheDocument()@@ -139,13 +120,14 @@ describe('PlatformWebhooksEndpointSheet', () => {submitForm()- await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))- expect(onSubmit).toHaveBeenCalledWith(- expect.objectContaining({- url: 'https://hooks.example.com/billing',- eventTypes: ['project.updated'],- }),- expect.anything()+ await waitFor(() =>+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ url: 'https://hooks.example.com/billing',+ eventTypes: ['project.updated'],+ }),+ expect.anything()+ ))})@@ -153,18 +135,19 @@ describe('PlatformWebhooksEndpointSheet', () => {const user = userEvent.setup()const { onSubmit } = renderEndpointSheet()- await user.type(getUrlInput(), 'https://hooks.example.com/billing')+ await fillInput(user, getUrlInput(), 'https://hooks.example.com/billing')await user.click(screen.getByRole('checkbox', { name: /subscribe to all events/i }))submitForm()- await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))- expect(onSubmit).toHaveBeenCalledWith(- expect.objectContaining({- subscribeAll: true,- eventTypes: PROJECT_EVENT_TYPES,- url: 'https://hooks.example.com/billing',- }),- expect.anything()+ await waitFor(() =>+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ subscribeAll: true,+ eventTypes: PROJECT_EVENT_TYPES,+ url: 'https://hooks.example.com/billing',+ }),+ expect.anything()+ ))})@@ -176,16 +159,17 @@ describe('PlatformWebhooksEndpointSheet', () => {})await user.click(screen.getByRole('button', { name: 'Add header' }))- await user.type(screen.getByPlaceholderText('Header name'), 'X-Webhook-Secret')- await user.type(screen.getByPlaceholderText('Header value'), 'super-secret')+ await fillInput(user, screen.getByPlaceholderText('Header name'), 'X-Webhook-Secret')+ await fillInput(user, screen.getByPlaceholderText('Header value'), 'super-secret')submitForm()- await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))- expect(onSubmit).toHaveBeenCalledWith(- expect.objectContaining({- customHeaders: [{ key: 'X-Webhook-Secret', value: 'super-secret' }],- }),- expect.anything()+ await waitFor(() =>+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ customHeaders: [{ key: 'X-Webhook-Secret', value: 'super-secret' }],+ }),+ expect.anything()+ ))})@@ -197,7 +181,7 @@ describe('PlatformWebhooksEndpointSheet', () => {})await user.click(screen.getByRole('button', { name: 'Add header' }))- await user.type(screen.getByPlaceholderText('Header name'), 'X-Webhook-Secret')+ await fillInput(user, screen.getByPlaceholderText('Header name'), 'X-Webhook-Secret')submitForm()expect(await screen.findByText('Header value is required')).toBeInTheDocument()diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.test.tsx b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.test.tsxindex 31ce83c9e69..cd1e86f29c6 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.test.tsx+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.test.tsx@@ -162,7 +162,8 @@ describe('PlatformWebhooksPage (project scope)', () => {fireEvent.click(await screen.findByRole('button', { name: 'Create endpoint' }))const urlInput = await screen.findByPlaceholderText('https://api.example.com/webhooks/supabase')- await userEvent.type(urlInput, 'https://hooks.example.com/project')+ await userEvent.click(urlInput)+ await userEvent.paste('https://hooks.example.com/project')await userEvent.click(screen.getByRole('checkbox', { name: /subscribe to all events/i }))fireEvent.click(screen.getByRole('button', { name: 'Create endpoint' }))@@ -207,7 +208,7 @@ describe('PlatformWebhooksPage (project scope)', () => {fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))const urlInput = await screen.findByDisplayValue(ENDPOINT_ATTRIBUTES.url)await userEvent.clear(urlInput)- await userEvent.type(urlInput, updatedUrl)+ await userEvent.paste(updatedUrl)fireEvent.click(await screen.findByRole('button', { name: 'Save changes' }))await waitFor(() => expect(requests).toHaveLength(1))diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.test.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.test.tsindex 0f9d125bdd5..cc11cfa7b60 100644--- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.test.ts+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.test.ts@@ -1,11 +1,6 @@import { AWS_REGIONS } from 'shared-data'import { describe, expect, it } from 'vitest'-import {- HIGH_AVAILABILITY_INSTANCE_SIZE,- HIGH_AVAILABILITY_POSTGRES_ENGINE,- HIGH_AVAILABILITY_RELEASE_CHANNEL,-} from './ProjectCreation.constants'import type { AvailableRegions } from './ProjectCreation.utils'import {AUTO_REGION_VALUE,@@ -140,12 +135,6 @@ describe('getAvailableRegions', () => {})describe('High Availability project creation constraints', () => {- it('pins the Alpha Postgres engine, release channel, and compute size', () => {- expect(HIGH_AVAILABILITY_POSTGRES_ENGINE).toBe('17')- expect(HIGH_AVAILABILITY_RELEASE_CHANNEL).toBe('ga')- expect(HIGH_AVAILABILITY_INSTANCE_SIZE).toBe('large')- })-it.each([['local', 'eu-central-1'],['staging', 'us-east-1'],@@ -206,16 +195,6 @@ describe('getFreeTierGeneralRegionExperimentVariant', () => {getFreeTierGeneralRegionExperimentVariant({ ...base, enrollmentFlag: false })).toBeUndefined()})-- it('returns undefined when the enrollment flag is off even if the selection flag is on', () => {- expect(- getFreeTierGeneralRegionExperimentVariant({- ...base,- enrollmentFlag: false,- selectionFlag: true,- })- ).toBeUndefined()- })})describe('getRegionSelectionType', () => {diff --git a/apps/studio/components/interfaces/ProjectCreation/RegionSelector.utils.test.ts b/apps/studio/components/interfaces/ProjectCreation/RegionSelector.utils.test.tsindex d3c71228949..74768395bf5 100644--- a/apps/studio/components/interfaces/ProjectCreation/RegionSelector.utils.test.ts+++ b/apps/studio/components/interfaces/ProjectCreation/RegionSelector.utils.test.ts@@ -85,9 +85,6 @@ describe('resolveRegionRestriction', () => {describe('getRegionRestrictionCopy', () => {it('uses the capacity copy for a capacity status', () => {expect(getRegionRestrictionCopy('capacity')).toBe(REGION_RESTRICTION_COPY.capacity)- expect(getRegionRestrictionCopy('capacity').tooltip).toBe(- 'Temporarily unavailable due to this region being at capacity.'- )})it.each(['other', 'unavailable', 'brand_new', 'toString'])(diff --git a/apps/studio/components/interfaces/ProjectHome/ChartDataTransform.utils.test.ts b/apps/studio/components/interfaces/ProjectHome/ChartDataTransform.utils.test.tsindex 3f7dbffdc38..c44295494b8 100644--- a/apps/studio/components/interfaces/ProjectHome/ChartDataTransform.utils.test.ts+++ b/apps/studio/components/interfaces/ProjectHome/ChartDataTransform.utils.test.ts@@ -7,25 +7,28 @@ import type { LogsBarChartDatum } from './ProjectUsage.metrics'describe('normalizeChartBuckets', () => {const now = dayjs('2024-01-28T12:00:00.000Z')- describe('1hr interval', () => {- it('should create exactly 30 buckets with 2-minute intervals', () => {- const result = normalizeChartBuckets([], '1hr', now.toDate())-- expect(result).toHaveLength(30)-- // Check first bucket- expect(result[0].timestamp).toBe(now.subtract(60, 'minute').toISOString())-- // Check last bucket- expect(result[29].timestamp).toBe(now.subtract(2, 'minute').toISOString())-- // Check all buckets are 2 minutes apart- for (let i = 0; i < result.length - 1; i++) {- const diff = dayjs(result[i + 1].timestamp).diff(dayjs(result[i].timestamp), 'minute')- expect(diff).toBe(2)- }- })+ it.each([+ ['1hr', 30, 2, 'minute'],+ ['1day', 24, 1, 'hour'],+ ['7day', 28, 6, 'hour'],+ ] as const)(+ 'creates %s buckets: %s empty buckets %s %s(s) apart, ending one step before now',+ (interval, count, step, unit) => {+ const result = normalizeChartBuckets([], interval, now.toDate())++ expect(result).toHaveLength(count)+ expect(result[0].timestamp).toBe(now.subtract(count * step, unit).toISOString())+ expect(result[count - 1].timestamp).toBe(now.subtract(step, unit).toISOString())+ result.forEach((bucket, i) => {+ expect(bucket).toMatchObject({ ok_count: 0, warning_count: 0, error_count: 0 })+ if (i > 0) {+ expect(dayjs(bucket.timestamp).diff(dayjs(result[i - 1].timestamp), unit)).toBe(step)+ }+ })+ }+ )+ describe('1hr interval', () => {it('should aggregate data points into correct 2-minute buckets', () => {const data: LogsBarChartDatum[] = [{@@ -63,38 +66,9 @@ describe('normalizeChartBuckets', () => {expect(bucket15.warning_count).toBe(2)expect(bucket15.error_count).toBe(0)})-- it('should return empty buckets when no data provided', () => {- const result = normalizeChartBuckets([], '1hr', now.toDate())-- expect(result).toHaveLength(30)- result.forEach((bucket) => {- expect(bucket.ok_count).toBe(0)- expect(bucket.warning_count).toBe(0)- expect(bucket.error_count).toBe(0)- })- })})describe('1day interval', () => {- it('should create exactly 24 buckets with 1-hour intervals', () => {- const result = normalizeChartBuckets([], '1day', now.toDate())-- expect(result).toHaveLength(24)-- // Check first bucket- expect(result[0].timestamp).toBe(now.subtract(24, 'hour').toISOString())-- // Check last bucket- expect(result[23].timestamp).toBe(now.subtract(1, 'hour').toISOString())-- // Check all buckets are 1 hour apart- for (let i = 0; i < result.length - 1; i++) {- const diff = dayjs(result[i + 1].timestamp).diff(dayjs(result[i].timestamp), 'hour')- expect(diff).toBe(1)- }- })-it('should aggregate multiple data points into hourly buckets', () => {const data: LogsBarChartDatum[] = [{@@ -121,24 +95,6 @@ describe('normalizeChartBuckets', () => {})describe('7day interval', () => {- it('should create exactly 28 buckets with 6-hour intervals', () => {- const result = normalizeChartBuckets([], '7day', now.toDate())-- expect(result).toHaveLength(28)-- // Check first bucket (7 days = 168 hours ago)- expect(result[0].timestamp).toBe(now.subtract(168, 'hour').toISOString())-- // Check last bucket- expect(result[27].timestamp).toBe(now.subtract(6, 'hour').toISOString())-- // Check all buckets are 6 hours apart- for (let i = 0; i < result.length - 1; i++) {- const diff = dayjs(result[i + 1].timestamp).diff(dayjs(result[i].timestamp), 'hour')- expect(diff).toBe(6)- }- })-it('should aggregate data points into 6-hour buckets', () => {const data: LogsBarChartDatum[] = [{diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.utils.test.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.utils.test.tsindex 998f5cb5fc7..3c117836ed0 100644--- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.utils.test.ts+++ b/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.utils.test.ts@@ -17,14 +17,7 @@ describe('isTimeMetric', () => {})describe('formatTime', () => {- it('formats a timestamp into a human-readable date string', () => {- const ts = new Date('2024-01-15T14:30:00Z').getTime()- const result = formatTime(ts)- expect(typeof result).toBe('string')- expect(result.length).toBeGreaterThan(0)- })-- it('includes the month and day', () => {+ it('formats a timestamp to include the month and day', () => {const ts = new Date('2024-06-01T10:00:00Z').getTime()const result = formatTime(ts)expect(result).toMatch(/Jun/)diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils.test.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils.test.tsindex 0867b8915cd..db6150dd263 100644--- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils.test.ts+++ b/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils.test.ts@@ -91,10 +91,6 @@ describe('getTableName', () => {expect(getTableName('TRUNCATE logs')).toBe('logs')})- it('strips schema prefix', () => {- expect(getTableName('SELECT * FROM public.users')).toBe('users')- })-it('strips quotes', () => {expect(getTableName('SELECT * FROM "my_table"')).toBe('my_table')})diff --git a/apps/studio/components/interfaces/QueryInsights/utils/supamonitor.utils.test.ts b/apps/studio/components/interfaces/QueryInsights/utils/supamonitor.utils.test.tsindex 243b67c4346..67360628520 100644--- a/apps/studio/components/interfaces/QueryInsights/utils/supamonitor.utils.test.ts+++ b/apps/studio/components/interfaces/QueryInsights/utils/supamonitor.utils.test.ts@@ -64,12 +64,6 @@ describe('parseSupamonitorLogs', () => {p95_plan_time: 4,})})-- it('handles multiple log entries', () => {- const raw = [makeSampleLog(), makeSampleLog({ query: safeSql`SELECT 2`, query_id: 2 })]- const result = parseSupamonitorLogs(raw)- expect(result).toHaveLength(2)- })})describe('transformLogsToChartData', () => {@@ -78,16 +72,11 @@ describe('transformLogsToChartData', () => {expect(transformLogsToChartData([])).toEqual([])})- it('filters out entries with no timestamp', () => {- const logs: ParsedLogEntry[] = [{ query: safeSql`SELECT 1`, calls: 5 }]- const result = transformLogsToChartData(logs)- expect(result).toEqual([])- })-- it('filters out entries with invalid timestamp', () => {- const logs: ParsedLogEntry[] = [{ timestamp: 'not-a-date', calls: 5 }]- const result = transformLogsToChartData(logs)- expect(result).toEqual([])+ it.each<[string, ParsedLogEntry]>([+ ['no', { query: safeSql`SELECT 1`, calls: 5 }],+ ['an invalid', { timestamp: 'not-a-date', calls: 5 }],+ ])('filters out entries with %s timestamp', (_, log) => {+ expect(transformLogsToChartData([log])).toEqual([])})it('transforms a valid log entry into a chart data point', () => {@@ -291,18 +280,4 @@ describe('aggregateLogsByQuery', () => {expect(result).toHaveLength(1)expect(result[0].mean_time).toBe(0)})-- it('sets static fields correctly', () => {- const logs: ParsedLogEntry[] = [- { query: safeSql`SELECT 1`, calls: 1, total_exec_time: 10, total_plan_time: 0 },- ]-- const result = aggregateLogsByQuery(logs)-- expect(result[0].rows_read).toBe(0)- expect(result[0].cache_hit_rate).toBe(0)- expect(result[0].index_advisor_result).toBeNull()- expect(result[0]._total_cache_hits).toBe(0)- expect(result[0]._total_cache_misses).toBe(0)- })})diff --git a/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.test.ts b/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.test.tsindex 3ab057de8f7..c041095b3ac 100644--- a/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.test.ts+++ b/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.test.ts@@ -106,48 +106,22 @@ describe('generateQueryPerformanceSql', () => {expect(result.sql).toContain('WHERE')})- it('does not include user-defined WHERE conditions when no filters set', () => {- const result = generateQueryPerformanceSql({ preset: 'mostFrequentlyInvoked' })- expect(result.whereSql).toBe('')- // The base SQL may still contain its own WHERE clause (e.g. statements.calls > 0)- // but the user-defined whereSql should be empty- })-- it('passes runIndexAdvisor and filterIndexAdvisor flags', () => {- const resultWithAdvisor = generateQueryPerformanceSql({- preset: 'mostFrequentlyInvoked',- runIndexAdvisor: true,- filterIndexAdvisor: true,- })- expect(resultWithAdvisor.sql).toBeDefined()- })-- it('works with different presets', () => {- const presets = [- 'mostFrequentlyInvoked',- 'mostTimeConsuming',- 'slowestExecutionTime',- 'queryHitRate',- 'unified',- ] as const-- for (const preset of presets) {- const result = generateQueryPerformanceSql({ preset })- expect(result.sql).toBeDefined()- }- })-- it('clamps page=0 to page=1 (no negative offset)', () => {- const result = generateQueryPerformanceSql({ preset: 'unified', page: 0, pageSize: 20 })+ it.each([+ 'mostFrequentlyInvoked',+ 'mostTimeConsuming',+ 'slowestExecutionTime',+ 'queryHitRate',+ 'unified',+ ] as const)('generates sql for the %s preset', (preset) => {+ expect(generateQueryPerformanceSql({ preset }).sql.length).toBeGreaterThan(0)+ })++ it.each([0, -5])('clamps page=%s to page=1 (no negative offset)', (page) => {+ const result = generateQueryPerformanceSql({ preset: 'unified', page, pageSize: 20 })expect(result.sql).toContain('offset 0')expect(result.sql).not.toMatch(/offset -\d/)})- it('clamps negative page to page=1', () => {- const result = generateQueryPerformanceSql({ preset: 'unified', page: -5, pageSize: 20 })- expect(result.sql).toContain('offset 0')- })-it('clamps pageSize above 100 to 100', () => {const result = generateQueryPerformanceSql({ preset: 'unified', page: 1, pageSize: 9999 })expect(result.sql).toContain('limit 100')@@ -173,14 +147,6 @@ describe('generateQueryPerformanceSql', () => {})describe('generateQueryPerformanceSql - ORDER BY column validation', () => {- it('rejects invalid orderBy column containing colon (old URL format)', () => {- const result = generateQueryPerformanceSql({- preset: 'mostFrequentlyInvoked',- orderBy: { column: 'created_at:asc' as any, order: 'desc' },- })- expect(result.orderBySql).toBeUndefined()- })-it('rejects SQL injection in orderBy column', () => {const result = generateQueryPerformanceSql({preset: 'mostFrequentlyInvoked',@@ -190,11 +156,12 @@ describe('generateQueryPerformanceSql - ORDER BY column validation', () => {expect(result.sql).not.toContain('DROP TABLE')})- it('falls back to default ORDER BY when column is invalid', () => {+ it('rejects an orderBy column containing a colon (old URL format) and falls back to the default', () => {const result = generateQueryPerformanceSql({preset: 'mostFrequentlyInvoked',orderBy: { column: 'created_at:asc' as any, order: 'asc' },})+ expect(result.orderBySql).toBeUndefined()expect(result.sql).toContain('order by statements.calls desc')})diff --git a/apps/studio/components/interfaces/Realtime/Inspector/MessagesFormatters.test.ts b/apps/studio/components/interfaces/Realtime/Inspector/MessagesFormatters.test.tsindex a27e18a8214..bc5b8020fa9 100644--- a/apps/studio/components/interfaces/Realtime/Inspector/MessagesFormatters.test.ts+++ b/apps/studio/components/interfaces/Realtime/Inspector/MessagesFormatters.test.ts@@ -18,12 +18,6 @@ describe('isBinaryPayload', () => {expect(isBinaryPayload(new DataView(new ArrayBuffer(4)))).toBe(true)})- it('returns true for a TypedArray view with non-zero byteOffset', () => {- const buffer = new ArrayBuffer(8)- const view = new Uint8Array(buffer, 2, 4)- expect(isBinaryPayload(view)).toBe(true)- })-it('returns false for nullish values', () => {expect(isBinaryPayload(null)).toBe(false)expect(isBinaryPayload(undefined)).toBe(false)@@ -67,17 +61,6 @@ describe('formatHexdump', () => {expect(formatHexdump(bytes)).toBe(`${row1}\n${row2}`)})- it('increments the offset column on later rows', () => {- const bytes = new Uint8Array(32)- bytes.fill(0x41, 0, 16) // 'A' × 16- bytes.fill(0x42, 16, 32) // 'B' × 16-- const secondRow = formatHexdump(bytes).split('\n')[1]- const expected =- '00000010 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 |BBBBBBBBBBBBBBBB|'- expect(secondRow).toBe(expected)- })-it('replaces non-printable bytes with "." in the ASCII gutter, leaving printable bytes (including space and ~) intact', () => {// Boundary mix: 0x00 (null) and 0x1f (just below printable) → dot;// 0x20 (space) and 0x7e (~) → printable (lowest/highest);diff --git a/apps/studio/components/interfaces/Realtime/RealtimeSettings.test.tsx b/apps/studio/components/interfaces/Realtime/RealtimeSettings.test.tsxindex fafa9e01a31..435416aa77a 100644--- a/apps/studio/components/interfaces/Realtime/RealtimeSettings.test.tsx+++ b/apps/studio/components/interfaces/Realtime/RealtimeSettings.test.tsx@@ -4,7 +4,6 @@ import type { components } from 'api-types'import { mockAnimationsApi } from 'jsdom-testing-mocks'import { HttpResponse } from 'msw'import { beforeEach, describe, expect, test, vi } from 'vitest'-import { z } from 'zod'import { RealtimeSettings } from './RealtimeSettings'import type { Entitlement, FeatureKey } from '@/data/entitlements/entitlements-query'@@ -56,7 +55,8 @@ vi.mock('@/lib/constants', async (importOriginal) => {const REALTIME_CONFIG = {connection_pool: 2,- postgres_changes_pool: 2,+ // Deliberately differs from REALTIME_DEFAULT_CONFIG so the fallback test can tell them apart+ postgres_changes_pool: 7,max_bytes_per_second: 100000,max_channels_per_client: 100,max_concurrent_users: 200,@@ -119,10 +119,13 @@ describe('RealtimeSettings', () => {})})- test('renders the fetched postgres changes pool value', async () => {+ test('renders the fetched postgres changes pool value without a suspension banner', async () => {customRender(<RealtimeSettings />)- expect(await screen.findByLabelText('Postgres Changes connection pool size')).toHaveValue(2)+ expect(await screen.findByLabelText('Postgres Changes connection pool size')).toHaveValue(7)+ expect(+ screen.queryByText('Supabase has suspended Realtime for this project')+ ).not.toBeInTheDocument()})test('falls back to the default postgres changes pool value when omitted', async () => {@@ -142,36 +145,6 @@ describe('RealtimeSettings', () => {expect(await screen.findByLabelText('Postgres Changes connection pool size')).toHaveValue(2)})- test('submits the postgres changes pool value when saving', async () => {- const updateBodySchema = z.object({ postgres_changes_pool: z.number() })-- const requests: z.infer<typeof updateBodySchema>[] = []- addAPIMock({- method: 'patch',- path: '/platform/projects/:ref/config/realtime',- response: async ({ request }) => {- requests.push(updateBodySchema.parse(await request.json()))- return new HttpResponse(null, { status: 204 })- },- })-- customRender(<RealtimeSettings />)-- const postgresChangesPoolInput = await screen.findByLabelText(- 'Postgres Changes connection pool size'- )- await userEvent.clear(postgresChangesPoolInput)- await userEvent.type(postgresChangesPoolInput, '5')-- fireEvent.click(screen.getByRole('button', { name: 'Save changes' }))-- const dialog = await screen.findByRole('dialog')- fireEvent.click(within(dialog).getByRole('button', { name: 'Save changes' }))-- await waitFor(() => expect(requests).toHaveLength(1))- expect(requests[0]).toMatchObject({ postgres_changes_pool: 5 })- })-test.each([{ value: '1', accepted: true },{ value: '20', accepted: true },@@ -289,13 +262,4 @@ describe('RealtimeSettings', () => {await screen.findByText('Supabase has suspended Realtime for this project')).toBeInTheDocument()})-- test('does not show a suspension banner when Realtime has not been admin-suspended', async () => {- customRender(<RealtimeSettings />)-- await screen.findByLabelText('Postgres Changes connection pool size')- expect(- screen.queryByText('Supabase has suspended Realtime for this project')- ).not.toBeInTheDocument()- })})diff --git a/apps/studio/components/interfaces/Reports/Reports.constants.test.ts b/apps/studio/components/interfaces/Reports/Reports.constants.test.tsindex e245070e63d..a7c40cd7cb6 100644--- a/apps/studio/components/interfaces/Reports/Reports.constants.test.ts+++ b/apps/studio/components/interfaces/Reports/Reports.constants.test.ts@@ -52,18 +52,6 @@ describe('generateRegexpWhereSafe', () => {)})- it('should handle numbers', () => {- const filters: ReportFilterItem[] = [- {- key: 'request.status_code',- value: 200,- compare: 'is',- },- ]- const result = generateRegexpWhereSafe(filters, true)- expect(result).toBe('WHERE `request`.`status_code` = 200')- })-it('should escape single quotes in string values', () => {const filters: ReportFilterItem[] = [{diff --git a/apps/studio/components/interfaces/Reports/Reports.queryPerformance.test.ts b/apps/studio/components/interfaces/Reports/Reports.queryPerformance.test.tsindex 48836556f2c..db0623f5a0c 100644--- a/apps/studio/components/interfaces/Reports/Reports.queryPerformance.test.ts+++ b/apps/studio/components/interfaces/Reports/Reports.queryPerformance.test.ts@@ -23,11 +23,6 @@ describe('QUERY_PERFORMANCE SQL queries', () => {const sql = queries[name].safeSql([], undefined, undefined)expect(sql).toContain('calls > 0')})-- it.each(queryNames)('%s still includes calls > 0 when user filters are provided', (name) => {- const sql = queries[name].safeSql([], "WHERE auth.rolname in ('postgres')", undefined)- expect(sql).toContain('calls > 0')- })})describe('WHERE clause composition with user filters', () => {diff --git a/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.test.tsx b/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.test.tsxindex 477a9229795..8de6109d4c1 100644--- a/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.test.tsx+++ b/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.test.tsx@@ -60,6 +60,11 @@ const mockUpsert = () => {const getNameInput = () => screen.getByLabelText('Name')+const enterName = async (name: string) => {+ await userEvent.clear(getNameInput())+ await userEvent.paste(name)+}+describe('RenameQueryModal', () => {test('submits the new name for the selected snippet', async () => {mockOpenAIKeyCheck()@@ -70,8 +75,7 @@ describe('RenameQueryModal', () => {<RenameQueryModal snippet={SNIPPET_A} visible onCancel={vi.fn()} onComplete={onComplete} />)- await userEvent.clear(getNameInput())- await userEvent.type(getNameInput(), 'Renamed query')+ await enterName('Renamed query')fireEvent.click(screen.getByRole('button', { name: 'Rename query' }))await waitFor(() => expect(onComplete).toHaveBeenCalledOnce())@@ -87,8 +91,7 @@ describe('RenameQueryModal', () => {<RenameQueryModal snippet={SNIPPET_A} visible onCancel={vi.fn()} onComplete={onComplete} />)- await userEvent.clear(getNameInput())- await userEvent.type(getNameInput(), 'Renamed query')+ await enterName('Renamed query')fireEvent.click(screen.getByRole('button', { name: 'Rename query' }))await waitFor(() => expect(onComplete).toHaveBeenCalledOnce())@@ -119,8 +122,7 @@ describe('RenameQueryModal', () => {<RenameQueryModal snippet={UNTITLED_A} visible onCancel={vi.fn()} onComplete={onComplete} />)- await userEvent.clear(getNameInput())- await userEvent.type(getNameInput(), 'Renamed query')+ await enterName('Renamed query')fireEvent.click(screen.getByRole('button', { name: 'Rename query' }))await waitFor(() => expect(onComplete).toHaveBeenCalledOnce())@@ -140,8 +142,7 @@ describe('RenameQueryModal', () => {await waitFor(() => expect(getNameInput()).toHaveValue('Untitled query'))- await userEvent.clear(getNameInput())- await userEvent.type(getNameInput(), 'Second renamed query')+ await enterName('Second renamed query')fireEvent.click(screen.getByRole('button', { name: 'Rename query' }))await waitFor(() => expect(onComplete).toHaveBeenCalledTimes(2))@@ -159,8 +160,7 @@ describe('RenameQueryModal', () => {<RenameQueryModal snippet={SNIPPET_A} visible onCancel={onCancel} onComplete={vi.fn()} />)- await userEvent.clear(getNameInput())- await userEvent.type(getNameInput(), 'Half-typed name')+ await enterName('Half-typed name')await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))expect(onCancel).toHaveBeenCalledOnce()diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.tsindex f88a2558afb..6991424261d 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts@@ -48,50 +48,20 @@ const buildTrigger = (overrides: Partial<DatabaseEventTrigger> = {}): DatabaseEv})describe('SQLEditor.utils.ts:shouldAutoGenerateTitle', () => {- test('returns true when AI is enabled, the name is still the placeholder, and on platform', () => {- expect(- shouldAutoGenerateTitle({- aiOptInLevel: 'default',- snippetName: `${untitledSnippetTitle} 1`,- isPlatform: true,- })- ).toBe(true)- })- test('returns false when AI opt-in is disabled', () => {- expect(- shouldAutoGenerateTitle({- aiOptInLevel: 'disabled',- snippetName: `${untitledSnippetTitle} 1`,- isPlatform: true,- })- ).toBe(false)- })- test('returns false when the snippet already has a custom name', () => {- expect(- shouldAutoGenerateTitle({- aiOptInLevel: 'default',- snippetName: 'My saved query',- isPlatform: true,- })- ).toBe(false)- })- test('returns false when not running on the hosted platform', () => {- expect(- shouldAutoGenerateTitle({- aiOptInLevel: 'default',- snippetName: `${untitledSnippetTitle} 1`,- isPlatform: false,- })- ).toBe(false)- })- test('returns false when the snippet name is undefined', () => {- expect(- shouldAutoGenerateTitle({- aiOptInLevel: 'default',- snippetName: undefined,- isPlatform: true,- })- ).toBe(false)+ const base = {+ aiOptInLevel: 'default',+ snippetName: `${untitledSnippetTitle} 1`,+ isPlatform: true,+ } as const++ test.each([+ ['AI is enabled, the name is still the placeholder, and on platform', {}, true],+ ['AI opt-in is disabled', { aiOptInLevel: 'disabled' }, false],+ ['the snippet already has a custom name', { snippetName: 'My saved query' }, false],+ ['not running on the hosted platform', { isPlatform: false }, false],+ ['the snippet name is undefined', { snippetName: undefined }, false],+ ] as const)('when %s -> %s', (_, overrides, expected) => {+ expect(shouldAutoGenerateTitle({ ...base, ...overrides })).toBe(expected)})})@@ -99,107 +69,81 @@ describe('SQLEditor.utils.ts:buildExecuteParams', () => {const impersonatedRoleState = createRoleImpersonationState('default', {current: async () => ({}),})+ const base = {+ limit: 100,+ connectionString: 'postgresql://example',+ projectRef: 'default',+ impersonatedRoleState,+ }test('applies the auto-limit suffix when appropriate', () => {- const params = buildExecuteParams({- sql: safeSql`select * from countries`,- limit: 100,- connectionString: 'postgresql://example',- projectRef: 'default',- impersonatedRoleState,- })+ const params = buildExecuteParams({ ...base, sql: safeSql`select * from countries` })expect(params.sql).toBe('select * from countries limit 100;')expect(params.autoLimit).toBe(100)})test('leaves autoLimit undefined when a limit is already present', () => {- const params = buildExecuteParams({- sql: safeSql`select * from countries limit 10;`,- limit: 100,- connectionString: 'postgresql://example',- projectRef: 'default',- impersonatedRoleState,- })+ const params = buildExecuteParams({ ...base, sql: safeSql`select * from countries limit 10;` })expect(params.sql).toBe('select * from countries limit 10;')expect(params.autoLimit).toBeUndefined()})test('reflects isRoleImpersonationEnabled from the impersonation state', () => {- const params = buildExecuteParams({- sql: safeSql`select * from countries`,- limit: 0,- connectionString: 'postgresql://example',- projectRef: 'default',- impersonatedRoleState,- })+ const params = buildExecuteParams({ ...base, limit: 0, sql: safeSql`select * from countries` })expect(params.isRoleImpersonationEnabled).toBe(false)expect(params.isStatementTimeoutDisabled).toBe(true)expect(params.contextualInvalidation).toBe(true)})})+type SnippetsMap = Record<string, { snippet: { content?: unknown } }>+describe('SQLEditor.utils.ts:deriveSnippetIdentity', () => {- test('uses the generated id when there is no url id, loading reflects the snippets map like any other id', () => {- const result = deriveSnippetIdentity({- urlId: undefined,- generatedId: 'generated-id',- snippets: {},- })- expect(result).toEqual({ id: 'generated-id', isLoading: true })- })- test('uses the generated id and is not loading once it appears in the snippets map', () => {- const result = deriveSnippetIdentity({- urlId: undefined,- generatedId: 'generated-id',- snippets: { 'generated-id': { snippet: { content: { some: 'content' } } } },- })- expect(result).toEqual({ id: 'generated-id', isLoading: false })- })- test('uses the generated id and is never loading when the url id is "new"', () => {- const result = deriveSnippetIdentity({- urlId: 'new',- generatedId: 'generated-id',- snippets: { 'generated-id': { snippet: { content: undefined } } },- })- expect(result).toEqual({ id: 'generated-id', isLoading: false })- })- test('uses the url id and is loading when the snippet is not yet in the store', () => {- const result = deriveSnippetIdentity({- urlId: 'existing-id',- generatedId: 'generated-id',- snippets: {},- })- expect(result).toEqual({ id: 'existing-id', isLoading: true })- })- test('uses the url id and is loading when the snippet has no content yet', () => {- const result = deriveSnippetIdentity({- urlId: 'existing-id',- generatedId: 'generated-id',- snippets: { 'existing-id': { snippet: { content: undefined } } },- })- expect(result).toEqual({ id: 'existing-id', isLoading: true })- })- test('uses the url id and is not loading once the snippet content has arrived', () => {- const result = deriveSnippetIdentity({- urlId: 'existing-id',- generatedId: 'generated-id',- snippets: { 'existing-id': { snippet: { content: { some: 'content' } } } },- })- expect(result).toEqual({ id: 'existing-id', isLoading: false })- })- test('is loading when the snippets map itself is missing', () => {- const result = deriveSnippetIdentity({- urlId: 'existing-id',- generatedId: 'generated-id',- snippets: undefined as unknown as Record<string, { snippet: { content?: unknown } }>,- })- expect(result).toEqual({ id: 'existing-id', isLoading: true })- })- test('is loading when the snippets entry has no snippet on it', () => {- const result = deriveSnippetIdentity({- urlId: 'existing-id',- generatedId: 'generated-id',- snippets: { 'existing-id': {} as { snippet: { content?: unknown } } },- })- expect(result).toEqual({ id: 'existing-id', isLoading: true })+ const loaded = { snippet: { content: { some: 'content' } } }+ const noContent = { snippet: { content: undefined } }++ test.each<+ [string, string | undefined, SnippetsMap | undefined, { id: string; isLoading: boolean }]+ >([+ ['no url id, generated id not in map', undefined, {}, { id: 'generated-id', isLoading: true }],+ [+ 'no url id, generated id in map',+ undefined,+ { 'generated-id': loaded },+ { id: 'generated-id', isLoading: false },+ ],+ [+ 'url id "new" is never loading',+ 'new',+ { 'generated-id': noContent },+ { id: 'generated-id', isLoading: false },+ ],+ ['url id not yet in the store', 'existing-id', {}, { id: 'existing-id', isLoading: true }],+ [+ 'url id with no content yet',+ 'existing-id',+ { 'existing-id': noContent },+ { id: 'existing-id', isLoading: true },+ ],+ [+ 'url id with content',+ 'existing-id',+ { 'existing-id': loaded },+ { id: 'existing-id', isLoading: false },+ ],+ ['snippets map missing', 'existing-id', undefined, { id: 'existing-id', isLoading: true }],+ [+ 'entry has no snippet',+ 'existing-id',+ { 'existing-id': {} as SnippetsMap[string] },+ { id: 'existing-id', isLoading: true },+ ],+ ])('%s', (_, urlId, snippets, expected) => {+ expect(+ deriveSnippetIdentity({+ urlId,+ generatedId: 'generated-id',+ snippets: snippets as SnippetsMap,+ })+ ).toEqual(expected)})})@@ -216,27 +160,20 @@ describe('SQLEditor.utils.ts:extractDebugContext', () => {errorMessage: 'relation does not exist',})})- test('falls back to an empty sql when the snippet is undefined', () => {- expect(extractDebugContext(undefined, { error: { message: 'boom' } })).toEqual({+ test.each([+ ['the snippet is undefined', undefined],+ ['the snippet has no content yet', { snippet: { content: undefined } }],+ ])('falls back to an empty sql when %s', (_, snippet) => {+ expect(extractDebugContext(snippet, { error: { message: 'boom' } })).toEqual({sql: '',errorMessage: 'boom',})})- test('falls back to an empty sql when the snippet has no content yet', () => {- expect(- extractDebugContext({ snippet: { content: undefined } }, { error: { message: 'boom' } })- ).toEqual({ sql: '', errorMessage: 'boom' })- })- test('falls back to "Unknown error" when the result is undefined', () => {- const snippet = buildDebugSnippet('select 1;')- expect(extractDebugContext(snippet, undefined)).toEqual({- sql: 'select 1;',- errorMessage: 'Unknown error',- })- })- test('falls back to "Unknown error" when the result has no error message', () => {- const snippet = buildDebugSnippet('select 1;')- expect(extractDebugContext(snippet, {})).toEqual({+ test.each([+ ['the result is undefined', undefined],+ ['the result has no error message', {}],+ ])('falls back to "Unknown error" when %s', (_, result) => {+ expect(extractDebugContext(buildDebugSnippet('select 1;'), result)).toEqual({sql: 'select 1;',errorMessage: 'Unknown error',})@@ -260,63 +197,37 @@ describe('SQLEditor.utils.ts:buildDebugChatArgs', () => {test('attaches the query with its source and names the dialect', () => {const snippet = buildDebugSnippet('select count(*) from logs;')const result = { error: { message: 'Unknown expression identifier' } }- expect(buildDebugChatArgs(snippet, result, 'logs').sqlSnippets).toEqual([+ const args = buildDebugChatArgs(snippet, result, 'logs')+ expect(args.sqlSnippets).toEqual([{ label: 'Current Query', content: 'select count(*) from logs;', source: 'logs' },])- expect(buildDebugChatArgs(snippet, result, 'logs').initialInput).toEqual(- 'Help me to debug the attached sql snippet which gives the following error: \n\nUnknown expression identifier\n\nThis query runs against the Supabase logs table on a ClickHouse-backed engine, not Postgres.'- )+ expect(args.initialInput).toContain('Unknown expression identifier')+ expect(args.initialInput).toContain('ClickHouse')+ expect(args.initialInput).toContain('not Postgres')})})describe('SQLEditor.utils.ts:buildCompletionRequestBody', () => {- test('builds the base request body with no extra options', () => {- expect(- buildCompletionRequestBody({- projectRef: 'default',- connectionString: 'postgresql://example',- orgSlug: 'acme',- })- ).toEqual({- projectRef: 'default',- connectionString: 'postgresql://example',- language: 'sql',- orgSlug: 'acme',- })- })- test('merges options on top of the base fields', () => {+ const base = { projectRef: 'default', connectionString: 'postgresql://example', orgSlug: 'acme' }++ test('builds the base request body and merges options on top', () => {+ expect(buildCompletionRequestBody(base)).toEqual({ ...base, language: 'sql' })expect(buildCompletionRequestBody({- projectRef: 'default',- connectionString: 'postgresql://example',- orgSlug: 'acme',+ ...base,options: { completionMetadata: { prompt: 'add a where clause' } },})).toEqual({- projectRef: 'default',- connectionString: 'postgresql://example',+ ...base,language: 'sql',- orgSlug: 'acme',completionMetadata: { prompt: 'add a where clause' },})})test('omits dialect when not provided, so the route keeps its Postgres default', () => {- const body = buildCompletionRequestBody({- projectRef: 'default',- connectionString: null,- orgSlug: 'acme',- })- expect(body).not.toHaveProperty('dialect')- })- test('includes the dialect when provided', () => {- expect(- buildCompletionRequestBody({- projectRef: 'default',- connectionString: null,- orgSlug: 'acme',- dialect: 'clickhouse',- }).dialect- ).toBe('clickhouse')+ expect(buildCompletionRequestBody(base)).not.toHaveProperty('dialect')+ expect(buildCompletionRequestBody({ ...base, dialect: 'clickhouse' }).dialect).toBe(+ 'clickhouse'+ )})})@@ -330,29 +241,16 @@ describe('SQLEditor.utils.ts:sqlSourceToDialect', () => {describe('SQLEditor.utils.ts:createSqlSnippetSkeletonV2', () => {const baseArgs = { name: 'Untitled', sql: 'select 1', owner_id: 1, project_id: 1 }- test('defaults to a database (sql) snippet', () => {- const snippet = createSqlSnippetSkeletonV2(baseArgs)- expect(snippet.type).toBe('sql')- expect(snippet.content?.unchecked_sql).toBe('select 1')+ test.each([+ ['defaults to a database (sql) snippet', undefined, 'sql'],+ ['builds a database snippet for source "database"', 'database', 'sql'],+ ['builds a logs (log_sql) snippet for source "logs"', 'logs', 'log_sql'],+ ] as const)('%s', (_, source, type) => {+ const snippet = createSqlSnippetSkeletonV2({ ...baseArgs, source, idOverride: 'snippet-id' })+ expect(snippet.type).toBe(type)expect(snippet.status).toBe('new')- })-- test('builds a database snippet when source is explicitly "database"', () => {- const snippet = createSqlSnippetSkeletonV2({ ...baseArgs, source: 'database' })- expect(snippet.type).toBe('sql')- })-- test('builds a logs (log_sql) snippet when source is "logs"', () => {- const snippet = createSqlSnippetSkeletonV2({ ...baseArgs, source: 'logs' })- expect(snippet.type).toBe('log_sql')expect(snippet.content?.unchecked_sql).toBe('select 1')- })-- test('sets content_id to the snippet id for both sources', () => {- const db = createSqlSnippetSkeletonV2({ ...baseArgs, idOverride: 'db-id' })- const logs = createSqlSnippetSkeletonV2({ ...baseArgs, idOverride: 'logs-id', source: 'logs' })- expect(db.content?.content_id).toBe('db-id')- expect(logs.content?.content_id).toBe('logs-id')+ expect(snippet.content?.content_id).toBe('snippet-id')})})@@ -364,500 +262,203 @@ describe('SQLEditor.utils.ts:planDiffRequestApplication', () => {})expect(plan).toEqual({ kind: 'replace', text: 'select 1;' })})- test('opens a diff against the existing content when it is not empty', () => {- const plan = planDiffRequestApplication({- existingValue: 'select 0;',- request: { diffType: DiffType.Modification, sql: 'select 1;' },- })- expect(plan).toEqual({- kind: 'diff',- diff: { original: 'select 0;', modified: 'select 1;' },- diffType: DiffType.Modification,- })- })- test('carries through the requested diff type', () => {- const plan = planDiffRequestApplication({- existingValue: 'select 0;',- request: { diffType: DiffType.NewSnippet, sql: 'select 1;' },- })- expect(plan).toEqual({- kind: 'diff',- diff: { original: 'select 0;', modified: 'select 1;' },- diffType: DiffType.NewSnippet,- })- })-})--const keyEvent = (overrides: Partial<Pick<KeyboardEvent, 'key' | 'metaKey' | 'ctrlKey'>> = {}) => ({- key: 'a',- metaKey: false,- ctrlKey: false,- ...overrides,+ test.each([DiffType.Modification, DiffType.NewSnippet])(+ 'opens a %s diff against the existing content when it is not empty',+ (diffType) => {+ const plan = planDiffRequestApplication({+ existingValue: 'select 0;',+ request: { diffType, sql: 'select 1;' },+ })+ expect(plan).toEqual({+ kind: 'diff',+ diff: { original: 'select 0;', modified: 'select 1;' },+ diffType,+ })+ }+ )})describe('SQLEditor.utils.ts:resolveDiffKeyAction', () => {- test('does nothing when neither a diff nor the prompt is open', () => {- const action = resolveDiffKeyAction(keyEvent({ key: 'Escape' }), {- isDiffOpen: false,- isPromptOpen: false,- os: 'macos',- })- expect(action).toEqual({ type: 'none' })- })- test('does nothing for keys other than Enter/Escape', () => {- const action = resolveDiffKeyAction(keyEvent({ key: 'a' }), {- isDiffOpen: true,- isPromptOpen: false,- os: 'macos',- })- expect(action).toEqual({ type: 'none' })- })- test('accepts on Cmd+Enter on macOS when a diff is open', () => {- const action = resolveDiffKeyAction(keyEvent({ key: 'Enter', metaKey: true }), {- isDiffOpen: true,- isPromptOpen: false,- os: 'macos',- })- expect(action).toEqual({ type: 'accept' })- })- test('accepts on Ctrl+Enter on Windows when a diff is open', () => {- const action = resolveDiffKeyAction(keyEvent({ key: 'Enter', ctrlKey: true }), {- isDiffOpen: true,- isPromptOpen: false,- os: 'windows',- })- expect(action).toEqual({ type: 'accept' })- })- test('does not accept on Ctrl+Enter on macOS (wrong modifier for the OS)', () => {- const action = resolveDiffKeyAction(keyEvent({ key: 'Enter', ctrlKey: true }), {- isDiffOpen: true,- isPromptOpen: false,- os: 'macos',- })- expect(action).toEqual({ type: 'none' })- })- test('does not accept on Enter without the modifier key', () => {- const action = resolveDiffKeyAction(keyEvent({ key: 'Enter' }), {- isDiffOpen: true,- isPromptOpen: false,- os: 'macos',- })- expect(action).toEqual({ type: 'none' })- })- test('does not accept on Cmd+Enter when the diff is not open, even if the prompt is', () => {- const action = resolveDiffKeyAction(keyEvent({ key: 'Enter', metaKey: true }), {- isDiffOpen: false,- isPromptOpen: true,- os: 'macos',- })- expect(action).toEqual({ type: 'none' })- })- test('escapes with shouldDiscard true when a diff is open', () => {- const action = resolveDiffKeyAction(keyEvent({ key: 'Escape' }), {- isDiffOpen: true,- isPromptOpen: false,- os: 'macos',- })- expect(action).toEqual({ type: 'escape', shouldDiscard: true })- })- test('escapes with shouldDiscard false when only the prompt is open', () => {- const action = resolveDiffKeyAction(keyEvent({ key: 'Escape' }), {- isDiffOpen: false,- isPromptOpen: true,- os: 'macos',- })- expect(action).toEqual({ type: 'escape', shouldDiscard: false })+ type KeyEvent = Pick<KeyboardEvent, 'key' | 'metaKey' | 'ctrlKey'>+ type Ctx = Parameters<typeof resolveDiffKeyAction>[1]+ const diffOpen: Ctx = { isDiffOpen: true, isPromptOpen: false, os: 'macos' }+ const promptOpen: Ctx = { isDiffOpen: false, isPromptOpen: true, os: 'macos' }+ const key = (k: string, mods: Partial<KeyEvent> = {}): KeyEvent => ({+ key: k,+ metaKey: false,+ ctrlKey: false,+ ...mods,+ })++ test.each<[string, KeyEvent, Ctx, ReturnType<typeof resolveDiffKeyAction>]>([+ [+ 'nothing when neither a diff nor the prompt is open',+ key('Escape'),+ { ...diffOpen, isDiffOpen: false },+ { type: 'none' },+ ],+ ['nothing for keys other than Enter/Escape', key('a'), diffOpen, { type: 'none' }],+ ['accept on Cmd+Enter on macOS', key('Enter', { metaKey: true }), diffOpen, { type: 'accept' }],+ [+ 'accept on Ctrl+Enter on Windows',+ key('Enter', { ctrlKey: true }),+ { ...diffOpen, os: 'windows' },+ { type: 'accept' },+ ],+ [+ 'nothing on Ctrl+Enter on macOS (wrong modifier)',+ key('Enter', { ctrlKey: true }),+ diffOpen,+ { type: 'none' },+ ],+ ['nothing on Enter without a modifier', key('Enter'), diffOpen, { type: 'none' }],+ [+ 'nothing on Cmd+Enter when only the prompt is open',+ key('Enter', { metaKey: true }),+ promptOpen,+ { type: 'none' },+ ],+ [+ 'escape and discard when a diff is open',+ key('Escape'),+ diffOpen,+ { type: 'escape', shouldDiscard: true },+ ],+ [+ 'escape without discard when only the prompt is open',+ key('Escape'),+ promptOpen,+ { type: 'escape', shouldDiscard: false },+ ],+ ])('%s', (_, event, ctx, expected) => {+ expect(resolveDiffKeyAction(event, ctx)).toEqual(expected)})})-describe(`SQLEditor.utils.ts:checkDestructiveQuery`, () => {- it('drop statement matches', () => {- const match = checkDestructiveQuery('drop table films, distributors;')-- expect(match).toBe(true)- })-- it('truncate statement matches', () => {- const match = checkDestructiveQuery('truncate films;')-- expect(match).toBe(true)- })-- it('delete statement matches', () => {- const match = checkDestructiveQuery("delete from films where kind <> 'Musical';")-- expect(match).toBe(true)- })-- it('delete statement after another statement matches', () => {- const match = checkDestructiveQuery(stripIndent`- select * from films;-- delete from films where kind <> 'Musical';- `)-- expect(match).toBe(true)+describe('SQLEditor.utils.ts:checkDestructiveQuery', () => {+ const doBlock = (body: string) => `DO $$\nBEGIN\n ${body}\nEND\n$$;`++ test.each([+ 'drop table films, distributors;',+ 'truncate films;',+ "delete from films where kind <> 'Musical';",+ "DELETE FROM films WHERE kind <> 'Musical';",+ "select * from films;\n\ndelete from films where kind <> 'Musical';",+ "delete from countries; update countries set name = 'hello';",+ 'ALTER TABLE test DROP COLUMN test;',+ 'TRUNCATE TABLE test;',+ ])('flags plain destructive statement: %s', (sql) => {+ expect(checkDestructiveQuery(sql)).toBe(true)+ })++ test.each([+ // string literal / format / concatenation+ `EXECUTE 'DROP TABLE users';`,+ `EXECUTE 'DELETE FROM users';`,+ `EXECUTE 'TRUNCATE TABLE users';`,+ `EXECUTE format('DROP TABLE %I', table_name);`,+ `EXECUTE format('DELETE FROM %I', table_name);`,+ `EXECUTE format('TRUNCATE TABLE %I', table_name);`,+ `EXECUTE 'DROP TABLE ' || table_name;`,+ `EXECUTE 'DELETE FROM ' || table_name;`,+ `execute 'drop table users';`,+ `EXECUTE Format('DROP TABLE users');`,+ // EXECUTE IMMEDIATE / OPEN cursor / RETURN QUERY+ `EXECUTE IMMEDIATE 'DROP TABLE users';`,+ `EXECUTE IMMEDIATE 'DELETE FROM users';`,+ `EXECUTE IMMEDIATE 'TRUNCATE TABLE users';`,+ `OPEN ref FOR EXECUTE 'DROP TABLE users';`,+ `OPEN ref FOR EXECUTE format('DELETE FROM %I', tbl);`,+ `OPEN ref FOR EXECUTE 'TRUNCATE TABLE ' || tbl;`,+ `RETURN QUERY EXECUTE 'DROP TABLE users';`,+ `RETURN QUERY EXECUTE format('DELETE FROM %I', tbl);`,+ // dollar-quoted, concat, E-strings+ `EXECUTE $sql$DROP TABLE users$sql$;`,+ `EXECUTE $body$TRUNCATE TABLE logs$body$;`,+ `EXECUTE concat('DROP TABLE ', 'users');`,+ `EXECUTE concat_ws(' ', 'DELETE FROM', 'users');`,+ `EXECUTE E'DROP TABLE users';`,+ // ALTER TABLE ... DROP COLUMN through every dynamic form+ `EXECUTE 'ALTER TABLE users DROP COLUMN email';`,+ `EXECUTE format('ALTER TABLE %I DROP COLUMN %I', 'users', 'email');`,+ `EXECUTE IMMEDIATE 'ALTER TABLE users DROP COLUMN email';`,+ `OPEN ref FOR EXECUTE 'ALTER TABLE users DROP COLUMN email';`,+ `RETURN QUERY EXECUTE 'ALTER TABLE users DROP COLUMN email';`,+ `EXECUTE $sql$ALTER TABLE users DROP COLUMN email$sql$;`,+ `EXECUTE concat('ALTER TABLE ', 'users DROP COLUMN email');`,+ // DO blocks+ doBlock(`EXECUTE 'DROP TABLE users';`),+ doBlock(`EXECUTE 'ALTER TABLE users DROP COLUMN email';`),+ stripIndent`+ DO $$+ BEGIN+ FOR rec IN SELECT tablename FROM pg_tables WHERE schemaname = 'public' LOOP+ EXECUTE format('DROP TABLE %I', rec.tablename);+ END LOOP;+ END+ $$;+ `,+ stripIndent`+ DO $$+ DECLARE+ func_name text;+ BEGIN+ FOR func_name IN+ SELECT routine_name FROM information_schema.routines WHERE routine_schema = 'public'+ LOOP+ EXECUTE format('DROP FUNCTION %I', func_name);+ END LOOP;+ END+ $$;+ `,+ ])('flags destructive dynamic SQL: %s', (sql) => {+ expect(checkDestructiveQuery(sql)).toBe(true)})- it("rls policy containing delete doesn't match", () => {- const match = checkDestructiveQuery(stripIndent`+ test.each([+ stripIndent`create policy "Users can delete their own files"on storage.objects for delete to authenticated using (bucket id = 'files' and (select auth.uid()) = owner);- `)-- expect(match).toBe(false)- })-- it('capitalized statement matches', () => {- const match = checkDestructiveQuery("DELETE FROM films WHERE kind <> 'Musical';")-- expect(match).toBe(true)- })-- it("comment containing keyword doesn't match", () => {- const match = checkDestructiveQuery(stripIndent`- -- Going to drop this in here, might delete later- select * from films;- `)-- expect(match).toBe(false)+ `,+ '-- Going to drop this in here, might delete later\nselect * from films;',+ `EXECUTE 'SELECT * FROM users';`,+ `EXECUTE 'INSERT INTO users (name) VALUES (''test'')';`,+ `EXECUTE 'UPDATE users SET name = ''test'' WHERE id = 1';`,+ `EXECUTE 'ALTER TABLE users ADD COLUMN email text';`,+ `sql := 'SELECT * FROM users';`,+ `OPEN ref FOR EXECUTE 'SELECT * FROM users';`,+ `RETURN QUERY EXECUTE 'SELECT * FROM users';`,+ ])('does not flag: %s', (sql) => {+ expect(checkDestructiveQuery(sql)).toBe(false)})})-describe('SQLEditor.utils:updateWithoutWhere', () => {- it('contains an update query with a where clause', () => {- const match = isUpdateWithoutWhere(stripIndent`- UPDATE public.countries SET name = 'New Name' WHERE id = 1;- `)-- expect(match).toBe(false)- })-- it('contains an update query without a where clause', () => {- const match = isUpdateWithoutWhere(stripIndent`- UPDATE public.countries SET name = 'New Name';- `)-- expect(match).toBe(true)- })-- it('contains an update query, with quoted identifiers with a where clause', () => {- const match = isUpdateWithoutWhere(stripIndent`- UPDATE "public"."countries" SET name = 'New Name' WHERE id = 1;- `)-- expect(match).toBe(false)- })-- it('contains an update query, with quoted identifiers without a where clause', () => {- const match = isUpdateWithoutWhere(stripIndent`- UPDATE "public"."countries" SET name = 'New Name';- `)-- expect(match).toBe(true)- })-- it('catches update on a single quoted table name without a where clause', () => {- const match = isUpdateWithoutWhere(`UPDATE "messages" SET id = 1;`)- expect(match).toBe(true)- })-- it('does not flag update on a single quoted table name with a where clause', () => {- const match = isUpdateWithoutWhere(`UPDATE "messages" SET id = 1 WHERE id = 2;`)- expect(match).toBe(false)- })-- it('catches update on a quoted schema with a bareword table without a where clause', () => {- const match = isUpdateWithoutWhere(`UPDATE "public".messages SET id = 1;`)- expect(match).toBe(true)- })-- it('catches update on a bareword schema with a quoted table without a where clause', () => {- const match = isUpdateWithoutWhere(`UPDATE public."messages" SET id = 1;`)- expect(match).toBe(true)- })-- it('catches update on a quoted table name containing a space without a where clause', () => {- const match = isUpdateWithoutWhere(`UPDATE "my table" SET id = 1;`)- expect(match).toBe(true)- })-- it('catches update on a quoted table name containing escaped quotes without a where clause', () => {- const match = isUpdateWithoutWhere(`UPDATE "weird""name" SET id = 1;`)- expect(match).toBe(true)- })-- it('catches update where a quoted identifier contains the word where', () => {- const match = isUpdateWithoutWhere(`UPDATE "where table" SET id = 1;`)- expect(match).toBe(true)- })-- it('catches update where a string literal contains the word where', () => {- const match = isUpdateWithoutWhere(`UPDATE messages SET name = 'where x';`)- expect(match).toBe(true)- })-- it('does not flag update where the only "where" sits inside a string literal but a real where clause exists', () => {- const match = isUpdateWithoutWhere(`UPDATE messages SET name = 'where x' WHERE id = 1;`)- expect(match).toBe(false)- })-- it('contains both an update query and a delete query, triggers destructive', () => {- const match = checkDestructiveQuery(stripIndent`- delete from countries; update countries set name = 'hello';- `)-- expect(match).toBe(true)- })-- it('contains both an update query and a delete query, triggers no where', () => {- const match = isUpdateWithoutWhere(stripIndent`- delete from countries; update countries set name = 'hello';- `)-- expect(match).toBe(true)- })- it('contains both an update query and a delete query, triggers no where', () => {- const match = isUpdateWithoutWhere(stripIndent`- delete from countries; update countries set name = 'hello';- `)-- expect(match).toBe(true)- })-- it('should catch potential destructive queries', () => {- const DESTRUCTIVE_QUERIES = [- `ALTER TABLE test DROP COLUMN test;`,- `DELETE FROM test;`,- `DROP TABLE test;`,- `TRUNCATE TABLE test;`,- ]-- DESTRUCTIVE_QUERIES.forEach((query) => {- expect(checkDestructiveQuery(query), `Query ${query} should be destructive`).toBe(true)- })- })-- it('should catch EXECUTE with DROP in string literal', () => {- expect(checkDestructiveQuery(`EXECUTE 'DROP TABLE users';`)).toBe(true)- })-- it('should catch EXECUTE with DELETE in string literal', () => {- expect(checkDestructiveQuery(`EXECUTE 'DELETE FROM users';`)).toBe(true)- })-- it('should catch EXECUTE with TRUNCATE in string literal', () => {- expect(checkDestructiveQuery(`EXECUTE 'TRUNCATE TABLE users';`)).toBe(true)- })-- it('should catch EXECUTE format with DROP', () => {- expect(checkDestructiveQuery(`EXECUTE format('DROP TABLE %I', table_name);`)).toBe(true)- })-- it('should catch EXECUTE format with DELETE', () => {- expect(checkDestructiveQuery(`EXECUTE format('DELETE FROM %I', table_name);`)).toBe(true)- })-- it('should catch EXECUTE format with TRUNCATE', () => {- expect(checkDestructiveQuery(`EXECUTE format('TRUNCATE TABLE %I', table_name);`)).toBe(true)- })-- it('should catch EXECUTE with string concatenation containing DROP', () => {- expect(checkDestructiveQuery(`EXECUTE 'DROP TABLE ' || table_name;`)).toBe(true)- })-- it('should catch EXECUTE with string concatenation containing DELETE', () => {- expect(checkDestructiveQuery(`EXECUTE 'DELETE FROM ' || table_name;`)).toBe(true)- })-- it('should catch DO block with EXECUTE DROP', () => {- expect(- checkDestructiveQuery(stripIndent`- DO $$- BEGIN- EXECUTE 'DROP TABLE users';- END- $$;- `)- ).toBe(true)- })-- it('should catch DO block with EXECUTE format DROP', () => {- expect(- checkDestructiveQuery(stripIndent`- DO $$- BEGIN- FOR rec IN SELECT tablename FROM pg_tables WHERE schemaname = 'public' LOOP- EXECUTE format('DROP TABLE %I', rec.tablename);- END LOOP;- END- $$;- `)- ).toBe(true)- })-- it('should catch DO block with multiple EXECUTE format DROPs', () => {- expect(- checkDestructiveQuery(stripIndent`- DO $$- DECLARE- func_name text;- BEGIN- FOR func_name IN- SELECT routine_name FROM information_schema.routines WHERE routine_schema = 'public'- LOOP- EXECUTE format('DROP FUNCTION %I', func_name);- END LOOP;- END- $$;- `)- ).toBe(true)- })-- it('should catch lowercase execute with drop', () => {- expect(checkDestructiveQuery(`execute 'drop table users';`)).toBe(true)- })-- it('should catch mixed case EXECUTE Format with DROP', () => {- expect(checkDestructiveQuery(`EXECUTE Format('DROP TABLE users');`)).toBe(true)- })-- it('should not flag EXECUTE with safe SQL', () => {- expect(checkDestructiveQuery(`EXECUTE 'SELECT * FROM users';`)).toBe(false)- })-- it('should not flag EXECUTE with INSERT', () => {- expect(checkDestructiveQuery(`EXECUTE 'INSERT INTO users (name) VALUES (''test'')';`)).toBe(- false- )- })-- it('should not flag EXECUTE with UPDATE and WHERE', () => {- expect(checkDestructiveQuery(`EXECUTE 'UPDATE users SET name = ''test'' WHERE id = 1';`)).toBe(- false- )- })-- it('should catch EXECUTE IMMEDIATE with DROP', () => {- expect(checkDestructiveQuery(`EXECUTE IMMEDIATE 'DROP TABLE users';`)).toBe(true)- })-- it('should catch EXECUTE IMMEDIATE with DELETE', () => {- expect(checkDestructiveQuery(`EXECUTE IMMEDIATE 'DELETE FROM users';`)).toBe(true)- })-- it('should catch EXECUTE IMMEDIATE with TRUNCATE', () => {- expect(checkDestructiveQuery(`EXECUTE IMMEDIATE 'TRUNCATE TABLE users';`)).toBe(true)- })-- it('should catch OPEN cursor FOR EXECUTE with DROP', () => {- expect(checkDestructiveQuery(`OPEN ref FOR EXECUTE 'DROP TABLE users';`)).toBe(true)- })-- it('should catch OPEN cursor FOR EXECUTE format with DELETE', () => {- expect(checkDestructiveQuery(`OPEN ref FOR EXECUTE format('DELETE FROM %I', tbl);`)).toBe(true)- })-- it('should catch OPEN cursor FOR EXECUTE with string concat', () => {- expect(checkDestructiveQuery(`OPEN ref FOR EXECUTE 'TRUNCATE TABLE ' || tbl;`)).toBe(true)- })-- it('should catch RETURN QUERY EXECUTE with DROP', () => {- expect(checkDestructiveQuery(`RETURN QUERY EXECUTE 'DROP TABLE users';`)).toBe(true)- })-- it('should catch RETURN QUERY EXECUTE format with DELETE', () => {- expect(checkDestructiveQuery(`RETURN QUERY EXECUTE format('DELETE FROM %I', tbl);`)).toBe(true)- })-- it('should catch EXECUTE with dollar-quoted string containing DROP', () => {- expect(checkDestructiveQuery(`EXECUTE $sql$DROP TABLE users$sql$;`)).toBe(true)- })-- it('should catch EXECUTE with dollar-quoted string containing TRUNCATE', () => {- expect(checkDestructiveQuery(`EXECUTE $body$TRUNCATE TABLE logs$body$;`)).toBe(true)- })-- it('should catch EXECUTE concat with DROP', () => {- expect(checkDestructiveQuery(`EXECUTE concat('DROP TABLE ', 'users');`)).toBe(true)- })-- it('should catch EXECUTE concat_ws with DELETE', () => {- expect(checkDestructiveQuery(`EXECUTE concat_ws(' ', 'DELETE FROM', 'users');`)).toBe(true)- })-- it('should catch EXECUTE with E-string escape containing DROP', () => {- expect(checkDestructiveQuery(`EXECUTE E'DROP TABLE users';`)).toBe(true)- })-- it('should catch EXECUTE with ALTER TABLE DROP COLUMN', () => {- expect(checkDestructiveQuery(`EXECUTE 'ALTER TABLE users DROP COLUMN email';`)).toBe(true)- })-- it('should catch EXECUTE format with ALTER TABLE DROP COLUMN', () => {- expect(- checkDestructiveQuery(`EXECUTE format('ALTER TABLE %I DROP COLUMN %I', 'users', 'email');`)- ).toBe(true)- })-- it('should catch EXECUTE IMMEDIATE with ALTER TABLE DROP COLUMN', () => {- expect(checkDestructiveQuery(`EXECUTE IMMEDIATE 'ALTER TABLE users DROP COLUMN email';`)).toBe(- true- )- })-- it('should catch OPEN cursor FOR EXECUTE with ALTER TABLE DROP COLUMN', () => {- expect(- checkDestructiveQuery(`OPEN ref FOR EXECUTE 'ALTER TABLE users DROP COLUMN email';`)- ).toBe(true)- })-- it('should catch RETURN QUERY EXECUTE with ALTER TABLE DROP COLUMN', () => {- expect(- checkDestructiveQuery(`RETURN QUERY EXECUTE 'ALTER TABLE users DROP COLUMN email';`)- ).toBe(true)- })-- it('should catch EXECUTE dollar-quoted with ALTER TABLE DROP COLUMN', () => {- expect(checkDestructiveQuery(`EXECUTE $sql$ALTER TABLE users DROP COLUMN email$sql$;`)).toBe(- true- )- })-- it('should catch EXECUTE concat with ALTER TABLE DROP COLUMN', () => {- expect(- checkDestructiveQuery(`EXECUTE concat('ALTER TABLE ', 'users DROP COLUMN email');`)- ).toBe(true)- })-- it('should catch DO block with EXECUTE ALTER TABLE DROP COLUMN', () => {- expect(- checkDestructiveQuery(stripIndent`- DO $$- BEGIN- EXECUTE 'ALTER TABLE users DROP COLUMN email';- END- $$;- `)- ).toBe(true)- })-- it('should not flag ALTER TABLE without DROP COLUMN', () => {- expect(checkDestructiveQuery(`EXECUTE 'ALTER TABLE users ADD COLUMN email text';`)).toBe(false)- })-- it('should not flag variable assignment with safe SQL', () => {- expect(checkDestructiveQuery(`sql := 'SELECT * FROM users';`)).toBe(false)- })-- it('should not flag OPEN cursor FOR EXECUTE with safe SQL', () => {- expect(checkDestructiveQuery(`OPEN ref FOR EXECUTE 'SELECT * FROM users';`)).toBe(false)- })-- it('should not flag RETURN QUERY EXECUTE with safe SQL', () => {- expect(checkDestructiveQuery(`RETURN QUERY EXECUTE 'SELECT * FROM users';`)).toBe(false)+describe('SQLEditor.utils:isUpdateWithoutWhere', () => {+ test.each([+ `UPDATE public.countries SET name = 'New Name';`,+ `UPDATE "public"."countries" SET name = 'New Name';`,+ `UPDATE "messages" SET id = 1;`,+ `UPDATE "public".messages SET id = 1;`,+ `UPDATE public."messages" SET id = 1;`,+ `UPDATE "my table" SET id = 1;`,+ `UPDATE "weird""name" SET id = 1;`,+ // the word "where" inside an identifier or string literal is not a where clause+ `UPDATE "where table" SET id = 1;`,+ `UPDATE messages SET name = 'where x';`,+ `delete from countries; update countries set name = 'hello';`,+ ])('flags update without a where clause: %s', (sql) => {+ expect(isUpdateWithoutWhere(sql)).toBe(true)+ })++ test.each([+ `UPDATE public.countries SET name = 'New Name' WHERE id = 1;`,+ `UPDATE "public"."countries" SET name = 'New Name' WHERE id = 1;`,+ `UPDATE "messages" SET id = 1 WHERE id = 2;`,+ `UPDATE messages SET name = 'where x' WHERE id = 1;`,+ ])('does not flag update with a where clause: %s', (sql) => {+ expect(isUpdateWithoutWhere(sql)).toBe(false)})})@@ -1143,34 +744,23 @@ describe('SQLEditor.utils:appendEnableRLSStatements', () => {})describe('SQLEditor.utils:hasActiveEnsureRLSTrigger', () => {- it('returns false for undefined triggers', () => {- expect(hasActiveEnsureRLSTrigger(undefined)).toBe(false)- })-- it('returns false for an empty list', () => {- expect(hasActiveEnsureRLSTrigger([])).toBe(false)- })-- it('returns true when a trigger named "ensure_rls" is active', () => {- expect(hasActiveEnsureRLSTrigger([buildTrigger()])).toBe(true)- })-- it('returns true when a trigger uses the rls_auto_enable function (renamed trigger)', () => {- expect(- hasActiveEnsureRLSTrigger([- buildTrigger({ name: 'something_else', function_name: 'rls_auto_enable' }),- ])- ).toBe(true)- })-- it('returns false when the matching trigger is DISABLED', () => {- expect(hasActiveEnsureRLSTrigger([buildTrigger({ enabled_mode: 'DISABLED' })])).toBe(false)- })-- it('ignores unrelated triggers', () => {- expect(- hasActiveEnsureRLSTrigger([buildTrigger({ name: 'audit_log', function_name: 'log_changes' })])- ).toBe(false)+ test.each<[string, DatabaseEventTrigger[] | undefined, boolean]>([+ ['undefined triggers', undefined, false],+ ['an empty list', [], false],+ ['an active "ensure_rls" trigger', [buildTrigger()], true],+ [+ 'a renamed trigger using rls_auto_enable',+ [buildTrigger({ name: 'something_else', function_name: 'rls_auto_enable' })],+ true,+ ],+ ['a DISABLED matching trigger', [buildTrigger({ enabled_mode: 'DISABLED' })], false],+ [+ 'unrelated triggers',+ [buildTrigger({ name: 'audit_log', function_name: 'log_changes' })],+ false,+ ],+ ])('%s -> %s', (_, triggers, expected) => {+ expect(hasActiveEnsureRLSTrigger(triggers)).toBe(expected)})})@@ -1207,55 +797,21 @@ describe('SQLEditor.utils:filterTablesCoveredByEnsureRLSTrigger', () => {})describe('SQLEditor.utils:checkAlterDatabaseConnection', () => {- it('detects connection limit 0', () => {- const match = checkAlterDatabaseConnection('alter database postgres connection limit 0;')- expect(match).toBe(true)- })-- it('detects allow_connections false', () => {- const match = checkAlterDatabaseConnection('alter database postgres allow_connections false;')- expect(match).toBe(true)- })-- it('detects case-insensitive match', () => {- const match = checkAlterDatabaseConnection('ALTER DATABASE postgres CONNECTION LIMIT 0;')- expect(match).toBe(true)- })-- it('detects statement among multiple statements', () => {- const match = checkAlterDatabaseConnection(stripIndent`- select * from countries;- alter database postgres connection limit 0;- `)- expect(match).toBe(true)- })-- it('does not flag unrelated alter database statement', () => {- const match = checkAlterDatabaseConnection(- 'alter database postgres set statement_timeout = 60000;'- )- expect(match).toBe(false)- })-- it('does not flag non-alter statements', () => {- const match = checkAlterDatabaseConnection('select * from countries;')- expect(match).toBe(false)- })-- it('ignores statements inside comments', () => {- const match = checkAlterDatabaseConnection(stripIndent`- -- alter database postgres connection limit 0;- select 1;- `)- expect(match).toBe(false)- })-- it('detects both dangerous statements in same query', () => {- const match = checkAlterDatabaseConnection(stripIndent`- alter database postgres connection limit 0;- alter database postgres allow_connections false;- `)- expect(match).toBe(true)+ test.each([+ 'alter database postgres connection limit 0;',+ 'alter database postgres allow_connections false;',+ 'ALTER DATABASE postgres CONNECTION LIMIT 0;',+ 'select * from countries;\nalter database postgres connection limit 0;',+ ])('detects: %s', (sql) => {+ expect(checkAlterDatabaseConnection(sql)).toBe(true)+ })++ test.each([+ 'alter database postgres set statement_timeout = 60000;',+ 'select * from countries;',+ '-- alter database postgres connection limit 0;\nselect 1;',+ ])('does not flag: %s', (sql) => {+ expect(checkAlterDatabaseConnection(sql)).toBe(false)})})@@ -1382,37 +938,19 @@ describe('SQLEditor.utils:hasBlockingIssues', () => {createTablesMissingRLS: [],}- it('returns false when there are no issues', () => {- expect(hasBlockingIssues(noIssues, false)).toBe(false)- })-- it('returns true when hasDestructiveOperations is set', () => {- expect(hasBlockingIssues({ ...noIssues, hasDestructiveOperations: true }, false)).toBe(true)- })-- it('returns true when hasUpdateWithoutWhere is set', () => {- expect(hasBlockingIssues({ ...noIssues, hasUpdateWithoutWhere: true }, false)).toBe(true)- })-- it('returns true when hasAlterDatabasePreventConnection is set', () => {- expect(hasBlockingIssues({ ...noIssues, hasAlterDatabasePreventConnection: true }, false)).toBe(- true- )- })-- it('returns true when createTablesMissingRLS is non-empty', () => {- expect(- hasBlockingIssues({ ...noIssues, createTablesMissingRLS: [{ tableName: 'foo' }] }, false)- ).toBe(true)+ test.each([+ ['no issues', {}, false],+ ['hasDestructiveOperations', { hasDestructiveOperations: true }, true],+ ['hasUpdateWithoutWhere', { hasUpdateWithoutWhere: true }, true],+ ['hasAlterDatabasePreventConnection', { hasAlterDatabasePreventConnection: true }, true],+ ['createTablesMissingRLS non-empty', { createTablesMissingRLS: [{ tableName: 'foo' }] }, true],+ ])('%s -> %s', (_, overrides, expected) => {+ expect(hasBlockingIssues({ ...noIssues, ...overrides }, false)).toBe(expected)})it('returns false when force is true, even with issues present', () => {expect(hasBlockingIssues({ ...noIssues, hasDestructiveOperations: true }, true)).toBe(false)})-- it('returns false when force is true and there are no issues', () => {- expect(hasBlockingIssues(noIssues, true)).toBe(false)- })})const buildDatabase = (overrides: Partial<Database> = {}): Database => ({diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.utils.test.ts b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.utils.test.tsindex d3e264256d5..765873c555d 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.utils.test.ts+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.utils.test.ts@@ -9,80 +9,58 @@ import {} from './Results.utils'describe('Results.utils', () => {- describe('formatResults', () => {- it('should stringify object values', () => {- const results = [{ id: 1, data: { nested: true } }]- const formatted = formatResults(results)- expect(formatted).toEqual([{ id: 1, data: '{"nested":true}' }])- })-- it('should stringify array values', () => {- const results = [{ id: 1, tags: ['a', 'b'] }]- const formatted = formatResults(results)- expect(formatted).toEqual([{ id: 1, tags: '["a","b"]' }])- })+ it.each([+ ['convertResultsToMarkdown', convertResultsToMarkdown],+ ['convertResultsToJSON', convertResultsToJSON],+ ['getResultsHeaders', getResultsHeaders],+ ['convertResultsToCSV', convertResultsToCSV],+ ])('%s returns undefined for empty results', (_, fn) => {+ expect(fn([])).toBeUndefined()+ })- it('should stringify null values', () => {- const results = [{ id: 1, value: null }]- const formatted = formatResults(results)- expect(formatted).toEqual([{ id: 1, value: 'null' }])+ describe('formatResults', () => {+ it.each([+ ['object', { nested: true }, '{"nested":true}'],+ ['array', ['a', 'b'], '["a","b"]'],+ ['null', null, 'null'],+ ])('stringifies %s values', (_, value, expected) => {+ expect(formatResults([{ id: 1, value }])).toEqual([{ id: 1, value: expected }])})- it('should leave primitive values unchanged', () => {+ it('leaves primitive values unchanged', () => {const results = [{ name: 'test', count: 42, active: true }]- const formatted = formatResults(results)- expect(formatted).toEqual([{ name: 'test', count: 42, active: true }])- })-- it('should return empty array for empty input', () => {+ expect(formatResults(results)).toEqual(results)expect(formatResults([])).toEqual([])})})describe('convertResultsToMarkdown', () => {- it('should return undefined for empty results', () => {- expect(convertResultsToMarkdown([])).toBeUndefined()- })-- it('should convert results to a markdown table', () => {- const results = [+ it('converts results to a markdown table, stringifying nested objects', () => {+ const md = convertResultsToMarkdown([{ id: 1, name: 'Alice' },- { id: 2, name: 'Bob' },- ]- const md = convertResultsToMarkdown(results)- expect(md).toContain('| id | name |')- expect(md).toContain('| 1 | Alice |')- expect(md).toContain('| 2 | Bob |')- })-- it('should stringify nested objects in markdown output', () => {- const results = [{ id: 1, meta: { role: 'admin' } }]- const md = convertResultsToMarkdown(results)+ { id: 2, name: { role: 'admin' } },+ ])+ expect(md).toContain('| 1 | Alice')expect(md).toContain('{"role":"admin"}')})- it('should escape pipe characters so a value cannot split into extra columns', () => {- const results = [{ id: 1, name: 'a|b' }]- const md = convertResultsToMarkdown(results)- const rows = md!.split('\n')+ it('escapes pipe characters so a value cannot split into extra columns', () => {+ const rows = convertResultsToMarkdown([{ id: 1, name: 'a|b' }])!.split('\n')// header + separator + one data row, not moreexpect(rows).toHaveLength(3)expect(rows[2]).toContain('a\\|b')})- it('should escape backslashes so an escaped pipe cannot be forged', () => {- const results = [{ id: 1, name: 'a\\|b' }]- const md = convertResultsToMarkdown(results)- expect(md).toContain('a\\\\\\|b')+ it('escapes backslashes so an escaped pipe cannot be forged', () => {+ expect(convertResultsToMarkdown([{ id: 1, name: 'a\\|b' }])).toContain('a\\\\\\|b')})- it('should replace newlines with <br> so a multiline value cannot create extra table rows', () => {- const results = [+ it('replaces newlines with <br> so a multiline value cannot create extra table rows', () => {+ const md = convertResultsToMarkdown([{ id: 1, query: 'select 1;\nselect 2;' },{ id: 2, query: 'select 3;\r\nselect 4;' },{ id: 3, query: 'select 5;\rselect 6;' },- ]- const md = convertResultsToMarkdown(results)+ ])const rows = md!.split('\n')// header + separator + 3 data rows, not moreexpect(rows).toHaveLength(5)@@ -93,92 +71,34 @@ describe('Results.utils', () => {})describe('convertResultsToJSON', () => {- it('should return undefined for empty results', () => {- expect(convertResultsToJSON([])).toBeUndefined()- })-- it('should return formatted JSON string', () => {- const results = [{ id: 1, name: 'Alice' }]- const json = convertResultsToJSON(results)- expect(json).toBe(JSON.stringify(results, null, 2))- })-- it('should preserve nested object structure', () => {+ it('returns a pretty-printed JSON string preserving nested structure', () => {const results = [{ id: 1, meta: { role: 'admin' } }]- const json = convertResultsToJSON(results)- const parsed = JSON.parse(json!)- expect(parsed[0].meta.role).toBe('admin')+ expect(convertResultsToJSON(results)).toBe(JSON.stringify(results, null, 2))})})describe('getResultsHeaders', () => {- it('should return undefined for empty results', () => {- expect(getResultsHeaders([])).toBeUndefined()- })-- it('should return keys from the first row', () => {- const results = [{ id: 1, name: 'Alice' }]- expect(getResultsHeaders(results)).toEqual(['id', 'name'])- })-- it('should preserve key order from the first row', () => {- const results = [{ z: 1, a: 2, m: 3 }]- expect(getResultsHeaders(results)).toEqual(['z', 'a', 'm'])- })-- it('should use only the first row for headers', () => {- const results = [{ id: 1 }, { id: 2, extra: 'bonus' }]- expect(getResultsHeaders(results)).toEqual(['id'])+ it('returns keys in order from the first row only', () => {+ expect(getResultsHeaders([{ z: 1, a: 2, m: 3 }, { extra: 'bonus' }])).toEqual(['z', 'a', 'm'])})})describe('convertResultsToCSV', () => {- it('should return undefined for empty results', () => {- expect(convertResultsToCSV([])).toBeUndefined()- })-- it('should include header row from first result keys', () => {- const results = [{ id: 1, name: 'Alice' }]- const csv = convertResultsToCSV(results)- expect(csv).toContain('id,name')- })-- it('should include data rows', () => {- const results = [- { id: 1, name: 'Alice' },- { id: 2, name: 'Bob' },- ]- const csv = convertResultsToCSV(results)- expect(csv).toContain('Alice')- expect(csv).toContain('Bob')+ it('writes a header row from the first result keys followed by data rows', () => {+ const csv = convertResultsToCSV([+ { z: 1, name: 'Alice' },+ { z: 2, name: 'Bob' },+ ])+ // split on CRLF line endings produced by papaparse+ expect(csv!.split('\r\n')).toEqual(['z,name', '1,Alice', '2,Bob'])})- it('should stringify object values', () => {- const results = [{ id: 1, meta: { role: 'admin' } }]- const csv = convertResultsToCSV(results)+ it('stringifies and quotes object and array values', () => {+ const csv = convertResultsToCSV([{ meta: { role: 'admin' }, tags: ['a', 'b'], value: null }])// CSV wraps values containing special chars in quotes and escapes inner quotesexpect(csv).toContain('"{""role"":""admin""}"')- })-- it('should stringify array values', () => {- const results = [{ id: 1, tags: ['a', 'b'] }]- const csv = convertResultsToCSV(results)- // CSV wraps values containing special chars in quotes and escapes inner quotesexpect(csv).toContain('"[""a"",""b""]"')- })-- it('should stringify null values', () => {- const results = [{ id: 1, value: null }]- const csv = convertResultsToCSV(results)expect(csv).toContain('null')})-- it('should preserve column order from first row', () => {- const results = [{ z: 1, a: 2, m: 3 }]- const csv = convertResultsToCSV(results)- // split on CRLF line endings produced by papaparse- const headerRow = csv!.split('\r\n')[0]- expect(headerRow).toBe('z,a,m')- })})})diff --git a/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.test.ts b/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.test.tsindex bd0eb330bbb..670cee071b2 100644--- a/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.test.ts+++ b/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { QueryClient } from '@tanstack/react-query'import { waitFor } from '@testing-library/react'import { HttpResponse } from 'msw'diff --git a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.test.tsx b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.test.tsxindex d24c621563e..0c31e428645 100644--- a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.test.tsx+++ b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.test.tsx@@ -84,13 +84,21 @@ const renderModal = (return { onClose }}+const user = userEvent.setup()++// Pasting rather than typing: keystroke-level input isn't the behaviour under test+const enterValue = async (input: HTMLElement, value: string) => {+ await user.clear(input)+ await user.paste(value)+}++const enterAddress = async (address: string) =>+ enterValue(await screen.findByPlaceholderText('0.0.0.0'), address)+const addEntry = async (address: string, cidrBlockSize?: string) => {- const ipInput = await screen.findByPlaceholderText('0.0.0.0')- await userEvent.type(ipInput, address)+ await enterAddress(address)if (cidrBlockSize !== undefined) {- const sizeInput = screen.getByPlaceholderText('32')- await userEvent.clear(sizeInput)- await userEvent.type(sizeInput, cidrBlockSize)+ await enterValue(screen.getByPlaceholderText('32'), cidrBlockSize)}fireEvent.click(screen.getByRole('button', { name: 'Add to list' }))}@@ -148,7 +156,7 @@ describe('AddRestrictionModal', () => {const { onClose } = renderModal()await addEntry('203.0.113.7')- await userEvent.type(screen.getByPlaceholderText('0.0.0.0'), '192.0.2.1')+ await enterAddress('192.0.2.1')fireEvent.click(await screen.findByRole('button', { name: 'Save restrictions' }))@@ -166,7 +174,7 @@ describe('AddRestrictionModal', () => {const requests = mockApply()const { onClose } = renderModal()- await userEvent.type(await screen.findByPlaceholderText('0.0.0.0'), '192.0.2.1')+ await enterAddress('192.0.2.1')fireEvent.click(await screen.findByRole('button', { name: 'Save restriction' }))await waitFor(() => expect(onClose).toHaveBeenCalled())@@ -226,7 +234,7 @@ describe('AddRestrictionModal', () => {renderModal()await addEntry('203.0.113.7')- await userEvent.click(await screen.findByRole('button', { name: 'Remove 203.0.113.7/32' }))+ await user.click(await screen.findByRole('button', { name: 'Remove 203.0.113.7/32' }))expect(screen.queryByDisplayValue('203.0.113.7/32')).not.toBeInTheDocument()expect(screen.getByRole('button', { name: 'Save restrictions' })).toBeDisabled()@@ -237,12 +245,12 @@ describe('AddRestrictionModal', () => {const { onClose } = renderModal()await addEntry('203.0.113.7')- await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ await user.click(screen.getByRole('button', { name: 'Cancel' }))expect(await screen.findByText('Unsaved changes')).toBeInTheDocument()expect(onClose).not.toHaveBeenCalled()- await userEvent.click(screen.getByRole('button', { name: 'Discard changes' }))+ await user.click(screen.getByRole('button', { name: 'Discard changes' }))expect(onClose).toHaveBeenCalled()})@@ -250,7 +258,7 @@ describe('AddRestrictionModal', () => {mockExistingRestrictions([])const { onClose } = renderModal()- await userEvent.click(await screen.findByRole('button', { name: 'Cancel' }))+ await user.click(await screen.findByRole('button', { name: 'Cancel' }))expect(onClose).toHaveBeenCalled()})diff --git a/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.test.tsx b/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.test.tsxindex be5e65de7d9..6fcb9bf4ebe 100644--- a/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.test.tsx+++ b/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.test.tsx@@ -1,4 +1,4 @@-import { screen, waitFor } from '@testing-library/react'+import { fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import type { components, paths } from 'api-types'import { HttpResponse } from 'msw'@@ -109,11 +109,10 @@ describe('SSLConfiguration', () => {// Nothing is loading for HA projects, so there is no announcement to makeexpect(screen.getByRole('status')).toBeEmptyDOMElement()- // The tooltip trigger is the wrapper around the (disabled) switch- await userEvent.hover(sslSwitch.parentElement!)- expect((await screen.findAllByText(HA_TOOLTIP, {}, { timeout: 2000 })).length).toBeGreaterThan(- 0- )+ // The tooltip trigger is the wrapper around the (disabled) switch. Focus opens a Radix+ // tooltip without the hover delay.+ fireEvent.focus(sslSwitch.parentElement!)+ expect((await screen.findAllByText(HA_TOOLTIP)).length).toBeGreaterThan(0)expect(sslEnforcementRequests.count).toBe(0)})diff --git a/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.test.tsx b/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.test.tsxindex 04af40ef5cd..c7264bacc1d 100644--- a/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.test.tsx+++ b/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.test.tsx@@ -1,5 +1,4 @@import { fireEvent, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'import { mockAnimationsApi } from 'jsdom-testing-mocks'import { HttpResponse } from 'msw'import { toast } from 'sonner'@@ -89,10 +88,10 @@ const mockSurveyAndDelete = ({ surveyStatus }: { surveyStatus: 201 | 403 }) => {const deleteProject = async () => {const [reason] = await screen.findAllByRole('radio', { hidden: true })fireEvent.click(reason)- await userEvent.type(screen.getByPlaceholderText('Type the project name in here'), PROJECT.name)+ fireEvent.change(screen.getByPlaceholderText('Type the project name in here'), {+ target: { value: PROJECT.name },+ })fireEvent.click(screen.getByRole('button', { name: 'I understand, delete this project' }))- await new Promise((r) => setTimeout(r, 300))- await new Promise((r) => setTimeout(r, 500))}describe('DeleteProjectModal', () => {diff --git a/apps/studio/components/interfaces/Settings/General/Infrastructure/PauseProjectButton.test.tsx b/apps/studio/components/interfaces/Settings/General/Infrastructure/PauseProjectButton.test.tsxindex dd09866a8aa..9613a39611f 100644--- a/apps/studio/components/interfaces/Settings/General/Infrastructure/PauseProjectButton.test.tsx+++ b/apps/studio/components/interfaces/Settings/General/Infrastructure/PauseProjectButton.test.tsx@@ -62,14 +62,11 @@ describe('PauseProjectButton', () => {const button = screen.getByRole('button', { name: 'Pause project' })expect(button).toBeAriaDisabled()- // Radix opens the tooltip on pointermove; focusable disabled buttons support this- fireEvent.pointerMove(button)+ // aria-disabled keeps the button focusable; Radix opens the tooltip on focus without the+ // hover delay+ fireEvent.focus(button)expect(- await screen.findAllByText(- 'Pausing is unavailable on High Availability projects',- {},- { timeout: 2000 }- )+ await screen.findAllByText('Pausing is unavailable on High Availability projects')).not.toHaveLength(0)})})diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.otel.test.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.otel.test.tsindex 7063b98d684..6f5ac485816 100644--- a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.otel.test.ts+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.otel.test.ts@@ -795,14 +795,6 @@ describe('mapOtelSingleLogToLegacy', () => {expect(log.metadata[0].response[0].headers[0].x_sb_error_code).toBeNull()})- it('falls back to the legacy x_sb_error_code key for api rows', () => {- const log = mapOtelSingleLogToLegacy(- { log_attributes: { 'response.headers.x_sb_error_code': 'pgrst' } },- 'api'- ) as any- expect(log.metadata[0].response[0].headers[0].x_sb_error_code).toBe('pgrst')- })-it('fills database metadata with null when attributes are missing', () => {const log = mapOtelSingleLogToLegacy({ log_attributes: {} }, 'database') as anyexpect(log.metadata[0].parsed[0].hint).toBeNull()diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.tsindex 6091e922362..c6c06b2bc5e 100644--- a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.ts+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.ts@@ -155,12 +155,6 @@ describe('Logs.utils', () => {const result = buildLogsPrompt(rows)expect(result).toContain('2 Supabase log entries')})-- test('handles singular correctly', () => {- const rows: LogData[] = [createLog({ id: '1', event_message: 'single error' })]- const result = buildLogsPrompt(rows)- expect(result).toContain('1 Supabase log entry')- })})describe('extractEdgeFunctionName', () => {@@ -168,18 +162,12 @@ describe('Logs.utils', () => {expect(extractEdgeFunctionName('/functions/v1/hello-world-1')).toBe('hello-world-1')})- test('returns empty string for null', () => {- expect(extractEdgeFunctionName(null)).toBe('')- })-- test('returns empty string for undefined', () => {- expect(extractEdgeFunctionName(undefined)).toBe('')- })-- test('returns empty string for non-string values', () => {- expect(extractEdgeFunctionName(42)).toBe('')- expect(extractEdgeFunctionName({})).toBe('')- })+ test.each([null, undefined, 42, {}])(+ 'returns empty string for non-string value %o',+ (value) => {+ expect(extractEdgeFunctionName(value)).toBe('')+ }+ )test('handles pathname with no slashes', () => {expect(extractEdgeFunctionName('my-function')).toBe('my-function')diff --git a/apps/studio/components/interfaces/SignIn/SignInMfa.utils.test.ts b/apps/studio/components/interfaces/SignIn/SignInMfa.utils.test.tsindex dbc48579ac2..5b3f9c2612d 100644--- a/apps/studio/components/interfaces/SignIn/SignInMfa.utils.test.ts+++ b/apps/studio/components/interfaces/SignIn/SignInMfa.utils.test.ts@@ -1,10 +1,6 @@import { describe, expect, test } from 'vitest'-import {- getFactorDisplayName,- getFactorFriendlyName,- MFA_SUPPORT_EMAIL_HREF,-} from './SignInMfa.utils'+import { getFactorDisplayName, getFactorFriendlyName } from './SignInMfa.utils'describe('getFactorFriendlyName', () => {test('returns the trimmed friendly name', () => {@@ -33,13 +29,3 @@ describe('getFactorDisplayName', () => {expect(getFactorDisplayName({ friendly_name: ' ' })).toBe('your authenticator app')})})--describe('MFA_SUPPORT_EMAIL_HREF', () => {- test('targets support with an encoded subject', () => {- const url = new URL(MFA_SUPPORT_EMAIL_HREF)-- expect(url.protocol).toBe('mailto:')- expect(url.pathname).toBe('[email protected]')- expect(url.searchParams.get('subject')).toBe('Unable to sign in via MFA')- })-})diff --git a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.test.tsx b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.test.tsxindex b8a49c2679d..4bed5044a41 100644--- a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.test.tsx+++ b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.test.tsx@@ -125,30 +125,18 @@ describe('BucketVersioningFields', () => {await waitForElementToBeRemoved(() => screen.queryByText('Expire a noncurrent version when'))})- test('warns when neither lifecycle condition is set', async () => {- renderFields({- defaultValues: {- enable_versioning: true,- version_expiry_days: '',- max_noncurrent_versions: '',- },- })-- expect(screen.getByText('No lifecycle policy')).toBeInTheDocument()- })-- test('warns that a public bucket serves every version', () => {- renderFields({ defaultValues: { enable_versioning: true }, isPublicBucket: true })-- expect(screen.getByText('A public bucket serves every version')).toBeInTheDocument()- })-- test('does not warn about public exposure for a private bucket', () => {- renderFields({ defaultValues: { enable_versioning: true }, isPublicBucket: false })-- expect(screen.getByText('Lifecycle policy')).toBeInTheDocument()- expect(screen.queryByText('A public bucket serves every version')).not.toBeInTheDocument()- })+ test.each([+ { isPublicBucket: true, shouldWarn: true },+ { isPublicBucket: false, shouldWarn: false },+ ])(+ 'warns that a public bucket serves every version (public: $isPublicBucket)',+ ({ isPublicBucket, shouldWarn }) => {+ renderFields({ defaultValues: { enable_versioning: true }, isPublicBucket })++ expect(screen.getByText('Lifecycle policy')).toBeInTheDocument()+ expect(screen.queryByText('A public bucket serves every version') !== null).toBe(shouldWarn)+ }+ )test('explains that turning the switch off suspends rather than disables', async () => {renderFields({@@ -197,7 +185,7 @@ describe('BucketVersioningFields', () => {expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument()})- test('shows the policy fields once it has resolved', () => {+ test('shows the policy fields once it has resolved, warning when neither condition is set', () => {renderFields({defaultValues: {enable_versioning: true,@@ -240,7 +228,8 @@ describe('BucketVersioningFields', () => {test('leaves a policy it cannot represent alone instead of offering to edit it', () => {renderFields({- defaultValues: { enable_versioning: true },+ // A tighter value than the partly-read initial policy must not trigger the tightening warning+ defaultValues: { enable_versioning: true, version_expiry_days: 7 },initialVersioningState: 'enabled',initialRetentionDays: 30,initialMaxVersions: 10,@@ -250,17 +239,6 @@ describe('BucketVersioningFields', () => {expect(screen.getByText('Lifecycle policy set outside the dashboard')).toBeInTheDocument()expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument()expect(screen.queryByText('No lifecycle policy')).not.toBeInTheDocument()- })-- test('does not warn about tightening a policy it only partly read', async () => {- renderFields({- defaultValues: { enable_versioning: true, version_expiry_days: 7 },- initialVersioningState: 'enabled',- initialRetentionDays: 30,- initialMaxVersions: 10,- isUnsupportedPolicy: true,- })-expect(screen.queryByText('Tightening retention expires some versions')).not.toBeInTheDocument()})diff --git a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.utils.test.ts b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.utils.test.tsindex 4adf9c4182f..25911601dc5 100644--- a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.utils.test.ts+++ b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.utils.test.ts@@ -1,10 +1,6 @@import { describe, expect, it } from 'vitest'-import {- getRetentionTightening,- RETENTION_TIGHTENING_DESCRIPTION,- toNullableNumber,-} from './BucketVersioningFields.utils'+import { getRetentionTightening, toNullableNumber } from './BucketVersioningFields.utils'const params = (overrides: Partial<Parameters<typeof getRetentionTightening>[0]> = {}) => ({initialVersioningState: 'enabled' as const,@@ -17,113 +13,88 @@ const params = (overrides: Partial<Parameters<typeof getRetentionTightening>[0]>})describe('getRetentionTightening', () => {- it('reports no tightening when nothing changed', () => {- expect(getRetentionTightening(params())).toBe('none')- })-- it('detects a shorter retention window', () => {- expect(getRetentionTightening(params({ nextRetentionDays: 7 }))).toBe('days')- })-- it('detects a lower version cap', () => {- expect(getRetentionTightening(params({ nextMaxVersions: 3 }))).toBe('versions')- })-- it('detects both bounds tightening at once', () => {- expect(getRetentionTightening(params({ nextRetentionDays: 7, nextMaxVersions: 3 }))).toBe(- 'both'- )- })-- it('does not warn when a bound is raised', () => {- expect(getRetentionTightening(params({ nextRetentionDays: 90, nextMaxVersions: 20 }))).toBe(- 'none'- )- })-- it('does not warn when a bound is cleared, which retains more rather than less', () => {- expect(getRetentionTightening(params({ nextRetentionDays: null, nextMaxVersions: null }))).toBe(- 'none'- )- })-- it('warns when a bound is newly added where none existed, which was keeping them forever', () => {- expect(- getRetentionTightening(params({ initialRetentionDays: null, nextRetentionDays: 7 }))- ).toBe('days')- })-- it('warns when a cap is newly added where none existed', () => {- expect(getRetentionTightening(params({ initialMaxVersions: null, nextMaxVersions: 3 }))).toBe(- 'versions'- )- })-- it('does not warn when both bounds stay unbounded', () => {- expect(- getRetentionTightening(- params({- initialRetentionDays: null,- initialMaxVersions: null,- nextRetentionDays: null,- nextMaxVersions: null,- })- )- ).toBe('none')- })-- it('does not warn while the initial bounds are still loading', () => {- expect(- getRetentionTightening(- params({ initialRetentionDays: undefined, initialMaxVersions: undefined })- )- ).toBe('none')- })-- it('does not warn when versioning is being turned off', () => {- // Suspending never expires what is already retained, so there is nothing to lose.- expect(- getRetentionTightening(params({ isVersioningEnabled: false, nextRetentionDays: 7 }))- ).toBe('none')- })-- it('does not warn when versioning is being enabled for the first time', () => {- expect(- getRetentionTightening(- params({- initialVersioningState: 'disabled',- initialRetentionDays: null,- initialMaxVersions: null,- nextRetentionDays: 7,- })- )- ).toBe('none')- })-- it('does not warn when re-enabling a suspended bucket', () => {- // A suspended bucket's stored bounds are cleared, so there is nothing to tighten from.- expect(- getRetentionTightening(params({ initialVersioningState: 'suspended', nextRetentionDays: 7 }))- ).toBe('none')- })-- it('has a description for every tightening kind it can report', () => {- for (const kind of ['days', 'versions', 'both'] as const) {- expect(RETENTION_TIGHTENING_DESCRIPTION[kind], kind).toBeTruthy()- }+ it.each([+ { scenario: 'nothing changed', overrides: {}, expected: 'none' },+ {+ scenario: 'a shorter retention window',+ overrides: { nextRetentionDays: 7 },+ expected: 'days',+ },+ { scenario: 'a lower version cap', overrides: { nextMaxVersions: 3 }, expected: 'versions' },+ {+ scenario: 'both bounds tightening at once',+ overrides: { nextRetentionDays: 7, nextMaxVersions: 3 },+ expected: 'both',+ },+ {+ scenario: 'a bound is raised',+ overrides: { nextRetentionDays: 90, nextMaxVersions: 20 },+ expected: 'none',+ },+ {+ scenario: 'a bound is cleared, which retains more rather than less',+ overrides: { nextRetentionDays: null, nextMaxVersions: null },+ expected: 'none',+ },+ {+ scenario: 'a bound is newly added where none existed, which was keeping them forever',+ overrides: { initialRetentionDays: null, nextRetentionDays: 7 },+ expected: 'days',+ },+ {+ scenario: 'a cap is newly added where none existed',+ overrides: { initialMaxVersions: null, nextMaxVersions: 3 },+ expected: 'versions',+ },+ {+ scenario: 'both bounds stay unbounded',+ overrides: {+ initialRetentionDays: null,+ initialMaxVersions: null,+ nextRetentionDays: null,+ nextMaxVersions: null,+ },+ expected: 'none',+ },+ {+ scenario: 'the initial bounds are still loading',+ overrides: { initialRetentionDays: undefined, initialMaxVersions: undefined },+ expected: 'none',+ },+ {+ // Suspending never expires what is already retained, so there is nothing to lose.+ scenario: 'versioning is being turned off',+ overrides: { isVersioningEnabled: false, nextRetentionDays: 7 },+ expected: 'none',+ },+ {+ scenario: 'versioning is being enabled for the first time',+ overrides: {+ initialVersioningState: 'disabled' as const,+ initialRetentionDays: null,+ initialMaxVersions: null,+ nextRetentionDays: 7,+ },+ expected: 'none',+ },+ {+ // A suspended bucket's stored bounds are cleared, so there is nothing to tighten from.+ scenario: 're-enabling a suspended bucket',+ overrides: { initialVersioningState: 'suspended' as const, nextRetentionDays: 7 },+ expected: 'none',+ },+ ])('reports $expected when $scenario', ({ overrides, expected }) => {+ expect(getRetentionTightening(params(overrides))).toBe(expected)})})describe('toNullableNumber', () => {- it('maps the empty sentinel to null', () => {- expect(toNullableNumber('')).toBeNull()- })-- it('preserves zero rather than treating it as empty', () => {- expect(toNullableNumber(0)).toBe(0)- })-- it('passes numbers through', () => {- expect(toNullableNumber(30)).toBe(30)+ it.each([+ { input: '' as const, expected: null },+ // Zero is a real value, not empty+ { input: 0, expected: 0 },+ { input: 30, expected: 30 },+ ])('maps $input to $expected', ({ input, expected }) => {+ expect(toNullableNumber(input)).toBe(expected)})})diff --git a/apps/studio/components/interfaces/Storage/FilesBuckets/CreateBucketModal.test.tsx b/apps/studio/components/interfaces/Storage/FilesBuckets/CreateBucketModal.test.tsxindex 5cb0b5600c6..12702295edf 100644--- a/apps/studio/components/interfaces/Storage/FilesBuckets/CreateBucketModal.test.tsx+++ b/apps/studio/components/interfaces/Storage/FilesBuckets/CreateBucketModal.test.tsx@@ -55,60 +55,51 @@ describe(`CreateBucketModal`, () => {})})- it(`renders a dialog with a form`, async () => {+ it('submits the public flag, size limit and MIME types entered in the form', async () => {+ const requests: unknown[] = []+ addAPIMock({+ method: 'post',+ path: '/platform/storage/:ref/buckets',+ response: async ({ request }) => {+ requests.push(await request.json())+ return Response.json({ name: 'test' })+ },+ })+ const onOpenChange = vi.fn()+customRender(<ProjectContextProvider projectRef="default">- <CreateBucketModal open={true} onOpenChange={() => {}} />- </ProjectContextProvider>,- {- nuqs: {- searchParams: {- new: 'true',- },- },- }+ <CreateBucketModal open onOpenChange={onOpenChange} />+ </ProjectContextProvider>)- await waitFor(() => {- expect(screen.getByRole(`dialog`)).toBeInTheDocument()- })-- const nameInput = screen.getByLabelText(`Bucket name`)- await userEvent.type(nameInput, `test`)-- const publicToggle = screen.getByLabelText(`Public bucket`)- expect(publicToggle).not.toBeChecked()- await userEvent.click(publicToggle)- expect(publicToggle).toBeChecked()-- const sizeLimitToggle = screen.getByLabelText(`Restrict file size`)- expect(sizeLimitToggle).not.toBeChecked()- await userEvent.click(sizeLimitToggle)- expect(sizeLimitToggle).toBeChecked()-- const sizeLimitInput = screen.getByLabelText(`File size limit`)- expect(sizeLimitInput).toHaveValue(null)- await userEvent.type(sizeLimitInput, `25`)+ await userEvent.type(await screen.findByLabelText('Bucket name'), 'test')+ await userEvent.click(screen.getByLabelText('Public bucket'))+ await userEvent.click(screen.getByLabelText('Restrict file size'))+ await userEvent.type(screen.getByLabelText('File size limit'), '25')- const sizeLimitUnitSelect = screen.getByLabelText(`File size limit unit`)- expect(sizeLimitUnitSelect).toHaveTextContent(`MB`)+ const sizeLimitUnitSelect = screen.getByLabelText('File size limit unit')+ expect(sizeLimitUnitSelect).toHaveTextContent('MB')await userEvent.click(sizeLimitUnitSelect)- const bytesOption = screen.getByRole(`option`, { name: `bytes` })- await userEvent.click(bytesOption)- expect(sizeLimitUnitSelect).toHaveTextContent(`bytes`)+ await userEvent.click(screen.getByRole('option', { name: 'bytes' }))- const mimeTypeToggle = screen.getByLabelText(`Restrict MIME types`)- expect(mimeTypeToggle).not.toBeChecked()- await userEvent.click(mimeTypeToggle)- expect(mimeTypeToggle).toBeChecked()-- const mimeTypeInput = screen.getByLabelText(`Allowed MIME types`)- expect(mimeTypeInput).toHaveValue(``)- await userEvent.type(mimeTypeInput, `image/jpeg, image/png`)+ await userEvent.click(screen.getByLabelText('Restrict MIME types'))+ fireEvent.change(screen.getByLabelText('Allowed MIME types'), {+ target: { value: 'image/jpeg, image/png' },+ })- const submitButton = screen.getByRole(`button`, { name: `Create` })+ // jsdom doesn't associate the footer button with the form by attribute+ fireEvent.submit(document.getElementById('create-storage-bucket-form')!)- fireEvent.click(submitButton)+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false))+ expect(requests).toEqual([+ expect.objectContaining({+ id: 'test',+ public: true,+ file_size_limit: 25,+ allowed_mime_types: ['image/jpeg', 'image/png'],+ }),+ ])})it('keeps the bucket it created when the retention policy is rejected', async () => {diff --git a/apps/studio/components/interfaces/Storage/FilesBuckets/FilesBucket.schema.test.ts b/apps/studio/components/interfaces/Storage/FilesBuckets/FilesBucket.schema.test.tsindex f82ad324c7f..2bae618bd33 100644--- a/apps/studio/components/interfaces/Storage/FilesBuckets/FilesBucket.schema.test.ts+++ b/apps/studio/components/interfaces/Storage/FilesBuckets/FilesBucket.schema.test.ts@@ -109,8 +109,4 @@ describe('bucketVersioningFormFields', () => {it('rejects a fractional retention window', () => {expect(schema.safeParse({ version_expiry_days: 1.5 }).success).toBe(false)})-- it('rejects an unknown expiration mode', () => {- expect(schema.safeParse({ expiration_mode: 'xor' }).success).toBe(false)- })})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeader.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeader.test.tsxindex 2a4c7fef1b3..6c3cd827ab8 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeader.test.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeader.test.tsx@@ -87,6 +87,11 @@ function createPreference(view: STORAGE_VIEWS = STORAGE_VIEWS.COLUMNS) {}}+const renderHeader = () =>+ render(+ <FileExplorerHeader itemSearchString="" setItemSearchString={vi.fn()} onFilesUpload={vi.fn()} />+ )+describe('FileExplorerHeader', () => {beforeEach(() => {mockTrack.mockReset()@@ -101,18 +106,13 @@ describe('FileExplorerHeader', () => {mockUseAsyncCheckPermissions.mockReturnValue({ can: true })})- it('does not render folder breadcrumbs in column view and places Navigate before Reload', () => {- render(- <FileExplorerHeader- itemSearchString=""- setItemSearchString={vi.fn()}- onFilesUpload={vi.fn()}- />- )+ it('in column view, shows Navigate before Reload with no breadcrumbs or go-up button', () => {+ renderHeader()expect(screen.queryByRole('button', { name: 'my-bucket' })).not.toBeInTheDocument()expect(screen.queryByRole('button', { name: 'images' })).not.toBeInTheDocument()expect(screen.queryByText('2024')).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Go up one level' })).not.toBeInTheDocument()const navigateButton = screen.getByRole('button', { name: 'Navigate' })const reloadButton = screen.getByRole('button', { name: 'Reload' })@@ -122,33 +122,19 @@ describe('FileExplorerHeader', () => {).toBeTruthy()})- it('renders a go-up button to the left of search when not at bucket root', () => {+ it('in list view below the bucket root, replaces Navigate with a go-up button that goes up a level', async () => {mockUseStoragePreference.mockReturnValue(createPreference(STORAGE_VIEWS.LIST))- render(- <FileExplorerHeader- itemSearchString=""- setItemSearchString={vi.fn()}- onFilesUpload={vi.fn()}- />- )+ renderHeader()- expect(screen.getByRole('button', { name: 'Go up one level' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Navigate' })).not.toBeInTheDocument()expect(screen.queryByRole('button', { name: 'my-bucket' })).not.toBeInTheDocument()expect(screen.queryByRole('button', { name: 'images' })).not.toBeInTheDocument()expect(screen.getByPlaceholderText('Search in 2024...')).toBeInTheDocument()- })- it('does not render the go-up button in column view when not at bucket root', () => {- render(- <FileExplorerHeader- itemSearchString=""- setItemSearchString={vi.fn()}- onFilesUpload={vi.fn()}- />- )+ await userEvent.click(screen.getByRole('button', { name: 'Go up one level' }))- expect(screen.queryByRole('button', { name: 'Go up one level' })).not.toBeInTheDocument()+ expect(mockGoUpOneLevel).toHaveBeenCalled()})it('does not render the go-up button at bucket root', () => {@@ -157,67 +143,19 @@ describe('FileExplorerHeader', () => {mockUseStorageExplorerStateSnapshot.mockReturnValue(snapshot)mockUseStoragePreference.mockReturnValue(createPreference(STORAGE_VIEWS.LIST))- render(- <FileExplorerHeader- itemSearchString=""- setItemSearchString={vi.fn()}- onFilesUpload={vi.fn()}- />- )+ renderHeader()expect(screen.queryByRole('button', { name: 'Go up one level' })).not.toBeInTheDocument()expect(screen.getByPlaceholderText('Search in root directory...')).toBeInTheDocument()})- it('goes up one folder level when the go-up button is clicked', async () => {- const snapshot = createSnapshot()- mockUseStorageExplorerStateSnapshot.mockReturnValue(snapshot)- mockUseStoragePreference.mockReturnValue(createPreference(STORAGE_VIEWS.LIST))-- render(- <FileExplorerHeader- itemSearchString=""- setItemSearchString={vi.fn()}- onFilesUpload={vi.fn()}- />- )-- await userEvent.click(screen.getByRole('button', { name: 'Go up one level' }))-- expect(mockGoUpOneLevel).toHaveBeenCalled()- })-- it('opens path edit mode from Navigate and tracks the click', async () => {- render(- <FileExplorerHeader- itemSearchString=""- setItemSearchString={vi.fn()}- onFilesUpload={vi.fn()}- />- )+ it('opens path edit mode prefilled with the current path, then navigates to a submitted path', async () => {+ renderHeader()await userEvent.click(screen.getByRole('button', { name: 'Navigate' }))expect(mockTrack).toHaveBeenCalledWith('storage_explorer_navigate_clicked')- expect(screen.getByRole('dialog')).toBeInTheDocument()expect(screen.getByText('Navigate to folder')).toBeInTheDocument()- expect(screen.getByDisplayValue('images/2024')).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Navigate' })).toBeInTheDocument()- })-- it('submits a path, tracks the submission, and navigates to it', async () => {- const snapshot = createSnapshot()- mockUseStorageExplorerStateSnapshot.mockReturnValue(snapshot)-- render(- <FileExplorerHeader- itemSearchString=""- setItemSearchString={vi.fn()}- onFilesUpload={vi.fn()}- />- )-- await userEvent.click(screen.getByRole('button', { name: 'Navigate' }))const input = screen.getByDisplayValue('images/2024')await userEvent.clear(input)@@ -230,47 +168,19 @@ describe('FileExplorerHeader', () => {await waitFor(() => {expect(mockTrack).toHaveBeenCalledWith('storage_explorer_navigate_submitted')})-- expect(mockTrack).toHaveBeenCalledWith('storage_explorer_navigate_clicked')})it('navigates to bucket root without tracking a folder-path submission', async () => {- const snapshot = createSnapshot()- mockUseStorageExplorerStateSnapshot.mockReturnValue(snapshot)-- render(- <FileExplorerHeader- itemSearchString=""- setItemSearchString={vi.fn()}- onFilesUpload={vi.fn()}- />- )+ renderHeader()await userEvent.click(screen.getByRole('button', { name: 'Navigate' }))- const input = screen.getByDisplayValue('images/2024')- await userEvent.clear(input)+ await userEvent.clear(screen.getByDisplayValue('images/2024'))await userEvent.click(screen.getByRole('button', { name: 'Navigate' }))await waitFor(() => {expect(mockNavigateToPath).toHaveBeenCalledWith([])})-- expect(mockTrack).toHaveBeenCalledWith('storage_explorer_navigate_clicked')expect(mockTrack).not.toHaveBeenCalledWith('storage_explorer_navigate_submitted')})-- it('does not render Navigate in list view', () => {- mockUseStoragePreference.mockReturnValue(createPreference(STORAGE_VIEWS.LIST))-- render(- <FileExplorerHeader- itemSearchString=""- setItemSearchString={vi.fn()}- onFilesUpload={vi.fn()}- />- )-- expect(screen.queryByRole('button', { name: 'Navigate' })).not.toBeInTheDocument()- })})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.test.tsxindex c518cf75c3e..42c42afce56 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.test.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.test.tsx@@ -104,17 +104,19 @@ describe('FileExplorerHeaderSelection', () => {expect(actions.setItemsToPurge).not.toHaveBeenCalled()})- it('drops the permanent delete on a suspended bucket, where deleting is already permanent', () => {- selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }-- render(<FileExplorerHeaderSelection />)-- expect(screen.getByRole('button', { name: 'Delete' })).toBeInTheDocument()- expect(screen.queryByRole('button', { name: 'Delete permanently' })).not.toBeInTheDocument()- })-- it('drops it on an unversioned bucket too, so the bar never says the same thing twice', () => {- selectedBucket.current = { id: 'my-bucket', name: 'my-bucket', public: false }+ it.each([+ {+ // Deleting is already permanent once versioning is suspended+ scenario: 'a suspended bucket',+ bucket: { id: 'my-bucket', name: 'my-bucket', public: false, versioning_status: 'SUSPENDED' },+ },+ {+ // So the bar never says the same thing twice+ scenario: 'an unversioned bucket',+ bucket: { id: 'my-bucket', name: 'my-bucket', public: false },+ },+ ])('drops the permanent delete on $scenario', ({ bucket }) => {+ selectedBucket.current = bucketrender(<FileExplorerHeaderSelection />)diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.test.tsxindex 9dca4f2ad00..5e588ee9e02 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.test.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.test.tsx@@ -96,32 +96,23 @@ beforeEach(() => {})describe('FileExplorerRow', () => {- it('offers both the relative path and the dashboard URL for a file', async () => {- render(- <FileExplorerRow- item={item({ id: 'f1' })}- index={0}- view={STORAGE_VIEWS.COLUMNS}- columnIndex={0}- selectedItems={[]}- />- )- await userEvent.click(screen.getByRole('button', { name: 'photo.png actions' }))- expect(await screen.findByText('Copy relative path')).toBeInTheDocument()- expect(screen.getByText('Copy link')).toBeInTheDocument()- })-- it('offers both the relative path and the dashboard URL for a folder', async () => {+ it.each([+ { kind: 'file', rowItem: item({ id: 'f1' }) },+ {+ kind: 'folder',+ rowItem: item({ name: 'avatars', type: STORAGE_ROW_TYPES.FOLDER, metadata: null }),+ },+ ])('offers both the relative path and the dashboard URL for a $kind', async ({ rowItem }) => {render(<FileExplorerRow- item={item({ name: 'avatars', type: STORAGE_ROW_TYPES.FOLDER, metadata: null })}+ item={rowItem}index={0}view={STORAGE_VIEWS.COLUMNS}columnIndex={0}selectedItems={[]}/>)- await userEvent.click(screen.getByRole('button', { name: 'avatars actions' }))+ await userEvent.click(screen.getByRole('button', { name: `${rowItem.name} actions` }))expect(await screen.findByText('Copy relative path')).toBeInTheDocument()expect(screen.getByText('Copy link')).toBeInTheDocument()expect(screen.queryByText('Copy path to folder')).not.toBeInTheDocument()@@ -209,34 +200,24 @@ describe('FileExplorerRow', () => {expect(screen.getByText('Delete permanently')).toBeInTheDocument()})- it('deletes rather than archives on a suspended bucket', async () => {- versioningEnabled.current = true- selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }-- await openFileMenu({ is_versioned: false })-- // Suspended can't archive, so there is no soft delete and nothing to purge from here.- expect(screen.getByText('Delete')).toBeInTheDocument()- expect(screen.queryByText('Archive')).not.toBeInTheDocument()- expect(screen.queryByText('Delete permanently')).not.toBeInTheDocument()- // The write overwrites in place, so it is not a new version.- expect(screen.getByText('Replace file')).toBeInTheDocument()- expect(screen.queryByText('Upload new version')).not.toBeInTheDocument()- })-- it('still reads "Replace file" for a file that predates the suspension', async () => {- versioningEnabled.current = true- selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }-- await openFileMenu({ is_versioned: true })-- // This write does retain one last version, but the label names the action taken,- // not the retention behind it. The version history is where that gets explained.- expect(screen.getByText('Replace file')).toBeInTheDocument()- expect(screen.queryByText('Upload new version')).not.toBeInTheDocument()- expect(screen.getByText('Delete')).toBeInTheDocument()- expect(screen.queryByText('Archive')).not.toBeInTheDocument()- })+ // A file that predates the suspension (is_versioned) does retain one last version on+ // write, but the label names the action taken, not the retention behind it.+ it.each([false, true])(+ 'deletes rather than archives and replaces in place on a suspended bucket (is_versioned: %s)',+ async (isVersioned) => {+ versioningEnabled.current = true+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }++ await openFileMenu({ is_versioned: isVersioned })++ // Suspended can't archive, so there is no soft delete and nothing to purge from here.+ expect(screen.getByText('Delete')).toBeInTheDocument()+ expect(screen.queryByText('Archive')).not.toBeInTheDocument()+ expect(screen.queryByText('Delete permanently')).not.toBeInTheDocument()+ expect(screen.getByText('Replace file')).toBeInTheDocument()+ expect(screen.queryByText('Upload new version')).not.toBeInTheDocument()+ }+ )it('ignores is_versioned on a disabled bucket', async () => {versioningEnabled.current = truediff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.test.tsxindex 6dcf66c9229..7f2863fd351 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.test.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.test.tsx@@ -147,20 +147,16 @@ describe('MoveItemsModal', () => {mockObjectsList()})- it('names the item being moved and defaults the destination to the bucket root', async () => {+ it('names the item, lists folders only, and blocks moving into the current folder', async () => {renderModal()expect(await screen.findByText('Move avatar.png')).toBeInTheDocument()expect(await screen.findByRole('button', { name: 'photos' })).toBeInTheDocument()- expect(screen.getByText('avatars', { selector: 'span.font-mono' })).toBeInTheDocument()- })-- it('lists folders only, leaving files out entirely', async () => {- renderModal()-- await screen.findByRole('button', { name: 'photos' })expect(screen.getByRole('button', { name: 'invoices' })).toBeInTheDocument()expect(screen.queryByText('avatar.png')).not.toBeInTheDocument()+ // Destination defaults to the bucket root, which is where the item already lives+ expect(screen.getByText('avatars', { selector: 'span.font-mono' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Move to avatars' })).toBeAriaDisabled()})it('marks the destination folder in the search results', async () => {@@ -170,7 +166,8 @@ describe('MoveItemsModal', () => {await user.click(await screen.findByRole('button', { name: 'photos' }))await screen.findByRole('button', { name: 'Move to photos' })- await user.type(screen.getByPlaceholderText('Search folders in avatars...'), 'photos')+ await user.click(screen.getByPlaceholderText('Search folders in avatars...'))+ await user.paste('photos')expect(await screen.findByRole('button', { name: 'photos in avatars' })).toHaveAttribute('aria-current',@@ -226,27 +223,6 @@ describe('MoveItemsModal', () => {expect(await screen.findByRole('button', { name: 'Move to photos' })).toBeInTheDocument()})- it('keeps a shallow path fully visible', async () => {- const user = userEvent.setup()- renderModal()-- await user.click(await screen.findByRole('button', { name: 'photos' }))- await screen.findByRole('button', { name: 'Move to photos' })-- const breadcrumb = screen.getByRole('navigation', { name: 'breadcrumb' })- expect(within(breadcrumb).getByText('photos')).toBeInTheDocument()- expect(- within(breadcrumb).queryByLabelText('Show the folders in between')- ).not.toBeInTheDocument()- })-- it('blocks moving items into the folder they are already in', async () => {- renderModal()-- const moveButton = await screen.findByRole('button', { name: 'Move to avatars' })- expect(moveButton).toBeAriaDisabled()- })-it('opens a folder on click and moves items into it', async () => {const user = userEvent.setup()const { onSelectMove } = renderModal()@@ -261,38 +237,37 @@ describe('MoveItemsModal', () => {expect(onSelectMove).toHaveBeenCalledWith('photos')})- it('navigates back up through the breadcrumb', async () => {+ it('keeps a shallow path fully visible and navigates back up through the breadcrumb', async () => {const user = userEvent.setup()renderModal()await user.click(await screen.findByRole('button', { name: 'photos' }))await screen.findByRole('button', { name: 'Move to photos' })+ // A shallow path stays fully visible, with nothing collapsedconst breadcrumb = screen.getByRole('navigation', { name: 'breadcrumb' })+ expect(within(breadcrumb).getByText('photos')).toBeInTheDocument()+ expect(+ within(breadcrumb).queryByLabelText('Show the folders in between')+ ).not.toBeInTheDocument()+await user.click(within(breadcrumb).getByRole('button', { name: 'avatars' }))expect(await screen.findByRole('button', { name: 'Move to avatars' })).toBeInTheDocument()})- it('swaps the listing for matching folders while searching', async () => {+ it('swaps the listing for matching folders while searching and selects one as the destination', async () => {const user = userEvent.setup()- renderModal()+ const { onSelectMove } = renderModal()await screen.findByRole('button', { name: 'photos' })- await user.type(screen.getByPlaceholderText('Search folders in avatars...'), '2024')+ await user.click(screen.getByPlaceholderText('Search folders in avatars...'))+ await user.paste('2024')- expect(await screen.findByRole('button', { name: '2024 in photos' })).toBeInTheDocument()+ const result = await screen.findByRole('button', { name: '2024 in photos' })await waitFor(() => expect(screen.queryByText('invoices')).not.toBeInTheDocument())- })-- it('selects a searched folder as the destination', async () => {- const user = userEvent.setup()- const { onSelectMove } = renderModal()-- await screen.findByRole('button', { name: 'photos' })- await user.type(screen.getByPlaceholderText('Search folders in avatars...'), '2024')- await user.click(await screen.findByRole('button', { name: '2024 in photos' }))+ await user.click(result)await user.click(await screen.findByRole('button', { name: 'Move to 2024' }))expect(onSelectMove).toHaveBeenCalledWith('photos/2024')diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.utils.test.tsindex f0eeb0ab1b6..744f9e02ff8 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.utils.test.ts+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.utils.test.ts@@ -108,7 +108,7 @@ describe('filterFoldersBySearch', () => {expect(filterFoldersBySearch(folders, ' ')).toEqual([])})- it('matches names case insensitively', () => {+ it('ranks exact names first, then prefixes, then substrings, case insensitively', () => {expect(filterFoldersBySearch(folders, 'PHOTOS').map((folder) => folder.path)).toEqual(['archive/photos','photos',@@ -116,14 +116,6 @@ describe('filterFoldersBySearch', () => {])})- it('ranks exact names first, then prefixes, then substrings', () => {- expect(filterFoldersBySearch(folders, 'photos').map((folder) => folder.path)).toEqual([- 'archive/photos',- 'photos',- 'photos-2024',- ])- })-it('matches on the folder path when the name does not match', () => {expect(filterFoldersBySearch(folders, 'archive').map((folder) => folder.path)).toEqual(['archive/photos',@@ -150,12 +142,11 @@ describe('toFolders', () => {{ id: null, name: 'videos' },] as Parameters<typeof toFolders>[0]- it('drops files and keeps folders in order', () => {- expect(toFolders(objects, '').map((folder) => folder.name)).toEqual(['photos', 'videos'])- })-- it('builds paths relative to the bucket root', () => {- expect(toFolders(objects, '').map((folder) => folder.path)).toEqual(['photos', 'videos'])+ it('drops files and keeps folders in order, with paths relative to the bucket root', () => {+ expect(toFolders(objects, '')).toEqual([+ expect.objectContaining({ name: 'photos', path: 'photos' }),+ expect.objectContaining({ name: 'videos', path: 'videos' }),+ ])})it('prefixes paths with the parent folder', () => {diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.test.tsxindex 4dadec6285f..34392e2fa69 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.test.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.test.tsx@@ -144,16 +144,19 @@ describe('PreviewPane', () => {})})- it('offers Archive and a purge on an enabled bucket', async () => {+ it('offers Archive, a purge and "Upload new version" on an enabled bucket', async () => {selectedBucket.current = { ...selectedBucket.current, versioning_status: 'ENABLED' }- renderPane()+ renderPane({ is_versioned: true })expect(await screen.findByRole('button', { name: 'Archive' })).toBeInTheDocument()expect(screen.getByRole('button', { name: 'More delete options' })).toBeInTheDocument()expect(screen.queryByRole('button', { name: 'Delete file' })).not.toBeInTheDocument()+ expect(await screen.findByRole('button', { name: 'Upload new version' })).toBeInTheDocument()})- it('offers a single Delete on a suspended bucket', async () => {+ it('offers a single Delete and no version history for a file written while suspended', async () => {+ // The listing drops unversioned rows, so a file with no history comes back empty.+ mockVersionListing([])selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }renderPane({ is_versioned: false })@@ -161,93 +164,55 @@ describe('PreviewPane', () => {expect(await screen.findByRole('button', { name: 'Delete file' })).toBeInTheDocument()expect(screen.queryByRole('button', { name: 'Archive' })).not.toBeInTheDocument()expect(screen.queryByRole('button', { name: 'More delete options' })).not.toBeInTheDocument()+ expect(screen.queryByText('Versions')).not.toBeInTheDocument()})- describe('replace action label', () => {- it('reads "Upload new version" on an enabled bucket', async () => {- selectedBucket.current = { ...selectedBucket.current, versioning_status: 'ENABLED' }- renderPane({ is_versioned: true })-- expect(await screen.findByRole('button', { name: 'Upload new version' })).toBeInTheDocument()- })-- it('reads "Replace file" on a suspended bucket, even for a file that still retains one', async () => {- selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }- renderPane({ is_versioned: true })-- // The label names the action, not the retention. The Versions section explains that.- expect(await screen.findByRole('button', { name: 'Replace file' })).toBeInTheDocument()- expect(screen.queryByRole('button', { name: 'Upload new version' })).not.toBeInTheDocument()- })-- it('reads "Replace file" on a disabled bucket', async () => {- mockVersionListing([])- selectedBucket.current = { ...selectedBucket.current, versioning_status: 'DISABLED' }- renderPane({ is_versioned: false })+ it('reads "Replace file" and shows version history for a versioned file on a suspended bucket', async () => {+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }+ renderPane({ is_versioned: true })- expect(await screen.findByRole('button', { name: 'Replace file' })).toBeInTheDocument()- })+ // The label names the action, not the retention. The Versions section explains that.+ expect(await screen.findByRole('button', { name: 'Replace file' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Upload new version' })).not.toBeInTheDocument()+ expect(await screen.findByText('Versions')).toBeInTheDocument()+ expect(await screen.findByText(/retains the current version one last time/)).toBeInTheDocument()})- describe('version history visibility', () => {- it('shows it for a versioned file on a suspended bucket', async () => {- selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }- renderPane({ is_versioned: true })-- expect(await screen.findByText('Versions')).toBeInTheDocument()- expect(- await screen.findByText(/retains the current version one last time/)- ).toBeInTheDocument()- })-- it('hides it for a file written while versioning was suspended', async () => {- // The listing drops unversioned rows, so a file with no history comes back empty.- mockVersionListing([])- selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }- renderPane({ is_versioned: false })-- expect(await screen.findByRole('button', { name: 'Delete file' })).toBeInTheDocument()- expect(screen.queryByText('Versions')).not.toBeInTheDocument()- })-- it('still shows it when a retained version sits under an unversioned current', async () => {- // Hiding here would strand a version the user can still restore.- mockVersionListing(NONCURRENT_UNDER_UNVERSIONED_CURRENT)- selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }- renderPane({ is_versioned: false })-- expect(await screen.findByText('Versions')).toBeInTheDocument()- expect(await screen.findByText(/overwrites it in place/)).toBeInTheDocument()- })+ it('still shows version history when a retained version sits under an unversioned current', async () => {+ // Hiding here would strand a version the user can still restore.+ mockVersionListing(NONCURRENT_UNDER_UNVERSIONED_CURRENT)+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }+ renderPane({ is_versioned: false })- it('hides it on a disabled bucket', async () => {- mockVersionListing([])- selectedBucket.current = { ...selectedBucket.current, versioning_status: 'DISABLED' }- renderPane({ is_versioned: false })+ expect(await screen.findByText('Versions')).toBeInTheDocument()+ expect(await screen.findByText(/overwrites it in place/)).toBeInTheDocument()+ })- expect(await screen.findByRole('button', { name: 'Delete file' })).toBeInTheDocument()- expect(screen.queryByText('Versions')).not.toBeInTheDocument()- })+ it('reads "Replace file" and hides version history on a disabled bucket', async () => {+ mockVersionListing([])+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'DISABLED' }+ renderPane({ is_versioned: false })- it('shows it for every file on an enabled bucket, even one written before versioning', async () => {- mockVersionListing([])- selectedBucket.current = { ...selectedBucket.current, versioning_status: 'ENABLED' }- renderPane({ is_versioned: false })+ expect(await screen.findByRole('button', { name: 'Replace file' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Delete file' })).toBeInTheDocument()+ expect(screen.queryByText('Versions')).not.toBeInTheDocument()+ })- // The next write will version it, so the history has to be on offer.- expect(await screen.findByText('Versions')).toBeInTheDocument()- })+ it('shows version history for every file on an enabled bucket, even one written before versioning', async () => {+ mockVersionListing([])+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'ENABLED' }+ renderPane({ is_versioned: false })- it('displays the file base name when it is not a deep path', async () => {- selectedBucket.current = { ...selectedBucket.current, versioning_status: 'ENABLED' }- renderPane({ name: 'photo.png' })- expect(await screen.findByText('photo.png')).toBeInTheDocument()- })+ // The next write will version it, so the history has to be on offer.+ expect(await screen.findByText('Versions')).toBeInTheDocument()+ })- it('displays the file base name when it is a deep path', async () => {+ it.each(['photo.png', 'nested/deep/photo.png'])(+ 'displays the file base name for %s',+ async (name) => {selectedBucket.current = { ...selectedBucket.current, versioning_status: 'ENABLED' }- renderPane({ name: 'nested/deep/photo.png' })+ renderPane({ name })expect(await screen.findByText('photo.png')).toBeInTheDocument()- })- })+ }+ )})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.test.tsindex e452401cc82..3ec1f3b7369 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.test.ts+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { toast } from 'sonner'import { copyToClipboard } from 'ui'import { beforeEach, describe, expect, it, vi } from 'vitest'@@ -50,70 +51,36 @@ function makeFolder(name: string): StorageItem {}describe('validateFolderName', () => {- describe('valid names', () => {- it('accepts plain alphanumeric names', () => {- expect(validateFolderName('myfolder')).toBeNull()- expect(validateFolderName('MyFolder123')).toBeNull()- })-- it('accepts names with underscores and hyphens', () => {- expect(validateFolderName('my_folder')).toBeNull()- expect(validateFolderName('my-folder')).toBeNull()- })-- it('accepts names with dots', () => {- expect(validateFolderName('my.folder')).toBeNull()- })-- it('accepts names with spaces', () => {- expect(validateFolderName('my folder')).toBeNull()- })-- it('accepts names with allowed special characters', () => {- expect(validateFolderName('folder!')).toBeNull()- expect(validateFolderName("folder'")).toBeNull()- expect(validateFolderName('folder(1)')).toBeNull()- expect(validateFolderName('folder*')).toBeNull()- expect(validateFolderName('folder&name')).toBeNull()- expect(validateFolderName('folder$name')).toBeNull()- expect(validateFolderName('folder@name')).toBeNull()- expect(validateFolderName('folder=name')).toBeNull()- expect(validateFolderName('folder;name')).toBeNull()- expect(validateFolderName('folder:name')).toBeNull()- expect(validateFolderName('folder+name')).toBeNull()- expect(validateFolderName('folder,name')).toBeNull()- expect(validateFolderName('folder?name')).toBeNull()- })-- it('accepts names with forward slashes', () => {- expect(validateFolderName('parent/child')).toBeNull()- })-- it('accepts an empty string', () => {- expect(validateFolderName('')).toBeNull()- })- })-- describe('invalid names', () => {- it('rejects a name containing #', () => {- const result = validateFolderName('my#folder')- expect(result).toBe('Folder name cannot contain the "#" character')- })-- it('rejects a name containing %', () => {- const result = validateFolderName('my%folder')- expect(result).toBe('Folder name cannot contain the "%" character')- })-- it('rejects a name containing ^', () => {- const result = validateFolderName('my^folder')- expect(result).toBe('Folder name cannot contain the "^" character')- })-- it('rejects a name containing [', () => {- const result = validateFolderName('my[folder')- expect(result).toBe('Folder name cannot contain the "[" character')- })+ it.each([+ 'myfolder',+ 'MyFolder123',+ 'my_folder',+ 'my-folder',+ 'my.folder',+ 'my folder',+ 'folder!',+ "folder'",+ 'folder(1)',+ 'folder*',+ 'folder&name',+ 'folder$name',+ 'folder@name',+ 'folder=name',+ 'folder;name',+ 'folder:name',+ 'folder+name',+ 'folder,name',+ 'folder?name',+ 'parent/child',+ '',+ ])('accepts %j', (name) => {+ expect(validateFolderName(name)).toBeNull()+ })++ it.each(['#', '%', '^', '['])('rejects a name containing %s', (char) => {+ expect(validateFolderName(`my${char}folder`)).toBe(+ `Folder name cannot contain the "${char}" character`+ )})})@@ -154,11 +121,8 @@ describe('getPathAlongFoldersToIndex', () => {expect(getPathAlongFoldersToIndex({ openedFolders }, 0)).toBe('')})- it('returns the first folder name for index 1', () => {- expect(getPathAlongFoldersToIndex({ openedFolders }, 1)).toBe('images')- })-it('returns folders joined up to (not including) the given index', () => {+ expect(getPathAlongFoldersToIndex({ openedFolders }, 1)).toBe('images')expect(getPathAlongFoldersToIndex({ openedFolders }, 2)).toBe('images/2024')expect(getPathAlongFoldersToIndex({ openedFolders }, 3)).toBe('images/2024/january')})@@ -234,11 +198,6 @@ describe('sanitizeNameForDuplicateInColumn', () => {sanitizeNameForDuplicateInColumn(state, { name: 'file.txt', reservedNames: ['FILE.TXT'] })).toBeNull()})-- it('leaves callers that pass none exactly as they were', () => {- const state = makeState([[{ name: 'file.txt' }]])- expect(sanitizeNameForDuplicateInColumn(state, { name: 'other.txt' })).toBe('other.txt')- })})describe('columnIndex', () => {@@ -264,16 +223,6 @@ describe('sanitizeNameForDuplicateInColumn', () => {'file.txt')})-- it('detects a conflict in the first column when columnIndex is 0', () => {- // col 0 has 'file.txt' → conflict- expect(sanitizeNameForDuplicateInColumn(state, { name: 'other.txt', columnIndex: 0 })).toBe(- 'other.txt'- ) // 'other.txt' is not in col 0- expect(- sanitizeNameForDuplicateInColumn(state, { name: 'file.txt', columnIndex: 0 })- ).toBeNull()- })})describe('autofix: false (default)', () => {@@ -391,12 +340,6 @@ describe('getStoragePathForItem', () => {'avatars/2024')})-- it('omits the bucket name so the value works with storage.from(bucket)', () => {- const openedFolders = [makeFolder('avatars')]- const path = getStoragePathForItem(openedFolders, { ...makeFile('a.png'), columnIndex: 1 })- expect(path.startsWith('my-bucket')).toBe(false)- })})describe('getStorageExplorerUrlForItem', () => {diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorerNavigation.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorerNavigation.test.tsxindex f5639d88ee3..2efd41c7436 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorerNavigation.test.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorerNavigation.test.tsx@@ -219,30 +219,19 @@ describe('StorageExplorerNavigation', () => {expect(update.options.history).toBe('replace')})- it('leaves ?preview alone when the listing is incomplete', async () => {- // The file may simply be on a later page — dropping the param would lose the deep link.+ it('keeps ?preview while the listing is incomplete, and resolves it once a later page brings the file in', async () => {+ // The file sits beyond the first LIMIT-sized page, so it is absent from the initial+ // listing. Dropping the param would lose the deep link; instead it is kept, and the+ // preview opens when pagination loads it.const snapshot = createSnapshot({columns: [makeColumn('my-bucket', [makeFile('other.png')], true)],})mockUseStorageExplorerStateSnapshot.mockReturnValue(snapshot)- const { onUrlUpdate } = renderWithProvider({ searchParams: '?preview=a.png' })-+ const { rerender, onUrlUpdate } = renderWithProvider({ searchParams: '?preview=a.png' })await Promise.resolve()expect(onUrlUpdate).not.toHaveBeenCalled()expect(snapshot.setSelectedFilePreview).not.toHaveBeenCalled()- })-- it('resolves ?preview once a later page brings the file in', async () => {- // The file sits beyond the first LIMIT-sized page, so it is absent from the initial- // listing. The param is kept, and the preview opens when pagination loads it.- const snapshot = createSnapshot({- columns: [makeColumn('my-bucket', [makeFile('other.png')], true)],- })- mockUseStorageExplorerStateSnapshot.mockReturnValue(snapshot)-- const { rerender } = renderWithProvider({ searchParams: '?preview=a.png' })- expect(snapshot.setSelectedFilePreview).not.toHaveBeenCalled()mockUseStorageExplorerStateSnapshot.mockReturnValue({...snapshot,diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.test.tsxindex 6b907c3de83..6e558e588f2 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.test.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.test.tsx@@ -24,6 +24,7 @@ const renderModal = (conflicts: Partial<UploadConflicts>) => {return { onCancel, onConfirm }}+// Copy variants (counts, archived, suspended wording) are covered by UploadConflictModal.utils.test.tsdescribe('UploadConflictModal', () => {it('stays closed when nothing clashes', () => {renderModal({})@@ -75,22 +76,7 @@ describe('UploadConflictModal', () => {expect(onConfirm).not.toHaveBeenCalled()})- it('says the retention only holds once when versioning is suspended', () => {- renderModal({ liveNames: ['photo.png'], isVersioningSuspended: true })-- expect(screen.getByText('Replace existing file')).toBeInTheDocument()- expect(screen.getByText(/one last time/)).toBeInTheDocument()- })-describe('archived conflicts', () => {- it('offers a restore rather than a replace', () => {- renderModal({ archivedNames: ['icon-1.svg'] })-- expect(screen.getByText('icon-1.svg already exists and is archived')).toBeInTheDocument()- expect(screen.getByText('Restore and add a new version')).toBeInTheDocument()- expect(screen.queryByText('Replace existing file')).not.toBeInTheDocument()- })-it('still reports the choice as a replace, which is what the upload does', async () => {const { onConfirm } = renderModal({ archivedNames: ['icon-1.svg'] })diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.test.tsxindex 8a2638b882c..fb5f37398f4 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.test.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.test.tsx@@ -86,7 +86,10 @@ describe('VersionHistory', () => {renderHistory()- await userEvent.click(await screen.findByRole('button', { name: /Actions for version/ }))+ const versionActions = await screen.findByRole('button', { name: /Actions for version/ })+ // No suspended notice on an enabled bucket+ expect(screen.queryByText(/Versioning is suspended/)).not.toBeInTheDocument()+ await userEvent.click(versionActions)await userEvent.click(await screen.findByText('Restore as current'))// A restore changes the object's size, type and modified date, and the row@@ -147,17 +150,5 @@ describe('VersionHistory', () => {expect(await screen.findByText(/overwrites it in place/)).toBeInTheDocument()expect(screen.getByText(/stay retained/)).toBeInTheDocument()})-- it('stays out of the way on an enabled bucket', async () => {- addAPIMock({- method: 'post',- path: '/platform/storage/:ref/buckets/:id/objects/list',- response: () => Response.json(VERSIONS),- })- renderHistory({ versioningState: 'enabled' })-- await screen.findByRole('button', { name: /Actions for version/ })- expect(screen.queryByText(/Versioning is suspended/)).not.toBeInTheDocument()- })})})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.test.tsindex 4e4102f5be7..4f972aff101 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.test.ts+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.test.ts@@ -67,10 +67,7 @@ describe('getArchivedOverlayItems', () => {expect(row.type).toBe(STORAGE_ROW_TYPES.FILE)expect(row.archived).toEqual({ archivedObjectId: 'id-logo.svg' })expect(row.path).toBe('logo.svg')- })-- it('carries the archived size and timestamp onto the row', () => {- const [row] = overlay([], [archived('logo.svg')])+ // Carries the archived size and timestamp onto the rowexpect(row.metadata?.size).toBe(1024)expect(row.updated_at).toBe('2026-08-01T00:00:00Z')})@@ -104,12 +101,11 @@ describe('getArchivedOverlayItems', () => {expect(rows.map((r) => r.name)).toEqual(['matches'])})- it('skips a folder that already exists in the live listing', () => {- expect(overlay([], [archived('matches/final.png')], ['matches'])).toEqual([])- })-- it('skips a file that already exists in the live listing', () => {- expect(overlay([], [archived('logo.svg')], ['logo.svg'])).toEqual([])+ it.each([+ { kind: 'folder', path: 'matches/final.png', liveName: 'matches' },+ { kind: 'file', path: 'logo.svg', liveName: 'logo.svg' },+ ])('skips a $kind that already exists in the live listing', ({ path, liveName }) => {+ expect(overlay([], [archived(path)], [liveName])).toEqual([])})it('orders folders before files', () => {@@ -150,7 +146,7 @@ describe('getArchivedObjectsUnderFolder', () => {archived('matches-2026/other.png'),]- it('collects everything under the folder at any depth', () => {+ it('collects everything under the folder at any depth, but not a sibling sharing its name as a prefix', () => {const under = getArchivedObjectsUnderFolder({folderSegments: ['matches'],archivedObjects: objects,@@ -161,14 +157,6 @@ describe('getArchivedObjectsUnderFolder', () => {])})- it('does not match a sibling folder sharing the name as a prefix', () => {- const under = getArchivedObjectsUnderFolder({- folderSegments: ['matches'],- archivedObjects: [archived('matches-2026/other.png')],- })- expect(under).toEqual([])- })-it('includes the placeholder, so an empty archived folder is still actionable', () => {const under = getArchivedObjectsUnderFolder({folderSegments: ['matches'],diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/archivedVersions.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedVersions.utils.test.tsindex 43c499930d4..206a15bc770 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/archivedVersions.utils.test.ts+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedVersions.utils.test.ts@@ -20,23 +20,11 @@ const object: ArchivedObject = {}describe('getMergedArchivedVersions', () => {- it('puts the version that was live at archive time first', () => {- const [first] = getMergedArchivedVersions(object)- expect(first.versionId).toBe('v-current')- expect(first.wasCurrentAtArchive).toBe(true)- })-- it('follows it with the retained noncurrent versions, newest first', () => {- expect(getMergedArchivedVersions(object).map((v) => v.versionId)).toEqual([- 'v-current',- 'v-2',- 'v-1',- ])- })-- it('flags only the first row as having been current', () => {+ it('puts the version that was live at archive time first, then the retained versions newest first', () => {const rows = getMergedArchivedVersions(object)- expect(rows.filter((v) => v.wasCurrentAtArchive)).toHaveLength(1)+ expect(rows.map((v) => v.versionId)).toEqual(['v-current', 'v-2', 'v-1'])+ // Only the first row was current+ expect(rows.map((v) => v.wasCurrentAtArchive)).toEqual([true, false, false])})it('preserves each version’s own size and action rather than inventing them', () => {diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/pickFile.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/pickFile.test.tsindex 183842fc52f..a6d9927b9f4 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/pickFile.test.ts+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/pickFile.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { describe, expect, it, vi } from 'vitest'import { pickFile } from './pickFile'diff --git a/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.schema.test.ts b/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.schema.test.tsindex 4a963cc614c..a11764c01b4 100644--- a/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.schema.test.ts+++ b/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.schema.test.ts@@ -3,46 +3,15 @@ import { describe, expect, it } from 'vitest'import { csatSurveyParamsSchema } from './CsatSurvey.schema'describe('parseCsatSurveyParams', () => {- it('returns a valid result with the yes answer preselected', () => {- expect(- csatSurveyParamsSchema.safeParse({ conversation_id: 'cnv_1abc2', helpful: 'yes' })- ).toEqual({+ it.each([+ { helpful: 'yes', expected: true },+ { helpful: 'no', expected: false },+ { helpful: undefined, expected: true },+ { helpful: 'maybe', expected: true },+ ])('parses helpful=$helpful as $expected (defaults to yes)', ({ helpful, expected }) => {+ expect(csatSurveyParamsSchema.safeParse({ conversation_id: 'cnv_1abc2', helpful })).toEqual({success: true,- data: {- conversation_id: 'cnv_1abc2',- helpful: true,- },- })- })-- it('returns a valid result with the no answer preselected', () => {- expect(- csatSurveyParamsSchema.safeParse({ conversation_id: 'cnv_1abc2', helpful: 'no' })- ).toEqual({- success: true,- data: {- conversation_id: 'cnv_1abc2',- helpful: false,- },- })- })-- it('preselects yes when helpful is missing or unknown', () => {- expect(csatSurveyParamsSchema.safeParse({ conversation_id: 'cnv_1abc2' })).toEqual({- success: true,- data: {- conversation_id: 'cnv_1abc2',- helpful: true,- },- })- expect(- csatSurveyParamsSchema.safeParse({ conversation_id: 'cnv_1abc2', helpful: 'maybe' })- ).toEqual({- success: true,- data: {- conversation_id: 'cnv_1abc2',- helpful: true,- },+ data: { conversation_id: 'cnv_1abc2', helpful: expected },})})diff --git a/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.test.tsx b/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.test.tsxindex 3b8c77836ac..417296adb3e 100644--- a/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.test.tsx+++ b/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.test.tsx@@ -77,19 +77,6 @@ describe('CsatSurvey', () => {expect(requests[0]).toMatchObject({ conversation_id: 'cnv_1abc2', satisfied: false })})- test('defaults to yes when the link did not preselect an answer', async () => {- routerMock.setCurrentUrl('/support/csat?conversation_id=cnv_1abc2')- const requests = mockSubmit(200)-- customRender(<CsatSurvey />)-- expect(screen.getByRole('button', { name: 'Yes' })).toHaveAttribute('aria-pressed', 'true')- submitForm()-- await waitFor(() => expect(requests).toHaveLength(1))- expect(requests[0]).toMatchObject({ conversation_id: 'cnv_1abc2', satisfied: true })- })-test('shows the already-submitted error on a 409', async () => {mockSubmit(409, { message: 'This survey has already been answered' })diff --git a/apps/studio/components/interfaces/Support/SupportAssistant.utils.test.ts b/apps/studio/components/interfaces/Support/SupportAssistant.utils.test.tsindex 0ae1f599251..4374bc6aa9f 100644--- a/apps/studio/components/interfaces/Support/SupportAssistant.utils.test.ts+++ b/apps/studio/components/interfaces/Support/SupportAssistant.utils.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { SupportCategories } from '@supabase/shared-types/out/constants'import { beforeEach, describe, expect, it, vi } from 'vitest'@@ -75,12 +76,6 @@ describe('SupportAssistant utils', () => {expect(parseSupportAssistantPrompt('<support></support>')).toBeNull()})- it('round-trips a request through store/consume', () => {- storeAssistantHandoff('token-1', supportRequest)-- expect(consumeAssistantHandoff('token-1')).toEqual(supportRequest)- })-it('preserves literal percent characters in the message (no URL encoding involved)', () => {const request = { ...supportRequest, message: '100% CPU, literal %20 text' }storeAssistantHandoff('token-1', request)@@ -88,7 +83,7 @@ describe('SupportAssistant utils', () => {expect(consumeAssistantHandoff('token-1')?.message).toBe('100% CPU, literal %20 text')})- it('removes the entry after consuming it, so it cannot be replayed', () => {+ it('round-trips a request and removes the entry after consuming it, so it cannot be replayed', () => {storeAssistantHandoff('token-1', supportRequest)expect(consumeAssistantHandoff('token-1')).toEqual(supportRequest)diff --git a/apps/studio/components/interfaces/Support/SupportAssistantSuccessCard.test.tsx b/apps/studio/components/interfaces/Support/SupportAssistantSuccessCard.test.tsxindex c7440cc5706..e7586940203 100644--- a/apps/studio/components/interfaces/Support/SupportAssistantSuccessCard.test.tsx+++ b/apps/studio/components/interfaces/Support/SupportAssistantSuccessCard.test.tsx@@ -144,11 +144,11 @@ describe('SupportAssistantSuccessCard', () => {})it('shows a loading preview before the assistant responds', async () => {- const { container } = render(<SupportAssistantSuccessCard request={supportRequest} />)+ render(<SupportAssistantSuccessCard request={supportRequest} />)expect(await screen.findByRole('heading', { name: 'While you wait' })).toBeInTheDocument()expect(screen.getByRole('button', { name: /open assistant response/i })).toBeInTheDocument()- expect(container.querySelectorAll('.animate-pulse').length).toBeGreaterThan(0)+ expect(screen.queryByTestId('assistant-preview-message')).not.toBeInTheDocument()})it('renders the full assistant response preview inside the clipped content area', async () => {@@ -252,18 +252,6 @@ describe('SupportAssistantSuccessCard', () => {expect(mockSyncSupportChatToFront).toHaveBeenCalledTimes(1)})- it('opens the generated assistant chat with keyboard activation', async () => {- const user = userEvent.setup()- render(<SupportAssistantSuccessCard request={supportRequest} />)-- const button = await screen.findByRole('button', { name: /open assistant response/i })- button.focus()- await user.keyboard('{Enter}')-- expect(mockSelectChat).toHaveBeenCalledWith('chat-1')- expect(mockOpenSidebar).toHaveBeenCalledWith('ai-assistant')- })-it('does not render or create a chat when no project is selected', () => {render(<SupportAssistantSuccessCarddiff --git a/apps/studio/components/interfaces/Support/SupportForm.utils.test.ts b/apps/studio/components/interfaces/Support/SupportForm.utils.test.tsindex c2d71ab5fb0..94aa01f8f93 100644--- a/apps/studio/components/interfaces/Support/SupportForm.utils.test.ts+++ b/apps/studio/components/interfaces/Support/SupportForm.utils.test.ts@@ -8,20 +8,11 @@ vi.mock('@/data/projects/project-detail-query', () => ({}))describe('createSupportFormUrl', () => {- it('returns base URL with no params', () => {+ it('returns the base URL without a bare ? when there are no params', () => {expect(createSupportFormUrl({})).toBe('/support/new')})- it('does not append a bare ? when params are empty', () => {- expect(createSupportFormUrl({})).not.toContain('?')- })-it('includes provided params in the query string', () => {- const url = createSupportFormUrl({ projectRef: 'my-project' })- expect(url).toContain('projectRef=my-project')- })-- it('includes multiple params', () => {const url = createSupportFormUrl({ projectRef: 'my-project', subject: 'help' })expect(url).toContain('projectRef=my-project')expect(url).toContain('subject=help')diff --git a/apps/studio/components/interfaces/Support/__tests__/SupportFormPage.test.tsx b/apps/studio/components/interfaces/Support/__tests__/SupportFormPage.test.tsxindex b739b49fa71..4552caa0759 100644--- a/apps/studio/components/interfaces/Support/__tests__/SupportFormPage.test.tsx+++ b/apps/studio/components/interfaces/Support/__tests__/SupportFormPage.test.tsx@@ -419,15 +419,9 @@ describe('SupportFormPage', () => {generateAttachmentUrlSpy = vi.fn()mswServer.use(- http.post('*/rest/v1/rpc/docs_search_fts', async () => {- return HttpResponse.json([])- }),- http.post('*/rest/v1/rpc/docs_search_fts_nimbus', async () => {- return HttpResponse.json([])- }),- http.post('*/functions/v1/search-embeddings', async () => {- return HttpResponse.json([])- }),+ // Docs suggestions search as the subject is typed+ http.post('*/api/search/fts', () => HttpResponse.json([])),+ http.post('*/api/search/embeddings', () => HttpResponse.json([])),http.post('http://localhost:3000/api/generate-attachment-url', async ({ request }) => {const body = (await request.json()) as {bucket?: string@@ -646,7 +640,7 @@ describe('SupportFormPage', () => {)})- test('loading a URL with no project slug falls back to first organization and project', async () => {+ test('loading a URL with no project slug falls back to first organization and project, and suggests the AI Assistant', async () => {renderSupportFormPage()await waitFor(@@ -656,6 +650,7 @@ describe('SupportFormPage', () => {},{ timeout: 5_000 })+ expect(await screen.findByText('Try Supabase Assistant')).toBeInTheDocument()})test('loading a URL with explicit no project ref falls back to first organization and no project', async () => {@@ -754,83 +749,12 @@ describe('SupportFormPage', () => {)})- test('loading a URL with a message prefills the message field', async () => {+ test('loading a URL with a message, subject, and category prefills those fields', async () => {const testMessage = 'This is a test support message from URL'- Object.defineProperty(window, 'location', {- value: createMockLocation(`?message=${encodeURIComponent(testMessage)}`),- writable: true,- })-- renderSupportFormPage()-- await waitFor(() => {- expect(getMessageField(screen)).toHaveValue(testMessage)- })- })-- test('loading a URL with a subject prefills the subject field', async () => {- const testSubject = 'Test Subject'- Object.defineProperty(window, 'location', {- value: createMockLocation(`?subject=${encodeURIComponent(testSubject)}`),- writable: true,- })-- renderSupportFormPage()-- await waitFor(() => {- const subjectField = getSummaryField(screen)- expect(subjectField).toHaveValue(testSubject)- })- })-- test('loading a URL with a category prefills the category field', async () => {- const testCategory = 'Problem'- Object.defineProperty(window, 'location', {- value: createMockLocation(`?category=${encodeURIComponent(testCategory)}`),- writable: true,- })-- renderSupportFormPage()-- await waitFor(() => {- expect(getCategorySelector(screen)).toHaveTextContent('APIs and client libraries')- })- })-- test('loading a URL with a category prefills the category field (case-insensitive)', async () => {- const testCategory = 'dashboard_bug'- Object.defineProperty(window, 'location', {- value: createMockLocation(`?category=${encodeURIComponent(testCategory)}`),- writable: true,- })-- renderSupportFormPage()-- await waitFor(() => {- expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')- })- })-- test('loading a URL with an invalid category gracefully falls back', async () => {- const testCategory = 'Invalid'- Object.defineProperty(window, 'location', {- value: createMockLocation(`?category=${encodeURIComponent(testCategory)}`),- writable: true,- })-- renderSupportFormPage()-- await waitFor(() => {- expect(getCategorySelector(screen)).toHaveTextContent('Select an issue')- })- })-- test('loading a URL with multiple initial fields fills them all in', async () => {- const testCategory = 'Problem'const testSubject = 'Test Subject'Object.defineProperty(window, 'location', {value: createMockLocation(- `?category=${encodeURIComponent(testCategory)}&subject=${encodeURIComponent(testSubject)}`+ `?category=Problem&subject=${encodeURIComponent(testSubject)}&message=${encodeURIComponent(testMessage)}`),writable: true,})@@ -840,99 +764,28 @@ describe('SupportFormPage', () => {await waitFor(() => {expect(getCategorySelector(screen)).toHaveTextContent('APIs and client libraries')expect(getSummaryField(screen)).toHaveValue(testSubject)+ expect(getMessageField(screen)).toHaveValue(testMessage)})})- test('includes Sentry issue ID from URL in submission payload', async () => {- const sentryIssueId = 'mock-sentry-id'-- const submitSpy = vi.fn()- addAPIMock({- method: 'post',- path: '/platform/feedback/send',- response: async ({ request }) => {- submitSpy(await request.json())- return HttpResponse.json<SendFeedbackResponse>({ result: 'ok' })- },- })-- Object.defineProperty(window, 'location', {- value: createMockLocation(`?sid=${encodeURIComponent(sentryIssueId)}`),- writable: true,- })-- renderSupportFormPage()-- await waitFor(- () => {- expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')- expect(getProjectSelector(screen)).toHaveTextContent('Project 1')- },- { timeout: 5_000 }- )-- await selectCategoryOption(screen, 'Dashboard bug')- await waitFor(() => {- expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')- })-- await fillField(getSummaryField(screen), 'Dashboard stopped loading')- await fillField(getMessageField(screen), 'The dashboard page loads blank after login')-- await userEvent.click(getSubmitButton(screen))-- await waitFor(() => {- expect(submitSpy).toHaveBeenCalledTimes(1)- })- expect(submitSpy.mock.calls[0]?.[0]?.dashboardSentryIssueId).toBe(sentryIssueId)- }, 10_000)-- test('includes initial error message from URL in submission payload', async () => {- const initialError = 'failed to fetch user data'- const messageBody = 'The dashboard page loads blank after login'-- const submitSpy = vi.fn()- addAPIMock({- method: 'post',- path: '/platform/feedback/send',- response: async ({ request }) => {- submitSpy(await request.json())- return HttpResponse.json<SendFeedbackResponse>({ result: 'ok' })- },- })-- Object.defineProperty(window, 'location', {- value: createMockLocation(`?errorMessage=${encodeURIComponent(initialError)}`),- writable: true,- })-- renderSupportFormPage()-- await waitFor(- () => {- expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')- expect(getProjectSelector(screen)).toHaveTextContent('Project 1')- },- { timeout: 5_000 }- )-- await selectCategoryOption(screen, 'Dashboard bug')- await waitFor(() => {- expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')- })-- await fillField(getSummaryField(screen), 'Dashboard stopped loading')- await fillField(getMessageField(screen), messageBody)+ test.each([+ { category: 'dashboard_bug', expected: 'Dashboard bug' },+ { category: 'Invalid', expected: 'Select an issue' },+ ])(+ 'loading a URL with category "$category" shows "$expected" (case-insensitive, invalid falls back)',+ async ({ category, expected }) => {+ Object.defineProperty(window, 'location', {+ value: createMockLocation(`?category=${encodeURIComponent(category)}`),+ writable: true,+ })- await userEvent.click(getSubmitButton(screen))+ renderSupportFormPage()- await waitFor(() => {- expect(submitSpy).toHaveBeenCalledTimes(1)- })-- const payload = submitSpy.mock.calls[0]?.[0]- expect(payload?.message).toMatch(initialError)- }, 10_000)+ await waitFor(() => {+ expect(getCategorySelector(screen)).toHaveTextContent(expected)+ })+ }+ )test('submits support request with problem category, library, and affected services', async () => {const submitSpy = vi.fn()@@ -1128,7 +981,7 @@ describe('SupportFormPage', () => {})}, 10_000)- test('submits database unresponsive ticket with initial error', async () => {+ test('submits database unresponsive ticket with initial error and Sentry issue ID, without dashboard logs', async () => {const submitSpy = vi.fn()addAPIMock({@@ -1152,20 +1005,10 @@ describe('SupportFormPage', () => {},})- addAPIMock({- method: 'get',- path: '/platform/projects/:ref',- response: ({ params }) => {- const { ref } = params as { ref: string }- const project = mockProjects.projects.find((candidate) => candidate.ref === ref)- return project- ? HttpResponse.json<ProjectDetailResponse>(toProjectDetailResponse(project))- : HttpResponse.json<APIErrorBody>({ message: 'Project not found' }, { status: 404 })- },- })-Object.defineProperty(window, 'location', {- value: createMockLocation('?projectRef=project-3&errorMessage=Connection timeout detected'),+ value: createMockLocation(+ '?projectRef=project-3&errorMessage=Connection timeout detected&sid=mock-sentry-id'+ ),writable: true,})@@ -1189,6 +1032,9 @@ describe('SupportFormPage', () => {expect(getSeveritySelector(screen)).toHaveTextContent('Normal')})+ // Dashboard logs are only offered for dashboard bugs+ expect(getDashboardLogsToggle(screen, 'query')).not.toBeInTheDocument()+const summaryField = getSummaryField(screen)await userEvent.clear(summaryField)await userEvent.paste('Database unreachable after upgrade')@@ -1228,107 +1074,16 @@ describe('SupportFormPage', () => {expect(payload.message).toBe('Connections time out after 30 seconds\n\nError: Connection timeout detected')+ expect(payload.dashboardSentryIssueId).toBe('mock-sentry-id')+ // The attach-logs value defaults to true even while hidden, so make sure nothing was uploaded+ expect(payload.dashboardLogs).toBeUndefined()+ expect(generateAttachmentUrlSpy).not.toHaveBeenCalled()await waitFor(() => {expect(screen.getByRole('heading', { name: /support request sent/i })).toBeInTheDocument()})}, 10_000)- test('when organization changes, project selector updates to match', async () => {- renderSupportFormPage()-- await waitFor(- () => {- expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')- expect(getProjectSelector(screen)).toHaveTextContent('Project 1')- },- { timeout: 5_000 }- )-- await userEvent.click(getOrganizationSelector(screen))- await userEvent.click(screen.getByRole('option', { name: 'Organization 2' }))- await waitFor(() => {- expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 2')- })-- await waitFor(- () => {- expect(getProjectSelector(screen)).toHaveTextContent('Project 2')- },- { timeout: 5_000 }- )- })-- test('AI Assistant suggestion displays when valid project and organization are selected', async () => {- renderSupportFormPage()-- await waitFor(() => {- expect(screen.getByText('Try Supabase Assistant')).toBeInTheDocument()- })- })-- test('can upload attachments', async () => {- const url = URL as unknown as {- createObjectURL?: (obj: Blob) => string- revokeObjectURL?: (url: string) => void- }- const originalCreateObjectURL = url.createObjectURL- const originalRevokeObjectURL = url.revokeObjectURL-- let urlIndex = 0- const createObjectURLMock = vi.fn(() => {- urlIndex += 1- return `blob:mock-url-${urlIndex}`- })- const revokeObjectURLMock = vi.fn()- url.createObjectURL = createObjectURLMock- url.revokeObjectURL = revokeObjectURLMock-- let unmount: (() => void) | undefined- try {- const renderResult = renderSupportFormPage()- unmount = renderResult.unmount-- await waitFor(- () => {- expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')- },- { timeout: 5_000 }- )-- const fileInput = getAttachmentFileInput()- const firstFile = new File(['first file'], 'first.png', { type: 'image/png' })- const secondFile = new File(['second file'], 'second.jpg', { type: 'image/jpeg' })- await userEvent.upload(fileInput, [firstFile, secondFile])-- await waitFor(() => {- expect(getAttachmentRemoveButtons(screen)).toHaveLength(2)- })- expect(createObjectURLMock).toHaveBeenCalledTimes(2)-- const firstRemoveButton = getAttachmentRemoveButtons(screen)[0]- await userEvent.click(firstRemoveButton)-- await waitFor(() => {- expect(getAttachmentRemoveButtons(screen)).toHaveLength(1)- })- expect(revokeObjectURLMock).toHaveBeenCalled()-- const thirdFile = new File(['third file'], 'third.png', { type: 'image/png' })- await userEvent.upload(getAttachmentFileInput(), thirdFile)-- await waitFor(() => {- expect(getAttachmentRemoveButtons(screen)).toHaveLength(2)- })-- expect(createObjectURLMock).toHaveBeenCalled()- } finally {- unmount?.()- url.createObjectURL = originalCreateObjectURL- url.revokeObjectURL = originalRevokeObjectURL- }- })-test('cannot submit form again while it is submitting', async () => {const submission = createDeferred()const submitSpy = vi.fn()@@ -1412,148 +1167,6 @@ describe('SupportFormPage', () => {await waitFor(() => {expect(getDashboardLogsToggle(screen, 'query')).not.toBeInTheDocument()})-- await selectCategoryOption(screen, 'Dashboard bug')- await waitFor(() => {- expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')- })- const dashboardLogToggleAgain = await getDashboardLogsToggle(screen)- expect(dashboardLogToggleAgain).toBeChecked()- }, 10_000)-- test('skips dashboard log upload when toggle is disabled', async () => {- const submitSpy = vi.fn()- const upload = vi.fn(async () => ({- data: { path: 'dashboard-logs/mock.log.json' },- error: null,- }))- const createSignedUrls = vi.fn(async (paths: string[]) => ({- data: paths.map((path) => ({- signedUrl: `https://storage.example.com/${path}`,- path,- error: null,- })),- error: null,- }))-- createSupportStorageClientMock.mockReturnValue({- storage: {- from: vi.fn(() => ({- upload,- createSignedUrls,- })),- },- } as any)-- addAPIMock({- method: 'post',- path: '/platform/feedback/send',- response: async ({ request }) => {- submitSpy(await request.json())- return HttpResponse.json<SendFeedbackResponse>({ result: 'ok' })- },- })-- renderSupportFormPage()-- await waitFor(- () => {- expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')- },- { timeout: 5_000 }- )-- await selectCategoryOption(screen, 'Dashboard bug')- await waitFor(() => {- expect(getCategorySelector(screen)).toHaveTextContent('Dashboard bug')- })-- const dashboardLogToggle = await getDashboardLogsToggle(screen)- expect(dashboardLogToggle).toBeChecked()- await userEvent.click(dashboardLogToggle!)- expect(dashboardLogToggle).not.toBeChecked()-- await fillField(getSummaryField(screen), 'Dashboard charts crashing')- await fillField(getMessageField(screen), 'Charts throw error on load')-- await userEvent.click(getSubmitButton(screen))-- await waitFor(() => {- expect(submitSpy).toHaveBeenCalledTimes(1)- })-- expect(upload).not.toHaveBeenCalled()- expect(createSignedUrls).not.toHaveBeenCalled()-- const payload = submitSpy.mock.calls[0]?.[0]- expect(payload.message).toContain('Charts throw error on load')- expect(payload.message).not.toContain('Dashboard logs:')- }, 10_000)-- test('skips dashboard log upload when toggle hidden', async () => {- const submitSpy = vi.fn()- const upload = vi.fn(async () => ({- data: { path: 'dashboard-logs/mock.log.json' },- error: null,- }))- const createSignedUrls = vi.fn(async (paths: string[]) => ({- data: paths.map((path) => ({- signedUrl: `https://storage.example.com/${path}`,- path,- error: null,- })),- error: null,- }))-- createSupportStorageClientMock.mockReturnValue({- storage: {- from: vi.fn(() => ({- upload,- createSignedUrls,- })),- },- } as any)-- addAPIMock({- method: 'post',- path: '/platform/feedback/send',- response: async ({ request }) => {- submitSpy(await request.json())- return HttpResponse.json<SendFeedbackResponse>({ result: 'ok' })- },- })-- renderSupportFormPage()-- await waitFor(- () => {- expect(getOrganizationSelector(screen)).toHaveTextContent('Organization 1')- },- { timeout: 5_000 }- )-- await selectCategoryOption(screen, 'Database unresponsive')- await waitFor(() => {- expect(getCategorySelector(screen)).toHaveTextContent('Database unresponsive')- })-- expect(getDashboardLogsToggle(screen, 'query')).not.toBeInTheDocument()-- await fillField(getSummaryField(screen), 'Dashboard charts crashing')- await fillField(getMessageField(screen), 'Charts throw error on load')-- await userEvent.click(getSubmitButton(screen))-- await waitFor(() => {- expect(submitSpy).toHaveBeenCalledTimes(1)- })-- expect(upload).not.toHaveBeenCalled()- expect(createSignedUrls).not.toHaveBeenCalled()-- const payload = submitSpy.mock.calls[0]?.[0]- expect(payload.message).toContain('Charts throw error on load')- expect(payload.message).not.toContain('Dashboard logs:')}, 10_000)test('uploads dashboard logs when enabled and appends link to message', async () => {@@ -1711,7 +1324,7 @@ describe('SupportFormPage', () => {})}, 10_000)- test('submits support request with attachments and includes attachment URLs in message', async () => {+ test('can add and remove attachments, and submits attachment URLs in the message', async () => {const submitSpy = vi.fn()// Mock URL.createObjectURL and revokeObjectURL@@ -1813,8 +1426,20 @@ describe('SupportFormPage', () => {const fileInput = getAttachmentFileInput()const firstFile = new File(['screenshot 1'], 'error-screenshot.png', { type: 'image/png' })const secondFile = new File(['screenshot 2'], 'logs-screenshot.jpg', { type: 'image/jpeg' })- await userEvent.upload(fileInput, [firstFile, secondFile])+ const removedFile = new File(['removed'], 'removed.png', { type: 'image/png' })+ await userEvent.upload(fileInput, [removedFile, firstFile])+ await waitFor(() => {+ expect(getAttachmentRemoveButtons(screen)).toHaveLength(2)+ })++ // Removing an attachment drops it from the list and releases its preview URL+ await userEvent.click(getAttachmentRemoveButtons(screen)[0])+ await waitFor(() => {+ expect(getAttachmentRemoveButtons(screen)).toHaveLength(1)+ })+ expect(revokeObjectURLMock).toHaveBeenCalled()+ await userEvent.upload(getAttachmentFileInput(), secondFile)await waitFor(() => {expect(getAttachmentRemoveButtons(screen)).toHaveLength(2)})@@ -1863,7 +1488,7 @@ describe('SupportFormPage', () => {}}, 10_000)- test('can submit form with no organizations and no projects', async () => {+ test('can submit form with no organizations and no projects, skipping dashboard logs when toggled off', async () => {const submitSpy = vi.fn()addAPIMock({@@ -1934,6 +1559,8 @@ describe('SupportFormPage', () => {dashboardStudioVersion: mockStudioVersion,})expect(payload.message).toBe('I need help accessing my Supabase account')+ expect(payload.dashboardLogs).toBeUndefined()+ expect(generateAttachmentUrlSpy).not.toHaveBeenCalled()await waitFor(() => {expect(screen.getByRole('heading', { name: /support request sent/i })).toBeInTheDocument()diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.utils.test.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.utils.test.tsindex 531f1db4959..be61b82805b 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.utils.test.ts+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.utils.test.ts@@ -13,85 +13,35 @@ import {describe('parseValue', () => {it('should return null when originalValue is null', () => {- const originalValue = null- const format = 'some format'- expect(parseValue(originalValue, format)).toBeNull()- })-- it('should return originalValue when it is 0', () => {- const originalValue = 0- const format = 'some format'- expect(parseValue(originalValue, format)).toEqual(originalValue)- })-- it('should return originalValue when it is an empty string', () => {- const originalValue = ''- const format = 'some format'- expect(parseValue(originalValue, format)).toEqual(originalValue)+ expect(parseValue(null, 'some format')).toBeNull()})- it('should return originalValue when it is a number and format is not provided', () => {- const originalValue = 42- const format = ''+ it.each([+ { originalValue: 0, format: 'some format' },+ { originalValue: '', format: 'some format' },+ { originalValue: 42, format: '' },+ { originalValue: 'some value', format: 'some format' },+ ])('should return $originalValue unchanged', ({ originalValue, format }) => {expect(parseValue(originalValue, format)).toEqual(originalValue)})- it('should return JSON string representation when originalValue is an empty array', () => {- const originalValue: any[] = []- const format = 'some format'- const expectedValue = JSON.stringify(originalValue)- expect(parseValue(originalValue, format)).toEqual(expectedValue)- })-- it('should return JSON string representation when originalValue is an empty object', () => {- const originalValue = {}- const format = 'some format'- const expectedValue = JSON.stringify(originalValue)- expect(parseValue(originalValue, format)).toEqual(expectedValue)- })-- it('should return JSON string representation when originalValue is an object', () => {- const originalValue = { key: 'value' }- const format = 'some format'- expect(parseValue(originalValue, format)).toEqual(JSON.stringify(originalValue))- })-- it('should handle complex nested object with titles correctly', () => {- const originalValue = {+ it.each([+ [],+ {},+ { key: 'value' },+ {glossary: {title: 'parent title',- subItem: {- title: 'subItem title',- items: ['item1', 'item2'],- },+ subItem: { title: 'subItem title', items: ['item1', 'item2'] },},- }- const format = 'some format'- const expectedValue = JSON.stringify(originalValue)- expect(parseValue(originalValue, format)).toEqual(expectedValue)+ },+ { width: 0, height: 0, length: 0, weight: 0 },+ ])('should return the JSON string representation of %j', (originalValue) => {+ expect(parseValue(originalValue, 'some format')).toEqual(JSON.stringify(originalValue))})- it('should handle object with all values set to 0 correctly', () => {- const originalValue = {- width: 0,- height: 0,- length: 0,- weight: 0,- }- const format = 'some format'- const expectedValue = JSON.stringify(originalValue)- expect(parseValue(originalValue, format)).toEqual(expectedValue)- })it('should return string representation of originalValue when it is a boolean', () => {- const originalValue = true- const format = 'some format'- expect(parseValue(originalValue, format)).toEqual(originalValue.toString())- })-- it('should return originalValue for other cases', () => {- const originalValue = 'some value'- const format = 'some format'- expect(parseValue(originalValue, format)).toEqual(originalValue)+ expect(parseValue(true, 'some format')).toEqual('true')})it('should return originalValue even when an error occurs', () => {@@ -303,20 +253,6 @@ describe('generateRowObjectFromFields', () => {})describe('isValueTruncated', () => {- it('should detect JSON truncated with ...', () => {- // Create a value larger than MAX_CHARACTERS (10KB) with "..." at the end- const value = '{"key": "value"}'.repeat(800) + '...'- expect(isValueTruncated(value)).toBe(true)- })-- it('should detect array truncated with "..." element', () => {- // Simulate MAX_ARRAY_SIZE elements with "..." at the end- // This matches the pattern from table-row-query.ts: array_cat(column[1:50], array['...'])- const items = Array(50).fill('"item"').join(',')- const value = `[${items},"..."]`- expect(isValueTruncated(value)).toBe(true)- })-it('should verify coordination with table-row-query.ts truncation patterns', () => {// Test the exact patterns that table-row-query.ts generates to ensure isValueTruncated stays in sync@@ -335,9 +271,6 @@ describe('isValueTruncated', () => {// array_cat(column[1:50]::json[], array['{"truncated": true}'::json]::json[])const jsonArrayTruncated = `[${Array(5).fill('{"key":"value"}').join(',')},{"truncated":true}]`expect(isValueTruncated(jsonArrayTruncated)).toBe(true)-- // Pattern 4: Multi-dimensional array- // column[1:50]::type[] + an extra entry filled with '...'})it('should detect multidimensional arrays with the truncation marker row', () => {@@ -358,10 +291,6 @@ describe('isValueTruncated', () => {expect(isValueTruncated(JSON.stringify(rows), '_text')).toBe(false)})- it('should detect truncated JSON arrays with truncated flag', () => {- expect(isValueTruncated('[{"a":1},{"b":2},{"truncated":true}]')).toBe(true)- })-it('should return false for normal values', () => {expect(isValueTruncated('normal string')).toBe(false)expect(isValueTruncated('{"key": "value"}')).toBe(false)@@ -668,50 +597,19 @@ describe('generateRowObjectFromFields - additional cases', () => {expect(generateRowObjectFromFields({ fields })).toEqual({ metadata: { key: 'value' } })})- it('should handle boolean true/false/null', () => {- const fields: RowField[] = [- createField({- name: 'active',- format: 'bool',- value: 'true',- }),- createField({- name: 'deleted',- format: 'bool',- value: 'false',- }),- createField({- name: 'optional',- format: 'bool',- value: 'null',- }),- ]- // Null values are kept (explicit NULL), only undefined values are omitted- const result = generateRowObjectFromFields({ fields })- expect(result).toEqual({ active: true, deleted: false, optional: null })- })-- it('should handle boolean true/false/null with includeNullProperties', () => {- const fields: RowField[] = [- createField({- name: 'active',- format: 'bool',- value: 'true',- }),- createField({- name: 'deleted',- format: 'bool',- value: 'false',- }),- createField({- name: 'optional',- format: 'bool',- value: 'null',- }),- ]- const result = generateRowObjectFromFields({ fields, includeUndefinedValues: true })- expect(result).toEqual({ active: true, deleted: false, optional: null })- })+ // Null values are kept (explicit NULL) either way, only undefined values are omitted+ it.each([false, true])(+ 'should handle boolean true/false/null (includeUndefinedValues: %s)',+ (includeUndefinedValues) => {+ const fields: RowField[] = [+ createField({ name: 'active', format: 'bool', value: 'true' }),+ createField({ name: 'deleted', format: 'bool', value: 'false' }),+ createField({ name: 'optional', format: 'bool', value: 'null' }),+ ]+ const result = generateRowObjectFromFields({ fields, includeUndefinedValues })+ expect(result).toEqual({ active: true, deleted: false, optional: null })+ }+ )it('should handle boolean with undefined value', () => {const fields: RowField[] = [diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.tsindex d9c87e78f03..42b542641ae 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.ts+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.ts@@ -312,7 +312,7 @@ describe('createTable', () => {const columns: ColumnField[] = [createColumnField({name: 'status',- defaultValue: "'pending'",+ defaultValue: 'pending',isNullable: false,}),]@@ -328,7 +328,7 @@ describe('createTable', () => {track: mockTrack,})- expect(mockExecuteSql).toHaveBeenCalledTimes(1)+ expect(mockExecuteSql.mock.calls[0][0].sql).toContain("DEFAULT 'pending'")})it('should create table with unique column', async () => {@@ -351,7 +351,7 @@ describe('createTable', () => {track: mockTrack,})- expect(mockExecuteSql).toHaveBeenCalledTimes(1)+ expect(mockExecuteSql.mock.calls[0][0].sql).toMatch(/UNIQUE/i)})it('should create table with array column', async () => {@@ -373,7 +373,7 @@ describe('createTable', () => {track: mockTrack,})- expect(mockExecuteSql).toHaveBeenCalledTimes(1)+ expect(mockExecuteSql.mock.calls[0][0].sql).toMatch(/\btext\[\]/i)})it('should create table with check constraint', async () => {@@ -397,7 +397,7 @@ describe('createTable', () => {track: mockTrack,})- expect(mockExecuteSql).toHaveBeenCalledTimes(1)+ expect(mockExecuteSql.mock.calls[0][0].sql).toMatch(/CHECK \(age >= 0\)/i)})it('should propagate SQL execution errors', async () => {diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.test.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.test.tsindex dacd54caecd..705633973f7 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.test.ts+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.test.ts@@ -178,40 +178,13 @@ describe('getRowFromSidePanel', () => {expect(getRowFromSidePanel(sidePanel)).toEqual(mockRow)})- test('returns undefined for table side panel', () => {- const sidePanel: SidePanel = {- type: 'table',- mode: 'new',- }- expect(getRowFromSidePanel(sidePanel)).toBeUndefined()- })-- test('returns undefined for column side panel', () => {- const sidePanel: SidePanel = {- type: 'column',- }- expect(getRowFromSidePanel(sidePanel)).toBeUndefined()- })-- test('returns undefined for schema side panel', () => {- const sidePanel: SidePanel = {- type: 'schema',- mode: 'new',- }- expect(getRowFromSidePanel(sidePanel)).toBeUndefined()- })-- test('returns undefined for csv-import side panel', () => {- const sidePanel: SidePanel = {- type: 'csv-import',- }- expect(getRowFromSidePanel(sidePanel)).toBeUndefined()- })-- test('returns undefined for operation-queue side panel', () => {- const sidePanel: SidePanel = {- type: 'operation-queue',- }+ test.each<SidePanel>([+ { type: 'table', mode: 'new' },+ { type: 'column' },+ { type: 'schema', mode: 'new' },+ { type: 'csv-import' },+ { type: 'operation-queue' },+ ])('returns undefined for $type side panel', (sidePanel) => {expect(getRowFromSidePanel(sidePanel)).toBeUndefined()})})diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.test.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.test.tsxindex 33840ff7909..38b421a6df0 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.test.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.test.tsx@@ -5,22 +5,13 @@ import { describe, expect, it, vi } from 'vitest'import { TableRealtimeToggle } from './TableEditor'describe('TableRealtimeToggle', () => {- it('shows the Realtime toggle with its description', () => {- render(<TableRealtimeToggle checked={false} onCheckedChange={vi.fn()} />)-- expect(screen.getByRole('checkbox', { name: 'Enable Realtime' })).toBeEnabled()- expect(- screen.getByText('Broadcast changes on this table to authorized subscribers.')- ).toBeInTheDocument()- })-- it('calls onCheckedChange when toggled', async () => {+ it('reports the new checked state when toggled', async () => {const user = userEvent.setup()const onCheckedChange = vi.fn()render(<TableRealtimeToggle checked={false} onCheckedChange={onCheckedChange} />)await user.click(screen.getByRole('checkbox', { name: 'Enable Realtime' }))- expect(onCheckedChange).toHaveBeenCalledOnce()+ expect(onCheckedChange).toHaveBeenCalledWith(true)})})diff --git a/apps/studio/components/interfaces/TableGridEditor/TableEntity.utils.test.ts b/apps/studio/components/interfaces/TableGridEditor/TableEntity.utils.test.tsindex be8d2ec3376..1caadd3ee55 100644--- a/apps/studio/components/interfaces/TableGridEditor/TableEntity.utils.test.ts+++ b/apps/studio/components/interfaces/TableGridEditor/TableEntity.utils.test.ts@@ -288,21 +288,7 @@ describe('TableEntity.utils: getTablePoliciesUrl', () => {)})- it('preserves special characters in the table name', () => {- const url = getTablePoliciesUrl('abc', 'public', 'user_data&secret=1')- const parsed = new URL(url, 'http://example.com')- expect(parsed.searchParams.get('search')).toBe('user_data&secret=1')- expect(parsed.searchParams.get('schema')).toBe('public')- })-- it('preserves special characters in the schema', () => {- const url = getTablePoliciesUrl('abc', 'my schema+x', 'users')- const parsed = new URL(url, 'http://example.com')- expect(parsed.searchParams.get('schema')).toBe('my schema+x')- expect(parsed.searchParams.get('search')).toBe('users')- })-- it('encodes both the table name and schema together', () => {+ it('preserves special characters in the table name and schema', () => {const url = getTablePoliciesUrl('abc', 'a&b=c', 'd e+f')const parsed = new URL(url, 'http://example.com')expect(parsed.searchParams.get('search')).toBe('d e+f')diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.filters.test.ts b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.filters.test.tsindex 178dee0a3f7..0bd752b1968 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.filters.test.ts+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.filters.test.ts@@ -77,17 +77,14 @@ describe('logsFiltersToColumnFilters', () => {])})- it('round-trips an eq URL filter back to the same param without flipping the operator', () => {- const seeded = logsFiltersToColumnFilters(parseLogsFilterUrlParams(['method:eq:GET']))- const update = buildFilterSearchUpdate(seeded, [{ value: 'method', type: 'checkbox' }])- expect(update.filter).toEqual(['method:eq:GET'])- })-- it('round-trips a neq URL filter without downgrading it to eq', () => {- const seeded = logsFiltersToColumnFilters(parseLogsFilterUrlParams(['method:neq:GET']))- const update = buildFilterSearchUpdate(seeded, [{ value: 'method', type: 'checkbox' }])- expect(update.filter).toEqual(['method:neq:GET'])- })+ it.each(['method:eq:GET', 'method:neq:GET'])(+ 'round-trips the URL filter %s back to the same param without changing the operator',+ (param) => {+ const seeded = logsFiltersToColumnFilters(parseLogsFilterUrlParams([param]))+ const update = buildFilterSearchUpdate(seeded, [{ value: 'method', type: 'checkbox' }])+ expect(update.filter).toEqual([param])+ }+ )})describe('buildFilterSearchUpdate', () => {@@ -148,18 +145,11 @@ describe('buildDefaultColumnFilters', () => {expect(update.date).toBe(range)})- it('omits `date` when no range is present, matching the pre-existing no-filter case', () => {- expect(buildDefaultColumnFilters({ filter: ['log_type:eq:postgres'], date: null })).toEqual([- { id: 'log_type', value: { operator: '=', values: ['postgres'] } },- ])- })-- it('omits `date` for a malformed single-element range', () => {- const columnFilters = buildDefaultColumnFilters({- filter: ['log_type:eq:postgres'],- date: [new Date('2026-05-08T00:00:00Z')],- })- expect(columnFilters).toEqual([+ it.each([+ ['no range is present', null],+ ['the range is a malformed single element', [new Date('2026-05-08T00:00:00Z')]],+ ])('omits `date` when %s', (_, date) => {+ expect(buildDefaultColumnFilters({ filter: ['log_type:eq:postgres'], date })).toEqual([{ id: 'log_type', value: { operator: '=', values: ['postgres'] } },])})diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.test.ts b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.test.tsindex 92cde3cf321..d833614fadd 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.test.ts+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.test.ts@@ -30,21 +30,19 @@ describe('UnifiedLogs.queries (OTEL flat)', () => {expect(where).not.toContain(`source = 'postgrest_logs'`)})- it('routes the `postgrest` log type solely to postgrest_logs (mutually exclusive from edge_logs)', () => {- const sql = getUnifiedLogsQuery(withFilters('log_type:eq:postgrest'))- const where = sql.split(/\bWHERE\b/)[1] ?? ''- expect(where).toContain(`source = 'postgrest_logs'`)- expect(where).not.toContain(`source = 'edge_logs'`)- expect(where).not.toContain(`log_attributes['request.path'] LIKE '%/rest/%'`)- })-- it('routes the `storage` log type solely to storage_logs (mutually exclusive from edge_logs)', () => {- const sql = getUnifiedLogsQuery(withFilters('log_type:eq:storage'))- const where = sql.split(/\bWHERE\b/)[1] ?? ''- expect(where).toContain(`source = 'storage_logs'`)- expect(where).not.toContain(`source = 'edge_logs'`)- expect(where).not.toContain(`log_attributes['request.path'] LIKE '%/storage/%'`)- })+ it.each([+ ['postgrest', 'postgrest_logs', '%/rest/%'],+ ['storage', 'storage_logs', '%/storage/%'],+ ])(+ 'routes the `%s` log type solely to %s (mutually exclusive from edge_logs)',+ (logType, source, edgePath) => {+ const sql = getUnifiedLogsQuery(withFilters(`log_type:eq:${logType}`))+ const where = sql.split(/\bWHERE\b/)[1] ?? ''+ expect(where).toContain(`source = '${source}'`)+ expect(where).not.toContain(`source = 'edge_logs'`)+ expect(where).not.toContain(`log_attributes['request.path'] LIKE '${edgePath}'`)+ }+ )it('routes the `compute` log type to every worker OTEL stream', () => {const sql = getUnifiedLogsQuery(withFilters('log_type:eq:compute'))@@ -122,31 +120,15 @@ describe('UnifiedLogs.queries (OTEL flat)', () => {expect(sql).toMatch(/END\) NOT IN \('401'\)/)})- it('reads the HTTP status from log_attributes[status] for auth rows', () => {- // Auth-service logs expose their status under `status`, not the gateway's- // `response.status_code`, so without this their 4xx/5xx classify as- // success and the severity filter returns nothing.- const sql = getUnifiedLogsQuery(withFilters('log_type:eq:auth'))- expect(sql).toContain(`WHEN source = 'auth_logs' THEN log_attributes['status']`)- })-- it('reads the HTTP status from log_attributes[res.statusCode] for storage rows', () => {- // Storage-service logs expose their status under `res.statusCode`, not the- // gateway's `response.status_code`.- const sql = getUnifiedLogsQuery(withFilters('log_type:eq:storage'))- expect(sql).toContain(`WHEN source = 'storage_logs' THEN log_attributes['res.statusCode']`)- })-- it('reads the method/pathname from log_attributes[req.method/req.url] for storage rows', () => {- // Storage-service logs expose method/path under `req.method` / `req.url`,- // not the gateway's `request.method` / `request.path`.- const sql = getUnifiedLogsQuery(withFilters('log_type:eq:storage'))- expect(sql).toContain(- `if(source = 'storage_logs', log_attributes['req.method'], log_attributes['request.method'])`- )- expect(sql).toContain(- `if(source = 'storage_logs', log_attributes['req.url'], log_attributes['request.path'])`- )+ // Auth- and storage-service logs expose their status under their own keys,+ // not the gateway's `response.status_code`; without this their 4xx/5xx+ // classify as success and the severity filter returns nothing.+ it.each([+ ['auth', `WHEN source = 'auth_logs' THEN log_attributes['status']`],+ ['storage', `WHEN source = 'storage_logs' THEN log_attributes['res.statusCode']`],+ ])('reads the HTTP status from the service-specific key for %s rows', (logType, expected) => {+ const sql = getUnifiedLogsQuery(withFilters(`log_type:eq:${logType}`))+ expect(sql).toContain(expected)})it('flips LIKE to NOT LIKE when the pathname/host operator is `<>`', () => {@@ -157,75 +139,34 @@ describe('UnifiedLogs.queries (OTEL flat)', () => {expect(sql).toContain(`log_attributes['request.url'] NOT LIKE '%cdn.foo%'`)})- it('emits ILIKE for pathname `~~*`, case-insensitive unlike the `=` LIKE behavior', () => {- const sql = getUnifiedLogsQuery(withFilters('pathname:ilike:Customers'))- expect(sql).toContain(- `(if(source = 'storage_logs', log_attributes['req.url'], log_attributes['request.path'])) ILIKE '%Customers%'`- )- })-- it('emits NOT ILIKE for pathname `!~~*` so rows matching the term are excluded', () => {- const sql = getUnifiedLogsQuery(withFilters('pathname:notilike:health'))- expect(sql).toContain(- `(if(source = 'storage_logs', log_attributes['req.url'], log_attributes['request.path'])) NOT ILIKE '%health%'`- )- })-- it('joins multiple pathname NOT ILIKE values with AND (row must match none)', () => {- const sql = getUnifiedLogsQuery(- withFilters('pathname:notilike:health', 'pathname:notilike:metrics')- )- const pathExpr = `(if(source = 'storage_logs', log_attributes['req.url'], log_attributes['request.path']))`- expect(sql).toContain(- `${pathExpr} NOT ILIKE '%health%' AND ${pathExpr} NOT ILIKE '%metrics%'`- )- })+ const pathExpr = `(if(source = 'storage_logs', log_attributes['req.url'], log_attributes['request.path']))`- it('passes through user-supplied `%` wildcards on pathname ILIKE without double-wrapping', () => {- const sql = getUnifiedLogsQuery(withFilters('pathname:ilike:foo%'))- expect(sql).toContain(- `(if(source = 'storage_logs', log_attributes['req.url'], log_attributes['request.path'])) ILIKE 'foo%'`- )- expect(sql).not.toContain(`'%foo%%'`)- })-- it('passes through user-supplied `_` wildcards on pathname ILIKE without wrapping', () => {- const sql = getUnifiedLogsQuery(withFilters('pathname:ilike:fo_bar'))- expect(sql).toContain(- `(if(source = 'storage_logs', log_attributes['req.url'], log_attributes['request.path'])) ILIKE 'fo_bar'`- )- expect(sql).not.toContain(`'%fo_bar%'`)- })-- it('emits ILIKE with auto-wrapped `%…%` for event_message `~~*`', () => {- const sql = getUnifiedLogsQuery(withFilters('event_message:ilike:Permission Denied'))- expect(sql).toContain(`event_message ILIKE '%Permission Denied%'`)- })-- it('emits NOT ILIKE for event_message `!~~*` so rows containing the term are excluded', () => {- const sql = getUnifiedLogsQuery(withFilters('event_message:notilike:cron'))- expect(sql).toContain(`event_message NOT ILIKE '%cron%'`)- })+ it.each([+ ['pathname:ilike:Customers', `${pathExpr} ILIKE '%Customers%'`, null],+ ['pathname:notilike:health', `${pathExpr} NOT ILIKE '%health%'`, null],+ ['pathname:ilike:foo%', `${pathExpr} ILIKE 'foo%'`, `'%foo%%'`],+ ['pathname:ilike:fo_bar', `${pathExpr} ILIKE 'fo_bar'`, `'%fo_bar%'`],+ ['event_message:ilike:Permission Denied', `event_message ILIKE '%Permission Denied%'`, null],+ ['event_message:notilike:cron', `event_message NOT ILIKE '%cron%'`, null],+ ['event_message:ilike:error%', `event_message ILIKE 'error%'`, `'%error%%'`],+ ['event_message:ilike:foo_bar', `event_message ILIKE 'foo_bar'`, `'%foo_bar%'`],+ ])(+ 'emits the pattern predicate for %s, auto-wrapping only values without wildcards',+ (filter, expected, notExpected) => {+ const sql = getUnifiedLogsQuery(withFilters(filter))+ expect(sql).toContain(expected)+ if (notExpected) expect(sql).not.toContain(notExpected)+ }+ )- it('joins multiple NOT ILIKE values with AND (row must contain none)', () => {+ it.each([+ ['pathname', pathExpr],+ ['event_message', 'event_message'],+ ])('joins multiple %s NOT ILIKE values with AND (row must match none)', (column, expr) => {const sql = getUnifiedLogsQuery(- withFilters('event_message:notilike:cron', 'event_message:notilike:heartbeat')- )- expect(sql).toMatch(- /event_message NOT ILIKE '%cron%' AND event_message NOT ILIKE '%heartbeat%'/+ withFilters(`${column}:notilike:health`, `${column}:notilike:metrics`))- })-- it('passes through user-supplied `%` wildcards on event_message ILIKE without double-wrapping', () => {- const sql = getUnifiedLogsQuery(withFilters('event_message:ilike:error%'))- expect(sql).toContain(`event_message ILIKE 'error%'`)- expect(sql).not.toContain(`'%error%%'`)- })-- it('passes through user-supplied `_` wildcards on event_message ILIKE without wrapping', () => {- const sql = getUnifiedLogsQuery(withFilters('event_message:ilike:foo_bar'))- expect(sql).toContain(`event_message ILIKE 'foo_bar'`)- expect(sql).not.toContain(`'%foo_bar%'`)+ expect(sql).toContain(`${expr} NOT ILIKE '%health%' AND ${expr} NOT ILIKE '%metrics%'`)})it('excludes connection log messages when show_connection_logs=false', () => {@@ -343,25 +284,16 @@ describe('UnifiedLogs.queries (OTEL flat)', () => {})describe('getLogsChartQuery', () => {- it('uses minute bucketing for short ranges', () => {- const sql = getLogsChartQuery(baseSearch)- expect(sql).toContain('toStartOfMinute(timestamp)')- })-- it('uses hour bucketing for ranges spanning more than 12 hours', () => {- const sql = getLogsChartQuery({- ...baseSearch,- date: [new Date('2026-05-08T00:00:00Z'), new Date('2026-05-08T18:00:00Z')],- } as any)- expect(sql).toContain('toStartOfHour(timestamp)')- })-- it('uses day bucketing for ranges spanning more than 2 days', () => {+ it.each([+ ['toStartOfMinute', '2026-05-08T09:00:00Z', '2026-05-08T10:00:00Z'],+ ['toStartOfHour', '2026-05-08T00:00:00Z', '2026-05-08T18:00:00Z'],+ ['toStartOfDay', '2026-05-01T00:00:00Z', '2026-05-08T00:00:00Z'],+ ])('buckets with %s for a %s - %s range', (bucketFn, start, end) => {const sql = getLogsChartQuery({...baseSearch,- date: [new Date('2026-05-01T00:00:00Z'), new Date('2026-05-08T00:00:00Z')],+ date: [new Date(start), new Date(end)],} as any)- expect(sql).toContain('toStartOfDay(timestamp)')+ expect(sql).toContain(`${bucketFn}(timestamp)`)})it('buckets auth rows by their log_attributes[status] so 4xx/5xx are not counted as success', () => {@@ -432,42 +364,18 @@ describe('UnifiedLogs.queries (OTEL flat)', () => {expect(isUserFilterUnreachable(withFilters('log_type:eq:edge'))).toBe(false)})- it('is false when the user filter is active with no explicit log_type filter', () => {- expect(isUserFilterUnreachable(withUser('user-123'))).toBe(false)- })-- it('is false when the explicit log_type filter includes an attributable source (auth)', () => {- expect(isUserFilterUnreachable(withUser('user-123', 'log_type:eq:auth'))).toBe(false)- })-- it('is false when the explicit log_type filter includes an attributable source (edge)', () => {- expect(isUserFilterUnreachable(withUser('user-123', 'log_type:eq:edge'))).toBe(false)- })-- it('is false when at least one of several selected log types is attributable', () => {- expect(- isUserFilterUnreachable(withUser('user-123', 'log_type:eq:edge', 'log_type:eq:auth'))- ).toBe(false)- })-- it('is true when the explicit log_type filter restricts to a single non-attributable source', () => {- expect(isUserFilterUnreachable(withUser('user-123', 'log_type:eq:storage'))).toBe(true)- })-- it('is true when every selected log type is non-attributable', () => {- expect(- isUserFilterUnreachable(withUser('user-123', 'log_type:eq:realtime', 'log_type:eq:storage'))- ).toBe(true)- })-- it('(neq) is false when excluding a non-attributable source — the attributable sources remain eligible', () => {- expect(isUserFilterUnreachable(withUser('user-123', 'log_type:neq:edge'))).toBe(false)- })-- it('(neq) is true only when both attributable sources are excluded', () => {- expect(- isUserFilterUnreachable(withUser('user-123', 'log_type:neq:auth', 'log_type:neq:edge'))- ).toBe(true)+ it.each([+ [[], false],+ [['log_type:eq:auth'], false],+ [['log_type:eq:edge'], false],+ [['log_type:eq:edge', 'log_type:eq:auth'], false],+ [['log_type:eq:storage'], true],+ [['log_type:eq:realtime', 'log_type:eq:storage'], true],+ // Excluding one attributable source leaves the other eligible.+ [['log_type:neq:edge'], false],+ [['log_type:neq:auth', 'log_type:neq:edge'], true],+ ])('with a user filter and log_type filters %j returns %s', (filters, expected) => {+ expect(isUserFilterUnreachable(withUser('user-123', ...filters))).toBe(expected)})})@@ -482,13 +390,6 @@ describe('UnifiedLogs.queries (OTEL flat)', () => {)expect(sql).not.toContain(`E'a`)})-- it("escapes single quotes by doubling them ('' rather than \\')", () => {- const sql = getUnifiedLogsQuery(withFilters("method:eq:GET' OR '1'='1"))- expect(sql).toContain(- `(if(source = 'storage_logs', log_attributes['req.method'], log_attributes['request.method'])) IN ('GET'' OR ''1''=''1')`- )- })})})@@ -498,18 +399,13 @@ describe('UnifiedLogs.queries.bq', () => {expect(sql).toContain("`method` IN ('GET')")})- it('rejects keys with non-identifier characters', () => {- // A column like "foo; DROP TABLE x" fails the quotedIdent regex (the `;` is not- // in `[A-Za-z_][A-Za-z0-9_]*`), so the predicate is dropped entirely.- const sql = getUnifiedLogsQueryBQ(withFilters('foo; DROP TABLE x:eq:y'))- expect(sql).not.toContain('DROP TABLE')- expect(sql).not.toContain('foo;')- })-- it('rejects keys containing spaces', () => {- const sql = getUnifiedLogsQueryBQ(withFilters('level OR id IS NOT NULL:eq:anything'))- expect(sql).not.toContain('IS NOT NULL')- expect(sql).not.toContain('level OR')+ // Keys failing the quotedIdent regex (`[A-Za-z_][A-Za-z0-9_]*`) drop the predicate entirely.+ it.each([+ ['foo; DROP TABLE x:eq:y', ['DROP TABLE', 'foo;']],+ ['level OR id IS NOT NULL:eq:anything', ['IS NOT NULL', 'level OR']],+ ])('rejects the non-identifier key in %s', (filter, forbidden) => {+ const sql = getUnifiedLogsQueryBQ(withFilters(filter))+ for (const fragment of forbidden) expect(sql).not.toContain(fragment)})it('escapes injection attempts in filter values via analyticsLiteral', () => {@@ -520,61 +416,22 @@ describe('UnifiedLogs.queries.bq', () => {expect(sql).not.toMatch(/`method` IN \('GET' OR '1'='1'\)/)})- it('emulates ILIKE with LOWER()/LOWER() since BigQuery has no ILIKE keyword', () => {- const sql = getUnifiedLogsQueryBQ(withFilters('event_message:ilike:Permission Denied'))- expect(sql).toContain("LOWER(`event_message`) LIKE LOWER('%Permission Denied%')")- // Sanity check: never emit a raw ILIKE keyword for BQ.- expect(sql).not.toMatch(/\bILIKE\b/)- })-- it('emulates NOT ILIKE with LOWER()/NOT LIKE/LOWER() for event_message `!~~*`', () => {- const sql = getUnifiedLogsQueryBQ(withFilters('event_message:notilike:cron'))- expect(sql).toContain("LOWER(`event_message`) NOT LIKE LOWER('%cron%')")- expect(sql).not.toMatch(/\bILIKE\b/)- })-- it('emulates ILIKE with LOWER()/LOWER() for pathname `~~*`', () => {- const sql = getUnifiedLogsQueryBQ(withFilters('pathname:ilike:Customers'))- expect(sql).toContain("LOWER(`pathname`) LIKE LOWER('%Customers%')")+ // BigQuery has no ILIKE keyword. Wildcard handling must match the ClickHouse+ // builder, otherwise switching the `otelUnifiedLogs` flag would silently+ // change what a saved/shared filter matches.+ it.each([+ [+ 'event_message:ilike:Permission Denied',+ "LOWER(`event_message`) LIKE LOWER('%Permission Denied%')",+ ],+ ['event_message:notilike:cron', "LOWER(`event_message`) NOT LIKE LOWER('%cron%')"],+ ['pathname:ilike:Customers', "LOWER(`pathname`) LIKE LOWER('%Customers%')"],+ ['pathname:notilike:health', "LOWER(`pathname`) NOT LIKE LOWER('%health%')"],+ ['pathname:ilike:foo%', "LOWER(`pathname`) LIKE LOWER('foo%')"],+ ['pathname:ilike:fo_bar', "LOWER(`pathname`) LIKE LOWER('fo_bar')"],+ ])('emulates ILIKE with LOWER() for %s', (filter, expected) => {+ const sql = getUnifiedLogsQueryBQ(withFilters(filter))+ expect(sql).toContain(expected)expect(sql).not.toMatch(/\bILIKE\b/)})-- it('emulates NOT ILIKE with LOWER()/NOT LIKE/LOWER() for pathname `!~~*`', () => {- const sql = getUnifiedLogsQueryBQ(withFilters('pathname:notilike:health'))- expect(sql).toContain("LOWER(`pathname`) NOT LIKE LOWER('%health%')")- expect(sql).not.toMatch(/\bILIKE\b/)- })-- it('passes through user-supplied `%` wildcards on pathname ILIKE without double-wrapping', () => {- const sql = getUnifiedLogsQueryBQ(withFilters('pathname:ilike:foo%'))- expect(sql).toContain("LOWER(`pathname`) LIKE LOWER('foo%')")- expect(sql).not.toContain("LOWER('%foo%%')")- })-- it('passes through user-supplied `_` wildcards on pathname ILIKE without wrapping', () => {- const sql = getUnifiedLogsQueryBQ(withFilters('pathname:ilike:fo_bar'))- expect(sql).toContain("LOWER(`pathname`) LIKE LOWER('fo_bar')")- expect(sql).not.toContain("LOWER('%fo_bar%')")- })-})--describe('pathname ILIKE prefix matching (cross-builder)', () => {- // Both query builders must treat an explicit `%` the same way — a value- // like `foo%` is a prefix match, not a "contains" search with a stray- // trailing wildcard — otherwise switching the `otelUnifiedLogs` flag would- // silently change what a saved/shared filter matches.- it('produces equivalent prefix-matching patterns for `pathname:ilike:foo%` on both backends', () => {- const clickhouseSql = getUnifiedLogsQuery(withFilters('pathname:ilike:foo%'))- const bqSql = getUnifiedLogsQueryBQ(withFilters('pathname:ilike:foo%'))-- expect(clickhouseSql).toContain(- `(if(source = 'storage_logs', log_attributes['req.url'], log_attributes['request.path'])) ILIKE 'foo%'`- )- expect(bqSql).toContain("LOWER(`pathname`) LIKE LOWER('foo%')")-- // Neither backend should have double-wrapped the wildcard into a- // "contains" pattern.- expect(clickhouseSql).not.toContain(`'%foo%%'`)- expect(bqSql).not.toContain("LOWER('%foo%%')")- })})diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.test.ts b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.test.tsindex 6b8e3d1aa85..172e84df6f6 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.test.ts+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.test.ts@@ -29,18 +29,10 @@ describe('buildUnifiedLogsUrl', () => {expect(params.get('filter')).toBe('log_type:eq:edge function')})- it('adds the date range as an epoch-ms pair when start and end are provided', () => {- const start = new Date('2026-05-08T00:00:00.000Z')- const end = new Date('2026-05-08T01:00:00.000Z')- const { params } = parse(- buildUnifiedLogsUrl({ projectRef: 'abc', logType: 'auth', start, end })- )- expect(params.get('date')).toBe(`${start.valueOf()}-${end.valueOf()}`)- })-- it('accepts ISO strings for the date range', () => {- const start = '2026-05-08T00:00:00.000Z'- const end = '2026-05-08T01:00:00.000Z'+ it.each([+ ['Date objects', new Date('2026-05-08T00:00:00.000Z'), new Date('2026-05-08T01:00:00.000Z')],+ ['ISO strings', '2026-05-08T00:00:00.000Z', '2026-05-08T01:00:00.000Z'],+ ])('adds the date range as an epoch-ms pair from %s', (_, start, end) => {const { params } = parse(buildUnifiedLogsUrl({ projectRef: 'abc', logType: 'auth', start, end }))@@ -220,59 +212,38 @@ describe('getComputeLogsAvailability', () => {expect(availability.readyToSyncFilters).toBe(false)})- it('allows Compute filters and queries when the platform flag is enabled', () => {- const availability = getComputeLogsAvailability({- isPlatform: true,- flagsLoaded: true,- computeEnabled: true,- })-- expect(availability).toEqual({- canQueryCompute: true,- preserveComputeFilter: true,- readyToSyncFilters: true,- })- })-- it('removes Compute filters and queries when the platform flag is disabled', () => {- const availability = getComputeLogsAvailability({- isPlatform: true,- flagsLoaded: true,- computeEnabled: false,- })-- expect(availability).toEqual({- canQueryCompute: false,- preserveComputeFilter: false,- readyToSyncFilters: true,- })- })-- it('syncs generic filters immediately while keeping Compute unavailable on self-hosted', () => {- const availability = getComputeLogsAvailability({- isPlatform: false,- computeEnabled: false,- })-- expect(availability).toEqual({- canQueryCompute: false,- preserveComputeFilter: false,+ it.each([+ [+ 'allows Compute when the platform flag is enabled',+ { isPlatform: true, flagsLoaded: true, computeEnabled: true },+ true,+ ],+ [+ 'removes Compute when the platform flag is disabled',+ { isPlatform: true, flagsLoaded: true, computeEnabled: false },+ false,+ ],+ [+ 'syncs generic filters immediately while keeping Compute unavailable on self-hosted',+ { isPlatform: false, computeEnabled: false },+ false,+ ],+ ])('%s', (_, input, computeAvailable) => {+ expect(getComputeLogsAvailability(input)).toEqual({+ canQueryCompute: computeAvailable,+ preserveComputeFilter: computeAvailable,readyToSyncFilters: true,})})})describe('wrapIlikePattern', () => {- it('wraps a bare value in %...% for a contains match', () => {- expect(wrapIlikePattern('foo')).toBe('%foo%')- })-- it('leaves the value untouched when it already contains a % wildcard', () => {- expect(wrapIlikePattern('foo%')).toBe('foo%')- expect(wrapIlikePattern('%foo')).toBe('%foo')- })-- it('leaves the value untouched when it already contains a _ wildcard', () => {- expect(wrapIlikePattern('fo_bar')).toBe('fo_bar')+ it.each([+ ['foo', '%foo%'],+ ['foo%', 'foo%'],+ ['%foo', '%foo'],+ ['fo_bar', 'fo_bar'],+ ])('wraps %s only when it has no %% or _ wildcard', (value, expected) => {+ expect(wrapIlikePattern(value)).toBe(expected)})})diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.utils.test.ts b/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.utils.test.tsindex b23288ea9d4..764155c0caf 100644--- a/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.utils.test.ts+++ b/apps/studio/components/interfaces/UnifiedLogs/components/LogsFilterBar.utils.test.ts@@ -1,5 +1,4 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import { z } from 'zod'import {buildColumnFilterValues,@@ -40,36 +39,16 @@ describe('buildFilterProperties', () => {expect(names).toEqual(['date', 'log_type', 'event_message', 'pathname', USER_PROPERTY])})- it('gives the event_message column pattern (ILIKE) operators', () => {- const eventMessage = buildFilterProperties({ fields }).find(- (property) => property.name === 'event_message'- )- expect(eventMessage?.operators).toEqual([- { label: 'iLike', value: '~~*', group: 'pattern' },- { label: 'Not iLike', value: '!~~*', group: 'pattern' },- ])- })-- it('gives every other column comparison operators', () => {- const logType = buildFilterProperties({ fields }).find(- (property) => property.name === 'log_type'+ it.each([+ ['event_message', ['~~*', '!~~*']],+ ['log_type', ['=', '<>']],+ ['pathname', ['=', '<>', '~~*', '!~~*']],+ ])('gives the %s column the %j operators', (name, operators) => {+ const property = buildFilterProperties({ fields }).find((property) => property.name === name)+ const operatorValues = property?.operators?.map((operator) =>+ typeof operator === 'string' ? operator : operator.value)- expect(logType?.operators).toEqual([- { label: 'Equals', value: '=', group: 'comparison' },- { label: 'Not equal', value: '<>', group: 'comparison' },- ])- })-- it('gives pathname both comparison and pattern (ILIKE) operators', () => {- const pathname = buildFilterProperties({ fields }).find(- (property) => property.name === 'pathname'- )- expect(pathname?.operators).toEqual([- { label: 'Equals', value: '=', group: 'comparison' },- { label: 'Not equal', value: '<>', group: 'comparison' },- { label: 'iLike', value: '~~*', group: 'pattern' },- { label: 'Not iLike', value: '!~~*', group: 'pattern' },- ])+ expect(operatorValues).toEqual(operators)})it('defaults a column without options to an empty array', () => {@@ -102,20 +81,16 @@ describe('buildFilterProperties', () => {})describe('getUserFilterValue', () => {- const resultSchema = z.string().optional()-- it('returns the user condition value coerced to a string, validated by schema', () => {+ it('returns the user condition value', () => {const result = getUserFilterValue([{ propertyName: 'log_type', value: 'postgres', operator: '=' },{ propertyName: USER_PROPERTY, value: '[email protected]', operator: '=' },])- expect(() => resultSchema.parse(result)).not.toThrow()expect(result).toBe('[email protected]')})it('coerces a non-string condition value to a string', () => {const result = getUserFilterValue([{ propertyName: USER_PROPERTY, value: 42, operator: '=' }])- expect(() => resultSchema.parse(result)).not.toThrow()expect(result).toBe('42')})@@ -123,7 +98,6 @@ describe('getUserFilterValue', () => {const result = getUserFilterValue([{ propertyName: 'log_type', value: 'postgres', operator: '=' },])- expect(() => resultSchema.parse(result)).not.toThrow()expect(result).toBeUndefined()})diff --git a/apps/studio/components/layouts/AppLayout/AdvisorButton.self-hosted.test.tsx b/apps/studio/components/layouts/AppLayout/AdvisorButton.self-hosted.test.tsxdeleted file mode 100644index b7b0a80a04d..00000000000--- a/apps/studio/components/layouts/AppLayout/AdvisorButton.self-hosted.test.tsx+++ /dev/null@@ -1,66 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest'--import { AdvisorButton } from '@/components/layouts/AppLayout/AdvisorButton'-import { render } from '@/tests/helpers'--const {- mockUseProjectLintsQuery,- mockUseNotificationsV2Query,- mockUseAdvisorSignals,- mockToggleSidebar,-} = vi.hoisted(() => ({- mockUseProjectLintsQuery: vi.fn(),- mockUseNotificationsV2Query: vi.fn(),- mockUseAdvisorSignals: vi.fn(),- mockToggleSidebar: vi.fn(),-}))--vi.mock('@/data/lint/lint-query', () => ({- useProjectLintsQuery: mockUseProjectLintsQuery,-}))--vi.mock('@/data/notifications/notifications-v2-query', () => ({- useNotificationsV2Query: mockUseNotificationsV2Query,-}))--vi.mock('@/components/ui/AdvisorPanel/useAdvisorSignals', () => ({- useAdvisorSignals: mockUseAdvisorSignals,-}))--vi.mock('@/lib/constants', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/lib/constants')>()),- IS_PLATFORM: false,-}))--vi.mock('@/state/sidebar-manager-state', () => ({- useSidebarManagerSnapshot: () => ({- toggleSidebar: mockToggleSidebar,- activeSidebar: undefined,- }),-}))--describe('AdvisorButton on self-hosted', () => {- beforeEach(() => {- mockUseProjectLintsQuery.mockReturnValue({ data: [], isPending: false, isError: false })- mockUseNotificationsV2Query.mockReturnValue({- data: { pages: [[]] },- isPending: false,- isError: false,- })- mockUseAdvisorSignals.mockReturnValue({- data: [],- isPending: false,- isError: false,- dismissSignal: vi.fn(),- })- })-- it('disables the notifications query so no request is made to the platform endpoint', () => {- render(<AdvisorButton projectRef="project-ref" />)-- expect(mockUseNotificationsV2Query).toHaveBeenCalledWith(- { filters: {}, limit: 20 },- { enabled: false }- )- })-})diff --git a/apps/studio/components/layouts/AppLayout/AdvisorButton.test.tsx b/apps/studio/components/layouts/AppLayout/AdvisorButton.test.tsxindex 78241055072..ef4ecfe9c33 100644--- a/apps/studio/components/layouts/AppLayout/AdvisorButton.test.tsx+++ b/apps/studio/components/layouts/AppLayout/AdvisorButton.test.tsx@@ -1,4 +1,3 @@-import { screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { AdvisorButton } from '@/components/layouts/AppLayout/AdvisorButton'@@ -9,7 +8,9 @@ const {mockUseNotificationsV2Query,mockUseAdvisorSignals,mockToggleSidebar,+ mockIsPlatform,} = vi.hoisted(() => ({+ mockIsPlatform: { value: true },mockUseProjectLintsQuery: vi.fn(),mockUseNotificationsV2Query: vi.fn(),mockUseAdvisorSignals: vi.fn(),@@ -30,7 +31,9 @@ vi.mock('@/components/ui/AdvisorPanel/useAdvisorSignals', () => ({vi.mock('@/lib/constants', async (importOriginal) => ({...(await importOriginal<typeof import('@/lib/constants')>()),- IS_PLATFORM: true,+ get IS_PLATFORM() {+ return mockIsPlatform.value+ },}))vi.mock('@/state/sidebar-manager-state', () => ({@@ -42,6 +45,7 @@ vi.mock('@/state/sidebar-manager-state', () => ({describe('AdvisorButton', () => {beforeEach(() => {+ mockIsPlatform.value = truemockUseProjectLintsQuery.mockReturnValue({ data: [], isPending: false, isError: false })mockUseNotificationsV2Query.mockReturnValue({data: { pages: [[]] },@@ -154,6 +158,15 @@ describe('AdvisorButton', () => {expect(container.querySelector('.bg-primary-bright')).toBeInTheDocument()expect(container.querySelector('.bg-warning')).not.toBeInTheDocument()expect(container.querySelector('.bg-destructive')).not.toBeInTheDocument()- expect(screen.getByRole('button')).toBeInTheDocument()+ })++ it('disables the notifications query on self-hosted so no request is made to the platform endpoint', () => {+ mockIsPlatform.value = false+ render(<AdvisorButton projectRef="project-ref" />)++ expect(mockUseNotificationsV2Query).toHaveBeenCalledWith(+ { filters: {}, limit: 20 },+ { enabled: false }+ )})})diff --git a/apps/studio/components/layouts/AppLayout/StatusBanner.test.tsx b/apps/studio/components/layouts/AppLayout/StatusBanner.test.tsxindex 38976d1a86a..9c2b849314f 100644--- a/apps/studio/components/layouts/AppLayout/StatusBanner.test.tsx+++ b/apps/studio/components/layouts/AppLayout/StatusBanner.test.tsx@@ -153,32 +153,7 @@ describe('StatusBanner', () => {})})- test('dismissing hides the banner and writes the dismissed key to local storage', async () => {- mswServer.use(- http.get(`${BASE_PATH}/api/status-page`, () =>- HttpResponse.json<StatusPageResponse>(- buildStatusPage({ ongoing_incidents: [buildIncident({ id: 'inc-1' })] })- )- )- )- mockOrgProjectEndpoints()-- customRender(<StatusBanner />, { profileContext: createMockProfileContext() })-- await screen.findByText(INCIDENT_TITLE)-- fireEvent.click(screen.getByRole('button', { name: 'Dismiss banner' }))-- await waitFor(() => {- expect(screen.queryByText(INCIDENT_TITLE)).not.toBeInTheDocument()- })-- expect(JSON.parse(window.localStorage.getItem('status-banner-dismissed-keys') ?? '[]')).toEqual(- ['incident:inc-1']- )- })-- test('a new incident brings the banner back even though the previous one is dismissed', async () => {+ test('dismissing persists the incident key, and a new incident brings the banner back', async () => {const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })mswServer.use(@@ -199,6 +174,9 @@ describe('StatusBanner', () => {await waitFor(() => {expect(screen.queryByText(INCIDENT_TITLE)).not.toBeInTheDocument()})+ expect(JSON.parse(window.localStorage.getItem('status-banner-dismissed-keys') ?? '[]')).toEqual(+ ['incident:inc-1']+ )mswServer.use(http.get(`${BASE_PATH}/api/status-page`, () =>diff --git a/apps/studio/components/layouts/ExplorerLayout/ExplorerNavHeader.test.tsx b/apps/studio/components/layouts/ExplorerLayout/ExplorerNavHeader.test.tsxindex 2f64ebd68c0..024990322ea 100644--- a/apps/studio/components/layouts/ExplorerLayout/ExplorerNavHeader.test.tsx+++ b/apps/studio/components/layouts/ExplorerLayout/ExplorerNavHeader.test.tsx@@ -34,10 +34,9 @@ function renderHeader(section?: ExplorerResourceType) {describe('Explorer sidebar header', () => {beforeEach(() => vi.clearAllMocks())- it('shows the smaller root title with the preferences action', () => {+ it('shows the root title with the preferences action and no breadcrumb', () => {renderHeader()expect(screen.getAllByText('Explorer')).toHaveLength(1)- expect(screen.getByText('Explorer')).toHaveClass('text-sm')expect(screen.getByText('Explorer preferences')).toBeInTheDocument()expect(screen.queryByRole('button')).not.toBeInTheDocument()})@@ -76,10 +75,4 @@ describe('Explorer sidebar header', () => {expect(level === 'notebook' ? createChat : createNotebook).not.toHaveBeenCalled()})-- it('keeps the default title and badge for other product sidebars', () => {- customRender(<ProductMenuBar title="Database" titleBadge={<span>Preview</span>} />)- expect(screen.getByRole('heading', { name: 'Database' })).toHaveClass('text-sm')- expect(screen.getByText('Preview')).toBeInTheDocument()- })})diff --git a/apps/studio/components/layouts/Navigation/FloatingMobileToolbar/FloatingMobileToolbar.utils.test.ts b/apps/studio/components/layouts/Navigation/FloatingMobileToolbar/FloatingMobileToolbar.utils.test.tsindex 72d80284e41..08b8cbb820f 100644--- a/apps/studio/components/layouts/Navigation/FloatingMobileToolbar/FloatingMobileToolbar.utils.test.ts+++ b/apps/studio/components/layouts/Navigation/FloatingMobileToolbar/FloatingMobileToolbar.utils.test.ts@@ -72,27 +72,12 @@ describe('getToolbarStyle', () => {const viewport = { width: 390, height: 844 }const navSize = { width: 200, height: 48 }- it('returns style with transform and zIndex', () => {- const style = getToolbarStyle({- position: null,- navSize,- isSheetOpen: false,- viewport,- isDragging: false,- })- expect(style.zIndex).toBe(41)- expect(style.transform).toBeDefined()- expect(style.left).toBe('50%')- })+ it('centers the toolbar by default and raises it above an open sheet', () => {+ const base = { position: null, navSize, viewport, isDragging: false }+ const closed = getToolbarStyle({ ...base, isSheetOpen: false })+ const open = getToolbarStyle({ ...base, isSheetOpen: true })- it('uses higher zIndex when sheet open', () => {- const style = getToolbarStyle({- position: null,- navSize,- isSheetOpen: true,- viewport,- isDragging: false,- })- expect(style.zIndex).toBe(101)+ expect(closed.left).toBe('50%')+ expect(Number(open.zIndex)).toBeGreaterThan(Number(closed.zIndex))})})diff --git a/apps/studio/components/layouts/Navigation/LayoutHeader/LocalVersionPopover.test.ts b/apps/studio/components/layouts/Navigation/LayoutHeader/LocalVersionPopover.test.tsindex 7288c17190e..afcc45c46a8 100644--- a/apps/studio/components/layouts/Navigation/LayoutHeader/LocalVersionPopover.test.ts+++ b/apps/studio/components/layouts/Navigation/LayoutHeader/LocalVersionPopover.test.ts@@ -2,50 +2,28 @@ import { describe, expect, test } from 'vitest'import { semverGte, semverLte } from './LocalVersionPopover.utils'+const v = (version: string) => {+ const [major, minor, patch] = version.split('.').map(Number)+ return { major, minor, patch }+}+describe('LocalVersionPopover.utils:semverLte', () => {- test('1.2.2 should be lower than 2.1.1', () => {- const version = { major: 1, minor: 2, patch: 2 }- const versionCompare = { major: 2, minor: 1, patch: 1 }- const result = semverLte(version, versionCompare)- expect(result).toBe(true)- })- test('2.1.0 should not be lower than 1.0.0', () => {- const version = { major: 2, minor: 1, patch: 0 }- const versionCompare = { major: 1, minor: 0, patch: 0 }- const result = semverLte(version, versionCompare)- expect(result).toBe(false)- })- test('2.1.2 should not be lower than 1.99.99', () => {- const version = { major: 2, minor: 1, patch: 2 }- const versionCompare = { major: 1, minor: 99, patch: 99 }- const result = semverLte(version, versionCompare)- expect(result).toBe(false)- })- test('Same value comparison should return true', () => {- const version = { major: 2, minor: 1, patch: 2 }- const versionCompare = { major: 2, minor: 1, patch: 2 }- const result = semverLte(version, versionCompare)- expect(result).toBe(true)+ test.each([+ ['1.2.2', '2.1.1', true],+ ['2.1.0', '1.0.0', false],+ ['2.1.2', '1.99.99', false],+ ['2.1.2', '2.1.2', true],+ ])('%s <= %s is %s', (version, compare, expected) => {+ expect(semverLte(v(version), v(compare))).toBe(expected)})})describe('LocalVersionPopover.utils:semverGte', () => {- test('2.0.0 should be greater than 1.99.99', () => {- const version = { major: 2, minor: 0, patch: 0 }- const versionCompare = { major: 1, minor: 99, patch: 99 }- const result = semverGte(version, versionCompare)- expect(result).toBe(true)- })- test('1.99.99 should be not be greater than 2.0.1', () => {- const version = { major: 1, minor: 99, patch: 99 }- const versionCompare = { major: 2, minor: 0, patch: 1 }- const result = semverGte(version, versionCompare)- expect(result).toBe(false)- })- test('Same value comparison should return true', () => {- const version = { major: 2, minor: 1, patch: 2 }- const versionCompare = { major: 2, minor: 1, patch: 2 }- const result = semverLte(version, versionCompare)- expect(result).toBe(true)+ test.each([+ ['2.0.0', '1.99.99', true],+ ['1.99.99', '2.0.1', false],+ ['2.1.2', '2.1.2', true],+ ])('%s >= %s is %s', (version, compare, expected) => {+ expect(semverGte(v(version), v(compare))).toBe(expected)})})diff --git a/apps/studio/components/layouts/Navigation/NavigationBar/NavigationBar.utils.test.tsx b/apps/studio/components/layouts/Navigation/NavigationBar/NavigationBar.utils.test.tsxindex 87e77c8f312..f600bb5c817 100644--- a/apps/studio/components/layouts/Navigation/NavigationBar/NavigationBar.utils.test.tsx+++ b/apps/studio/components/layouts/Navigation/NavigationBar/NavigationBar.utils.test.tsx@@ -70,16 +70,6 @@ describe('useGenerateToolRoutes', () => {})describe('generateProductRoutes', () => {- it('includes all product routes when all features are enabled', () => {- const routes = generateProductRoutes(REF, activeProject, {- auth: true,- storage: true,- edgeFunctions: true,- realtime: true,- })- expect(keys(routes)).toEqual(['database', 'auth', 'storage', 'functions', 'realtime'])- })-it('includes all product routes by default (features default to true)', () => {const routes = generateProductRoutes(REF, activeProject)expect(keys(routes)).toEqual(['database', 'auth', 'storage', 'functions', 'realtime'])@@ -95,27 +85,15 @@ describe('generateProductRoutes', () => {expect(routes.filter((r) => !r.shortcutId)).toEqual([])})- it('excludes auth when auth feature is disabled', () => {- const routes = generateProductRoutes(REF, activeProject, { auth: false })- expect(keys(routes)).not.toContain('auth')-+ it.each([+ ['auth', 'auth'],+ ['storage', 'storage'],+ ['edgeFunctions', 'functions'],+ ['realtime', 'realtime'],+ ] as const)('excludes %s when its feature is disabled', (feature, key) => {+ const routes = generateProductRoutes(REF, activeProject, { [feature]: false })+ expect(keys(routes)).not.toContain(key)expect(keys(routes)).toContain('database')- expect(keys(routes)).toContain('storage')- })-- it('excludes storage when storage feature is disabled', () => {- const routes = generateProductRoutes(REF, activeProject, { storage: false })- expect(keys(routes)).not.toContain('storage')- })-- it('excludes edge functions when edgeFunctions feature is disabled', () => {- const routes = generateProductRoutes(REF, activeProject, { edgeFunctions: false })- expect(keys(routes)).not.toContain('functions')- })-- it('excludes realtime when realtime feature is disabled', () => {- const routes = generateProductRoutes(REF, activeProject, { realtime: false })- expect(keys(routes)).not.toContain('realtime')})it('links auth to overview page when authOverviewPage is enabled', () => {diff --git a/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.test.tsx b/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.test.tsxindex a61aa7a3b8e..03adcbb0ced 100644--- a/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.test.tsx+++ b/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.test.tsx@@ -60,54 +60,35 @@ describe('useGenerateObservabilityMenu', () => {vi.mocked(useIsFeatureEnabled).mockReturnValue(true)})- it('always includes the GENERAL section', () => {+ const getGeneralKeys = () => {const { result } = renderHook(() => useGenerateObservabilityMenu())+ return result.current+ .find((section) => section.title === 'GENERAL')+ ?.items.map((item) => item.key)+ }- expect(result.current.some((section) => section.title === 'GENERAL')).toBe(true)- })-- it('includes Overview when the observabilityOverview flag is enabled', () => {- vi.mocked(useFlag).mockReturnValue(true)-- const { result } = renderHook(() => useGenerateObservabilityMenu())- const general = result.current.find((section) => section.title === 'GENERAL')-- expect(general?.items.some((item) => item.key === 'observability')).toBe(true)- })-- it('excludes Overview when the observabilityOverview flag is disabled', () => {+ it('includes Overview only when the observabilityOverview flag is enabled', () => {vi.mocked(useFlag).mockReturnValue(false)+ expect(getGeneralKeys()).not.toContain('observability')- const { result } = renderHook(() => useGenerateObservabilityMenu())- const general = result.current.find((section) => section.title === 'GENERAL')-- expect(general?.items.some((item) => item.key === 'observability')).toBe(false)+ vi.mocked(useFlag).mockReturnValue(true)+ expect(getGeneralKeys()).toContain('observability')})- it('shows Query Performance when supamonitor is disabled', () => {+ it('shows Query Performance or Query Insights depending on supamonitor', () => {vi.mocked(useSupamonitorStatus).mockReturnValue({isSupamonitorEnabled: false,isLoading: false,})+ expect(getGeneralKeys()).toContain('query-performance')+ expect(getGeneralKeys()).not.toContain('query-insights')- const { result } = renderHook(() => useGenerateObservabilityMenu())- const general = result.current.find((section) => section.title === 'GENERAL')-- expect(general?.items.some((item) => item.key === 'query-performance')).toBe(true)- expect(general?.items.some((item) => item.key === 'query-insights')).toBe(false)- })-- it('shows Query Insights when supamonitor is enabled', () => {vi.mocked(useSupamonitorStatus).mockReturnValue({isSupamonitorEnabled: true,isLoading: false,})-- const { result } = renderHook(() => useGenerateObservabilityMenu())- const general = result.current.find((section) => section.title === 'GENERAL')-- expect(general?.items.some((item) => item.key === 'query-insights')).toBe(true)- expect(general?.items.some((item) => item.key === 'query-performance')).toBe(false)+ expect(getGeneralKeys()).toContain('query-insights')+ expect(getGeneralKeys()).not.toContain('query-performance')})it('includes API Gateway and the PRODUCT section on platform', () => {@@ -131,23 +112,20 @@ describe('useGenerateObservabilityMenu', () => {expect(result.current.length).toBe(1)})- it('includes Storage in the PRODUCT section when project_storage:all is enabled', () => {- vi.mocked(useIsFeatureEnabled).mockReturnValue(true)-- const { result } = renderHook(() => useGenerateObservabilityMenu())- const product = result.current.find((section) => section.title === 'PRODUCT')+ it('includes Storage in the PRODUCT section only when project_storage:all is enabled', () => {+ const getProductKeys = () => {+ const { result } = renderHook(() => useGenerateObservabilityMenu())+ return result.current+ .find((section) => section.title === 'PRODUCT')+ ?.items.map((item) => item.key)+ }- expect(product?.items.some((item) => item.key === 'storage')).toBe(true)+ vi.mocked(useIsFeatureEnabled).mockReturnValue(true)+ expect(getProductKeys()).toContain('storage')expect(useIsFeatureEnabled).toHaveBeenCalledWith('project_storage:all')- })- it('excludes Storage from the PRODUCT section when project_storage:all is disabled', () => {vi.mocked(useIsFeatureEnabled).mockReturnValue(false)-- const { result } = renderHook(() => useGenerateObservabilityMenu())- const product = result.current.find((section) => section.title === 'PRODUCT')-- expect(product?.items.some((item) => item.key === 'storage')).toBe(false)+ expect(getProductKeys()).not.toContain('storage')})it('always includes Database, Data API, Auth, Edge Functions, and Realtime in the PRODUCT section', () => {@@ -167,16 +145,6 @@ describe('useGenerateObservabilityMenu', () => {expect(database?.url).toBe(`/project/${REF}/observability/database`)})- it('handles an undefined project ref', () => {- vi.mocked(useParams).mockReturnValue({ ref: undefined })-- const { result } = renderHook(() => useGenerateObservabilityMenu())- const product = result.current.find((section) => section.title === 'PRODUCT')- const database = product?.items.find((item) => item.key === 'database')-- expect(database?.url).toBe('/project/undefined/observability/database')- })-it('preserves date range and helper query params across menu item URLs', () => {routerMock.setCurrentUrl(`/project/${REF}/observability?its=2024-01-01&ite=2024-01-31&isHelper=true&helperText=hello`diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/MobileMenuContent/MobileMenuContent.test.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/MobileMenuContent/MobileMenuContent.test.tsxindex f7048911f4c..bff54c1f0d0 100644--- a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/MobileMenuContent/MobileMenuContent.test.tsx+++ b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/MobileMenuContent/MobileMenuContent.test.tsx@@ -111,20 +111,7 @@ describe('Mobile product header', () => {})- it('hides the current product header in the top-level menu and other product sections', async () => {- const user = userEvent.setup()- customRender(<ExplorerMobileMenu initialSection="notebook" />)-- await user.click(screen.getByRole('button', { name: 'Back to menu' }))- expect(- screen.queryByRole('navigation', { name: 'Explorer navigation' })- ).not.toBeInTheDocument()- await user.click(screen.getByRole('button', { name: 'Database' }))- expect(screen.getByText('Database menu')).toBeInTheDocument()- expect(screen.queryByRole('button', { name: 'New notebook' })).not.toBeInTheDocument()- })-- it('names the project menu dialog across top-level and section navigation', async () => {+ it('names the project menu dialog and hides the Explorer header outside Explorer', async () => {const user = userEvent.setup()customRender(<ExplorerMobileMenu initialSection="notebook" />)@@ -132,6 +119,9 @@ describe('Mobile product header', () => {expect(screen.getAllByRole('heading', { name: 'Project menu' })).toHaveLength(1)await user.click(screen.getByRole('button', { name: 'Back to menu' }))+ expect(+ screen.queryByRole('navigation', { name: 'Explorer navigation' })+ ).not.toBeInTheDocument()expect(screen.getByRole('navigation', { name: 'Project menu' })).toBeInTheDocument()expect(screen.getByRole('dialog', { name: 'Project menu' })).toBeInTheDocument()@@ -139,5 +129,6 @@ describe('Mobile product header', () => {expect(screen.getByText('Database menu')).toBeInTheDocument()expect(screen.getByRole('dialog', { name: 'Project menu' })).toBeInTheDocument()expect(screen.getAllByRole('heading', { name: 'Project menu' })).toHaveLength(1)+ expect(screen.queryByRole('button', { name: 'New notebook' })).not.toBeInTheDocument()})})diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/index.test.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/index.test.tsxindex 01741276e7c..112a64ecd1f 100644--- a/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/index.test.tsx+++ b/apps/studio/components/layouts/ProjectLayout/LayoutSidebar/index.test.tsx@@ -148,25 +148,15 @@ describe('LayoutSidebar', () => {mockProjectData = mockProject})- it('does not register project-related sidebars when no project is available', async () => {- renderSidebar()-- // Wait a bit to ensure sidebars have been registered- await waitFor(() => {- // Project-related sidebars should not be registered- expect(sidebarManagerState.sidebars[SIDEBAR_KEYS.AI_ASSISTANT]).toBeUndefined()- expect(sidebarManagerState.sidebars[SIDEBAR_KEYS.EDITOR_PANEL]).toBeUndefined()- // Advisor panel should still be available (doesn't require project)- expect(sidebarManagerState.sidebars[SIDEBAR_KEYS.ADVISOR_PANEL]).toBeDefined()- })- })-- it('does not render project-related sidebars even when toggled', async () => {+ it('registers only the advisor panel, so project-related sidebars cannot be toggled', async () => {renderSidebar()+ // Advisor panel doesn't require a project, so it is still registeredawait waitFor(() => {expect(sidebarManagerState.sidebars[SIDEBAR_KEYS.ADVISOR_PANEL]).toBeDefined()})+ expect(sidebarManagerState.sidebars[SIDEBAR_KEYS.AI_ASSISTANT]).toBeUndefined()+ expect(sidebarManagerState.sidebars[SIDEBAR_KEYS.EDITOR_PANEL]).toBeUndefined()// Try to toggle AI_ASSISTANT - should not work since it's not registeredact(() => {diff --git a/apps/studio/components/layouts/ProjectLayout/OrganizationSettingsLayout.test.ts b/apps/studio/components/layouts/ProjectLayout/OrganizationSettingsLayout.test.tsindex 4022b3ee12e..3d96fd661ef 100644--- a/apps/studio/components/layouts/ProjectLayout/OrganizationSettingsLayout.test.ts+++ b/apps/studio/components/layouts/ProjectLayout/OrganizationSettingsLayout.test.ts@@ -111,23 +111,6 @@ describe('OrganizationSettingsLayout helpers', () => {expect(linkByKey('documents')?.shortcutId).toBe(SHORTCUT_IDS.NAV_ORG_SETTINGS_DOCUMENTS)})- it('omits feature-flagged links (and their shortcutIds) when flags are off', () => {- const sections = generateOrganizationSettingsSections({- slug: 'my-org',- currentPath: '/org/my-org/general',- showSecuritySettings: false,- showSsoSettings: false,- showLegalDocuments: false,- })-- const allLinks = sections.flatMap((s) => s.links)- const keys = allLinks.map((l) => l.key)-- expect(keys).not.toContain('security')- expect(keys).not.toContain('sso')- expect(keys).not.toContain('documents')- })-it('keeps webhooks nav item active for nested endpoint routes', () => {const sections = generateOrganizationSettingsSections({slug: 'my-org',diff --git a/apps/studio/components/layouts/ProjectLayout/RestoringState.test.tsx b/apps/studio/components/layouts/ProjectLayout/RestoringState.test.tsxindex fe05297d03f..c810108f545 100644--- a/apps/studio/components/layouts/ProjectLayout/RestoringState.test.tsx+++ b/apps/studio/components/layouts/ProjectLayout/RestoringState.test.tsx@@ -1,9 +1,9 @@-import { screen, waitFor } from '@testing-library/react'+import { act, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { platformComponents as components } from 'api-types'import { LOCAL_STORAGE_KEYS } from 'common'import { HttpResponse } from 'msw'-import { beforeEach, describe, expect, test } from 'vitest'+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'import { POLL_INTERVAL_MS, RestoringState } from './RestoringState'import { customRender } from '@/tests/lib/custom-render'@@ -15,8 +15,6 @@ type DownloadableBackupsResponse = components['schemas']['DownloadableBackupsResconst PROJECT_REF = 'default'-const SETTLE_MS = 2000-const createProject = (status: ProjectStatus): ProjectDetailResponse => ({cloud_provider: 'AWS',connectionString: `postgresql://postgres:password@db.${PROJECT_REF}.supabase.co:5432/postgres`,@@ -54,13 +52,21 @@ const mockProjectDetail = (statuses: [ProjectStatus, ...ProjectStatus[]]) => {const mockProjectStatus = (statuses: [ProjectStatus, ...ProjectStatus[]]) => {const nextStatus = createStatusSequence(statuses)+ const requests = { count: 0 }addAPIMock({method: 'get',path: '/platform/projects/:ref/status',- response: () => HttpResponse.json({ status: nextStatus() }),+ response: () => {+ requests.count += 1+ return HttpResponse.json({ status: nextStatus() })+ },})+ return requests}+// Advances past one status poll so the next queued status is fetched+const advancePoll = () => act(() => vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS))+const mockDownloadableBackups = () => {addAPIMock({method: 'get',@@ -83,64 +89,45 @@ const mockDownloadableBackups = () => {describe('RestoringState', () => {beforeEach(() => {+ // Status polling runs on a 4s interval; fake timers avoid waiting on it in real time+ vi.useFakeTimers({ shouldAdvanceTime: true })window.localStorage.clear()mockDownloadableBackups()})+ afterEach(() => {+ vi.useRealTimers()+ })+test('shows restoration in progress while the backend reports RESTORING', async () => {mockProjectDetail(['RESTORING'])- mockProjectStatus(['RESTORING'])+ const statusRequests = mockProjectStatus(['RESTORING'])customRender(<RestoringState />)expect(await screen.findByText('Restoration in progress')).toBeInTheDocument()+ // A second poll only fires after the first response has been rendered+ await advancePoll()+ await waitFor(() => expect(statusRequests.count).toBe(2))expect(screen.queryByText('Restoration complete!')).not.toBeInTheDocument()})- test('shows restoration complete once the project goes healthy after restoring', async () => {+ test('ignores an early stale healthy reading and only completes once the restore actually finishes', async () => {mockProjectDetail(['RESTORING'])- mockProjectStatus(['RESTORING', 'ACTIVE_HEALTHY'])+ const statusRequests = mockProjectStatus(['ACTIVE_HEALTHY', 'RESTORING', 'ACTIVE_HEALTHY'])customRender(<RestoringState />)expect(await screen.findByText('Restoration in progress')).toBeInTheDocument()- expect(- await screen.findByText('Restoration complete!', {}, { timeout: POLL_INTERVAL_MS + 2000 })- ).toBeInTheDocument()- })-- test('does not claim completion when the first status poll still reports the pre-restore healthy state', async () => {- mockProjectDetail(['RESTORING'])- mockProjectStatus(['ACTIVE_HEALTHY', 'RESTORING'])-- customRender(<RestoringState />)+ // A second poll only fires after the stale healthy response has been rendered+ await advancePoll()+ await waitFor(() => expect(statusRequests.count).toBe(2))+ expect(screen.queryByText('Restoration complete!')).not.toBeInTheDocument()- await expect(- screen.findByText('Restoration complete!', {}, { timeout: SETTLE_MS })- ).rejects.toThrow()- expect(screen.getByText('Restoration in progress')).toBeInTheDocument()+ await advancePoll()+ expect(await screen.findByText('Restoration complete!')).toBeInTheDocument()})- test(- 'still reaches completion after an early healthy reading, once the restore actually finishes',- async () => {- mockProjectDetail(['RESTORING'])- mockProjectStatus(['ACTIVE_HEALTHY', 'RESTORING', 'ACTIVE_HEALTHY'])-- customRender(<RestoringState />)-- expect(await screen.findByText('Restoration in progress')).toBeInTheDocument()- expect(- await screen.findByText(- 'Restoration complete!',- {},- { timeout: POLL_INTERVAL_MS * 3 + SETTLE_MS }- )- ).toBeInTheDocument()- },- POLL_INTERVAL_MS * 3 + SETTLE_MS * 2- )-test('clears the persisted restore start time when the restore fails', async () => {const storageKey = LOCAL_STORAGE_KEYS.PROJECT_RESTORING_STARTED_AT(PROJECT_REF)window.localStorage.setItem(storageKey, String(Date.now()))@@ -154,25 +141,22 @@ describe('RestoringState', () => {})})- test(- 'does not leave Return to project stuck loading when the details still report restoring',- async () => {- mockProjectDetail(['RESTORING'])- mockProjectStatus(['RESTORING', 'ACTIVE_HEALTHY'])+ test('completes after restoring and does not leave Return to project stuck loading when the details still report restoring', async () => {+ mockProjectDetail(['RESTORING'])+ mockProjectStatus(['RESTORING', 'ACTIVE_HEALTHY'])- customRender(<RestoringState />)+ customRender(<RestoringState />)- const returnToProject = await screen.findByRole(- 'button',- { name: 'Return to project' },- { timeout: POLL_INTERVAL_MS + SETTLE_MS }- )- await userEvent.click(returnToProject)+ expect(await screen.findByText('Restoration in progress')).toBeInTheDocument()+ await advancePoll()+ expect(await screen.findByText('Restoration complete!')).toBeInTheDocument()- await waitFor(() => {- expect(returnToProject).not.toBeDisabled()- })- },- POLL_INTERVAL_MS + SETTLE_MS * 2- )+ const returnToProject = screen.getByRole('button', { name: 'Return to project' })+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })+ await user.click(returnToProject)++ await waitFor(() => {+ expect(returnToProject).not.toBeDisabled()+ })+ })})diff --git a/apps/studio/components/layouts/ProjectLayout/index.test.tsx b/apps/studio/components/layouts/ProjectLayout/index.test.tsxindex b2606bd21e0..8752f1affb8 100644--- a/apps/studio/components/layouts/ProjectLayout/index.test.tsx+++ b/apps/studio/components/layouts/ProjectLayout/index.test.tsx@@ -412,7 +412,7 @@ describe('ProjectLayout title', () => {})})- it('renders the Stripe project banner across project surfaces when the selected project is Stripe-connected', () => {+ it('renders the Stripe project banner with a project-specific dismiss key when the selected project is Stripe-connected', () => {mockProjectState.current = {...mockProjectState.current,integration_source: 'stripe_projects',@@ -420,21 +420,11 @@ describe('ProjectLayout title', () => {renderLayout()- expect(screen.getByText('This project is connected to Stripe')).toBeTruthy()+ expect(screen.getByText('This project is connected to Stripe')).toBeInTheDocument()expect(screen.getByText('Changes made here may affect your connected Stripe project.')- ).toBeTruthy()- expect(screen.getByTestId('partner-icon')).toBeTruthy()- })-- it('uses a project-specific dismiss key for the Stripe project banner', () => {- mockProjectState.current = {- ...mockProjectState.current,- integration_source: 'stripe_projects',- }-- renderLayout()-+ ).toBeInTheDocument()+ expect(screen.getByTestId('partner-icon')).toBeInTheDocument()expect(mockUseLocalStorageQuery).toHaveBeenCalledWith(LOCAL_STORAGE_KEYS.PROJECT_INTEGRATION_BANNER_DISMISSED('default', 'stripe_projects'),false@@ -490,41 +480,34 @@ describe('FREE_MICRO_UPGRADE banner', () => {})})- it('calls dismissBanner when banner was previously dismissed', async () => {- mockBannerDismissedState.current = true-- renderLayout()-- await waitFor(() => {- expect(mockDismissBanner).toHaveBeenCalledWith('free-micro-upgrade-banner')- })- expect(mockAddBanner).not.toHaveBeenCalledWith(- expect.objectContaining({ id: 'free-micro-upgrade-banner' })- )- })-- it('calls dismissBanner when compute warnings are cleared', async () => {- mockResourceWarningsState.current = [- {- project: 'default',- cpu_exhaustion: false,- memory_and_swap_exhaustion: false,- disk_space_exhaustion: false,+ it.each([+ [+ 'the banner was previously dismissed',+ () => {+ mockBannerDismissedState.current = true},- ]-- renderLayout()-- await waitFor(() => {- expect(mockDismissBanner).toHaveBeenCalledWith('free-micro-upgrade-banner')- })- expect(mockAddBanner).not.toHaveBeenCalledWith(- expect.objectContaining({ id: 'free-micro-upgrade-banner' })- )- })-- it('calls dismissBanner when project is not nano compute', async () => {- mockProjectState.current = { ...mockProjectState.current, infra_compute_size: 'micro' }+ ],+ [+ 'compute warnings are cleared',+ () => {+ mockResourceWarningsState.current = [+ {+ project: 'default',+ cpu_exhaustion: false,+ memory_and_swap_exhaustion: false,+ disk_space_exhaustion: false,+ },+ ]+ },+ ],+ [+ 'the project is not nano compute',+ () => {+ mockProjectState.current = { ...mockProjectState.current, infra_compute_size: 'micro' }+ },+ ],+ ])('calls dismissBanner instead of addBanner when %s', async (_, arrange) => {+ arrange()renderLayout()diff --git a/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.test.tsx b/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.test.tsxindex adca7556778..d457ac65757 100644--- a/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.test.tsx+++ b/apps/studio/components/layouts/ProjectNeedsSecuring/ProjectNeedsSecuring.test.tsx@@ -208,55 +208,28 @@ describe('ProjectNeedsSecuring', () => {)})- it('renders the project content when the security gate has been dismissed', () => {- mockUseLocalStorageQuery.mockReturnValue([- '2026-04-21T00:00:00.000Z',- vi.fn(),- { isLoading: false },- ])-- render(- <ProjectNeedsSecuring>- <div data-testid="project-children">Project content</div>- </ProjectNeedsSecuring>- )-- expect(screen.queryByText('Your project needs securing')).not.toBeInTheDocument()- expect(screen.getByTestId('project-children')).toBeInTheDocument()- })-- it('renders the project content when there are no RLS issues', () => {- mockUseProjectLintsQuery.mockReturnValue({- data: [],- isPending: false,- isError: false,- })-- render(- <ProjectNeedsSecuring>- <div data-testid="project-children">Project content</div>- </ProjectNeedsSecuring>- )-- expect(screen.queryByText('Your project needs securing')).not.toBeInTheDocument()- expect(screen.getByTestId('project-children')).toBeInTheDocument()- })-- it('renders the project content on non-home project routes', () => {- mockUseRouter.mockReturnValue({ pathname: '/project/[ref]/database/tables' })-- render(- <ProjectNeedsSecuring>- <div data-testid="project-children">Project content</div>- </ProjectNeedsSecuring>- )-- expect(screen.queryByText('Your project needs securing')).not.toBeInTheDocument()- expect(screen.getByTestId('project-children')).toBeInTheDocument()- })-- it('renders the project content when the feature flag is disabled', () => {- mockUseFlag.mockReturnValue(false)+ it.each([+ [+ 'the security gate has been dismissed',+ () =>+ mockUseLocalStorageQuery.mockReturnValue([+ '2026-04-21T00:00:00.000Z',+ vi.fn(),+ { isLoading: false },+ ]),+ ],+ [+ 'there are no RLS issues',+ () =>+ mockUseProjectLintsQuery.mockReturnValue({ data: [], isPending: false, isError: false }),+ ],+ [+ 'on non-home project routes',+ () => mockUseRouter.mockReturnValue({ pathname: '/project/[ref]/database/tables' }),+ ],+ ['the feature flag is disabled', () => mockUseFlag.mockReturnValue(false)],+ ])('renders the project content when %s', (_, arrange) => {+ arrange()render(<ProjectNeedsSecuring>diff --git a/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.selfhosted.test.tsx b/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.selfhosted.test.tsxdeleted file mode 100644index b4cb5ee9b07..00000000000--- a/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.selfhosted.test.tsx+++ /dev/null@@ -1,117 +0,0 @@-import { renderHook } from '@testing-library/react'-import { beforeEach, describe, expect, it, vi } from 'vitest'--import { useGenerateSettingsMenu } from './SettingsMenu.utils'-import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'-import { SHORTCUT_IDS } from '@/state/shortcuts/registry'--const getShortcutId = (item: unknown) => (item as { shortcutId?: string } | undefined)?.shortcutId--vi.mock('@/lib/constants', async () => {- const actual = await vi.importActual<Record<string, unknown>>('@/lib/constants')- return {- ...actual,- IS_PLATFORM: false,- }-})--vi.mock('common', () => ({- useFlag: vi.fn().mockReturnValue(false),- useParams: vi.fn().mockReturnValue({ ref: 'project-ref' }),-}))--vi.mock('@/hooks/misc/useSelectedOrganization', () => ({- useSelectedOrganizationQuery: vi.fn().mockReturnValue({ data: { slug: 'my-org' } }),-}))--vi.mock('@/hooks/misc/useSelectedProject', () => ({- useSelectedProjectQuery: vi.fn().mockReturnValue({ data: { status: 'ACTIVE_HEALTHY' } }),-}))--vi.mock('@/hooks/misc/useIsFeatureEnabled', () => ({- useIsFeatureEnabled: vi.fn(),-}))--vi.mock('@/components/interfaces/App/FeaturePreview/FeaturePreviewContext', () => ({- useIsPlatformWebhooksEnabled: vi.fn().mockReturnValue(false),-}))--describe('useGenerateSettingsMenu (self-hosted)', () => {- beforeEach(() => {- vi.mocked(useIsFeatureEnabled).mockReturnValue({- projectSettingsLegacyJwtKeys: false,- billingAll: true,- logsAll: true,- projectSettingsLogDrains: true,- } as any)- })-- it('includes General, API Keys, JWT Keys, and Log Drains in self-hosted mode', () => {- const { result } = renderHook(() => useGenerateSettingsMenu())- const configGroup = result.current.find((group) => group.title === 'Configuration')-- expect(configGroup?.items.some((item) => item.key === 'general')).toBe(true)- expect(configGroup?.items.some((item) => item.key === 'api-keys')).toBe(true)- expect(configGroup?.items.some((item) => item.key === 'jwt')).toBe(true)- expect(configGroup?.items.some((item) => item.key === 'log-drains')).toBe(true)- expect(getShortcutId(configGroup?.items.find((item) => item.key === 'log-drains'))).toBe(- SHORTCUT_IDS.NAV_PROJECT_SETTINGS_LOG_DRAINS- )- })-- it('hides Log Drains in self-hosted mode when logs:all is disabled', () => {- vi.mocked(useIsFeatureEnabled).mockReturnValue({- projectSettingsLegacyJwtKeys: false,- billingAll: true,- logsAll: false,- projectSettingsLogDrains: true,- } as any)-- const { result } = renderHook(() => useGenerateSettingsMenu())- const configGroup = result.current.find((group) => group.title === 'Configuration')-- expect(configGroup?.items.some((item) => item.key === 'log-drains')).toBe(false)- })-- it('hides Log Drains in self-hosted mode when project_settings:log_drains is disabled', () => {- vi.mocked(useIsFeatureEnabled).mockReturnValue({- projectSettingsLegacyJwtKeys: false,- billingAll: true,- logsAll: true,- projectSettingsLogDrains: false,- } as any)-- const { result } = renderHook(() => useGenerateSettingsMenu())- const configGroup = result.current.find((group) => group.title === 'Configuration')-- expect(configGroup?.items.some((item) => item.key === 'log-drains')).toBe(false)- })-- it('includes Data API and Vault integrations in self-hosted mode', () => {- const { result } = renderHook(() => useGenerateSettingsMenu())- const integrationsGroup = result.current.find((group) => group.title === 'Integrations')-- expect(integrationsGroup?.items.some((item) => item.key === 'api')).toBe(true)- expect(integrationsGroup?.items.some((item) => item.key === 'vault')).toBe(true)- })-- it('does not include dashboard settings in self-hosted mode', () => {- const { result } = renderHook(() => useGenerateSettingsMenu())- const configGroup = result.current.find((group) => group.title === 'Configuration')-- expect(configGroup?.items.some((item) => item.key === 'dashboard')).toBe(false)- })-- it('does not include platform-only settings in self-hosted mode', () => {- const { result } = renderHook(() => useGenerateSettingsMenu())- const configGroup = result.current.find((group) => group.title === 'Configuration')-- expect(configGroup?.items.some((item) => item.key === 'infrastructure')).toBe(false)- expect(configGroup?.items.some((item) => item.key === 'addons')).toBe(false)- })-- it('does not include billing group in self-hosted mode', () => {- const { result } = renderHook(() => useGenerateSettingsMenu())- expect(result.current.some((group) => group.title === 'Billing')).toBe(false)- })-})diff --git a/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.test.tsx b/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.test.tsxindex 1ea61eb5e70..1359d1698a2 100644--- a/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.test.tsx+++ b/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.test.tsx@@ -9,11 +9,15 @@ import { SHORTCUT_IDS } from '@/state/shortcuts/registry'const getShortcutId = (item: unknown) => (item as { shortcutId?: string } | undefined)?.shortcutId+const { mockIsPlatform } = vi.hoisted(() => ({ mockIsPlatform: { value: true } }))+vi.mock('@/lib/constants', async () => {const actual = await vi.importActual<Record<string, unknown>>('@/lib/constants')return {...actual,- IS_PLATFORM: true,+ get IS_PLATFORM() {+ return mockIsPlatform.value+ },}})@@ -38,6 +42,69 @@ vi.mock('@/components/interfaces/App/FeaturePreview/FeaturePreviewContext', () =useIsPlatformWebhooksEnabled: vi.fn().mockReturnValue(true),}))+const FEATURES = {+ projectSettingsLegacyJwtKeys: false,+ billingAll: true,+ logsAll: true,+ projectSettingsLogDrains: true,+}++const getConfigurationKeys = () => {+ const { result } = renderHook(() => useGenerateSettingsMenu())+ return result.current+ .find((group) => group.title === 'Configuration')+ ?.items.map((item) => item.key)+}++beforeEach(() => {+ mockIsPlatform.value = true+})++describe.each([+ ['platform', true],+ ['self-hosted', false],+])('useGenerateSettingsMenu log drains (%s)', (_, isPlatform) => {+ beforeEach(() => {+ mockIsPlatform.value = isPlatform+ })++ it.each([+ [{}, true],+ [{ logsAll: false }, false],+ [{ projectSettingsLogDrains: false }, false],+ ])('with feature overrides %o shows log drains: %s', (overrides, expected) => {+ vi.mocked(useIsFeatureEnabled).mockReturnValue({ ...FEATURES, ...overrides } as any)+ expect(getConfigurationKeys()?.includes('log-drains')).toBe(expected)+ })+})++describe('useGenerateSettingsMenu (self-hosted)', () => {+ beforeEach(() => {+ mockIsPlatform.value = false+ vi.mocked(useIsPlatformWebhooksEnabled).mockReturnValue(false)+ vi.mocked(useIsFeatureEnabled).mockReturnValue(FEATURES as any)+ })++ it('includes only the self-hosted configuration items and integrations, with no billing group', () => {+ const { result } = renderHook(() => useGenerateSettingsMenu())+ const configGroup = result.current.find((group) => group.title === 'Configuration')+ const configKeys = configGroup?.items.map((item) => item.key)+ const integrationKeys = result.current+ .find((group) => group.title === 'Integrations')+ ?.items.map((item) => item.key)++ expect(configKeys).toEqual(expect.arrayContaining(['general', 'api-keys', 'jwt', 'log-drains']))+ expect(configKeys).not.toContain('dashboard')+ expect(configKeys).not.toContain('infrastructure')+ expect(configKeys).not.toContain('addons')+ expect(getShortcutId(configGroup?.items.find((item) => item.key === 'log-drains'))).toBe(+ SHORTCUT_IDS.NAV_PROJECT_SETTINGS_LOG_DRAINS+ )+ expect(integrationKeys).toEqual(expect.arrayContaining(['api', 'vault']))+ expect(result.current.some((group) => group.title === 'Billing')).toBe(false)+ })+})+describe('useGenerateSettingsMenu', () => {beforeEach(() => {vi.mocked(useFlag).mockReturnValue(false)@@ -122,41 +189,6 @@ describe('useGenerateSettingsMenu', () => {expect(configurationGroup?.items.some((item) => item.name === 'Dashboard')).toBe(false)})- it('includes log drains when logs:all and project_settings:log_drains are enabled', () => {- const { result } = renderHook(() => useGenerateSettingsMenu())- const configurationGroup = result.current.find((group) => group.title === 'Configuration')-- expect(configurationGroup?.items.some((item) => item.key === 'log-drains')).toBe(true)- })-- it('hides log drains when logs:all is disabled', () => {- vi.mocked(useIsFeatureEnabled).mockReturnValue({- projectSettingsLegacyJwtKeys: false,- billingAll: true,- logsAll: false,- projectSettingsLogDrains: true,- } as any)-- const { result } = renderHook(() => useGenerateSettingsMenu())- const configurationGroup = result.current.find((group) => group.title === 'Configuration')-- expect(configurationGroup?.items.some((item) => item.key === 'log-drains')).toBe(false)- })-- it('hides log drains when project_settings:log_drains is disabled', () => {- vi.mocked(useIsFeatureEnabled).mockReturnValue({- projectSettingsLegacyJwtKeys: false,- billingAll: true,- logsAll: true,- projectSettingsLogDrains: false,- } as any)-- const { result } = renderHook(() => useGenerateSettingsMenu())- const configurationGroup = result.current.find((group) => group.title === 'Configuration')-- expect(configurationGroup?.items.some((item) => item.key === 'log-drains')).toBe(false)- })-it('adds shortcuts to eligible configuration settings items', () => {vi.mocked(useFlag).mockReturnValue(true)diff --git a/apps/studio/components/layouts/SQLEditorLayout/SqlEditor.Commands.test.tsx b/apps/studio/components/layouts/SQLEditorLayout/SqlEditor.Commands.test.tsxindex a0e673cb209..7de27006cf3 100644--- a/apps/studio/components/layouts/SQLEditorLayout/SqlEditor.Commands.test.tsx+++ b/apps/studio/components/layouts/SQLEditorLayout/SqlEditor.Commands.test.tsx@@ -173,22 +173,7 @@ describe('useQueryTableCommands', () => {}})- it('does not prefetch tables when the menu closes', async () => {- mockProjectDetail(() => HttpResponse.json<ProjectDetailResponse>(PROJECT))- const { prefetchQuery, rerender } = renderMountedMenu()-- rerender(<MenuToggle open />)-- await waitFor(() => {- expect(prefetchQuery).toHaveBeenCalledTimes(1)- })-- rerender(<MenuToggle open={false} />)-- expect(prefetchQuery).toHaveBeenCalledTimes(1)- })-- it('prefetches tables again when the menu reopens', async () => {+ it('does not prefetch on close, and prefetches again when the menu reopens', async () => {mockProjectDetail(() => HttpResponse.json<ProjectDetailResponse>(PROJECT))const { prefetchQuery, rerender } = renderMountedMenu()diff --git a/apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx b/apps/studio/components/layouts/Tabs/Tabs.utils.test.tsxindex a89fd1bdfb0..eaea7b79313 100644--- a/apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx+++ b/apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx@@ -71,16 +71,6 @@ describe('useSqlEditorTabsCleanup', () => {expect(store.tabsMap['sql-logs-live']).toBeDefined()})- it('keeps a logs tab that still exists in the snippet list', () => {- const store = createTabsState('default')- store.addTab(logsTab('logs'))-- const cleanup = renderCleanup(store)- act(() => cleanup({ snippets: [{ id: 'logs', type: 'log_sql', name: 'logs' }] }))-- expect(store.openTabs).toEqual(['sql-logs'])- })-it('preserves logs tabs when logs snippets are not authoritative (canPruneLogsTabs false)', () => {const store = createTabsState('default')store.addTab(dbTab('db-stale'))diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.test.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.test.tsindex e7c9eaa7d25..80a5ff5c3c4 100644--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.test.ts+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.test.ts@@ -30,63 +30,29 @@ const pendingSqlApprovalPart = {} satisfies UIMessage['parts'][number]describe('AIAssistant.utils.ts:isReadOnlySelect', () => {- test('Should return true for SQL that only contains SELECT operation', () => {- const sql = 'select * from countries where id > 100 order by id asc;'- const result = isReadOnlySelect(sql)- expect(result).toBe(true)- })- test('Should return false for SQL that contains INSERT operation', () => {- const sql = `insert into countries (id, name) values (1, 'hello');`- const result = isReadOnlySelect(sql)- expect(result).toBe(false)- })- test('Should return false for SQL that contains UPDATE operation', () => {- const sql = `update countries set name = 'hello' where id = 2;`- const result = isReadOnlySelect(sql)- expect(result).toBe(false)- })- test('Should return false for SQL that contains DELETE operation', () => {- const sql = `delete from countries where id = 2;`- const result = isReadOnlySelect(sql)- expect(result).toBe(false)- })- test('Should return false for SQL that contains ALTER operation', () => {- const sql = `alter table countries drop column id if exists;`- const result = isReadOnlySelect(sql)- expect(result).toBe(false)- })- test('Should return false for SQL that contains DROP operation', () => {- const sql = `drop table if exists countries;`- const result = isReadOnlySelect(sql)- expect(result).toBe(false)- })- test('Should return false for SQL that contains CREATE operation', () => {- const sql = `create schema test_schema;`- const result = isReadOnlySelect(sql)- expect(result).toBe(false)- })- test('Should return false for SQL that contains REPLACE operation', () => {- const sql = `create or replace view test_view as select * from countries where id > 500;`- const result = isReadOnlySelect(sql)- expect(result).toBe(false)- })- test('Should return false for SQL that calls a function not whitelisted', () => {- const sql = `select create_new_user();`- const result = isReadOnlySelect(sql)- expect(result).toBe(false)- })- test('Should return true for SQL that calls a function that is whitelisted', () => {- const sql = `select count(select * from countries);`- const result = isReadOnlySelect(sql)- expect(result).toBe(true)- })- test('Should return false for SQL that contains a write operation with a read operation', () => {- const sql1 = `select count(select * from countries); create schema joshen;`- const result1 = isReadOnlySelect(sql1)- expect(result1).toBe(false)- const sql2 = `create schema joshen; select count(select * from countries);`- const result2 = isReadOnlySelect(sql2)- expect(result2).toBe(false)+ test.each([+ 'select * from countries where id > 100 order by id asc;',+ // whitelisted function+ 'select count(select * from countries);',+ ])('returns true for read-only SQL: %s', (sql) => {+ expect(isReadOnlySelect(sql)).toBe(true)+ })++ test.each([+ `insert into countries (id, name) values (1, 'hello');`,+ `update countries set name = 'hello' where id = 2;`,+ `delete from countries where id = 2;`,+ `alter table countries drop column id if exists;`,+ `drop table if exists countries;`,+ `create schema test_schema;`,+ `create or replace view test_view as select * from countries where id > 500;`,+ // function that is not whitelisted+ `select create_new_user();`,+ // write mixed with a read, in either order+ `select count(select * from countries); create schema joshen;`,+ `create schema joshen; select count(select * from countries);`,+ ])('returns false for SQL that may write: %s', (sql) => {+ expect(isReadOnlySelect(sql)).toBe(false)})})diff --git a/apps/studio/components/ui/AIAssistantPanel/Confirm.test.tsx b/apps/studio/components/ui/AIAssistantPanel/Confirm.test.tsxindex 61b2cecb93a..6a558f0bc60 100644--- a/apps/studio/components/ui/AIAssistantPanel/Confirm.test.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/Confirm.test.tsx@@ -5,29 +5,28 @@ import { Confirm } from './Confirm'import { customRender as render } from '@/tests/lib/custom-render'describe('Confirm', () => {- it('keeps its content visible and replaces actions with a success status', () => {- render(- <Confirm state="success" message="Run query" successMessage="Query executed">- <div>Query preview</div>- </Confirm>- )-- expect(screen.getByText('Query preview')).toBeInTheDocument()- expect(screen.getByText('Query executed')).toBeInTheDocument()- expect(screen.queryByRole('button')).not.toBeInTheDocument()- })+ it.each([+ { state: 'success' as const, outcome: 'Query executed' },+ { state: 'error' as const, outcome: 'Failed to execute SQL' },+ ])(+ 'keeps its content visible and replaces actions with the $state status',+ ({ state, outcome }) => {+ render(+ <Confirm+ state={state}+ message="Run query"+ successMessage="Query executed"+ errorMessage="Failed to execute SQL"+ >+ <div>Query preview</div>+ </Confirm>+ )- it('keeps its content visible and replaces actions with an error status', () => {- render(- <Confirm state="error" message="Run query" errorMessage="Failed to execute SQL">- <div>Query preview</div>- </Confirm>- )-- expect(screen.getByText('Query preview')).toBeInTheDocument()- expect(screen.getByText('Failed to execute SQL')).toBeInTheDocument()- expect(screen.queryByRole('button')).not.toBeInTheDocument()- })+ expect(screen.getByText('Query preview')).toBeInTheDocument()+ expect(screen.getByText(outcome)).toBeInTheDocument()+ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ }+ )it('keeps the confirm and cancel buttons visible but disabled while loading after approval', () => {render(diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.Actions.test.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.Actions.test.tsxdeleted file mode 100644index 4f4bc36a194..00000000000--- a/apps/studio/components/ui/AIAssistantPanel/Message.Actions.test.tsx+++ /dev/null@@ -1,18 +0,0 @@-import { describe, expect, it } from 'vitest'--import { MessageActions } from './Message.Actions'-import { customRender } from '@/tests/lib/custom-render'--describe('MessageActions', () => {- it('uses the standard centered message width', () => {- const { container } = customRender(- <MessageActions>- <button type="button" tabIndex={0}>- Copy- </button>- </MessageActions>- )-- expect(container.firstChild).toHaveClass('w-full', 'max-w-3xl', 'mx-auto')- })-})diff --git a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsxindex 75ca96057e4..2c42d9cd1cb 100644--- a/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/NotebookProposalRenderer.test.tsx@@ -454,25 +454,6 @@ describe('NotebookProposalRenderer', () => {expect(screen.queryByRole('button', { name: 'Added Markdown cell' })).not.toBeInTheDocument()})- it('falls back to the compact completed body when previous_content is absent', () => {- render(- <NotebookProposalRenderer- mode="update"- state="output-available"- input={{- id: NOTEBOOK_ID,- expected_updated_at: '2024-01-01T00:00:00.000Z',- operations: [{ _tag: 'delete_cell', cell_id: 'cell-1' }],- }}- output={{ id: NOTEBOOK_ID, name: 'Signup funnel' }}- />- )-- expect(screen.getByText('Notebook updated: Signup funnel')).toBeInTheDocument()- expect(screen.queryByText("This update can't be applied as written")).not.toBeInTheDocument()- expect(screen.getByRole('link', { name: 'Open notebook' })).toBeInTheDocument()- })-it('falls back to the compact completed body when the snapshot no longer matches the operations', () => {render(<NotebookProposalRendererdiff --git a/apps/studio/components/ui/Charts/useChartHoverState.test.tsx b/apps/studio/components/ui/Charts/useChartHoverState.test.tsxindex c887a82b30e..9571e21ad7c 100644--- a/apps/studio/components/ui/Charts/useChartHoverState.test.tsx+++ b/apps/studio/components/ui/Charts/useChartHoverState.test.tsx@@ -51,8 +51,9 @@ describe('useChartHoverState', () => {})it('should load sync settings from localStorage on initialization', async () => {- localStorageMock.setItem('supabase-chart-hover-sync-enabled', 'true')- localStorageMock.setItem('supabase-chart-tooltip-sync-enabled', 'true')+ // Defaults are true, so persist false to prove the stored values are read+ localStorageMock.setItem('supabase-chart-hover-sync-enabled', 'false')+ localStorageMock.setItem('supabase-chart-tooltip-sync-enabled', 'false')vi.resetModules()const { useChartHoverState: useChartHoverStateWithStorage } =@@ -60,8 +61,8 @@ describe('useChartHoverState', () => {const { result } = renderHook(() => useChartHoverStateWithStorage('chart1'))- expect(result.current.syncHover).toBe(true)- expect(result.current.syncTooltip).toBe(true)+ expect(result.current.syncHover).toBe(false)+ expect(result.current.syncTooltip).toBe(false)})it('should handle corrupted localStorage data gracefully', async () => {@@ -81,7 +82,7 @@ describe('useChartHoverState', () => {})describe('hover functionality', () => {- it('should set hover state locally when sync is disabled', () => {+ it('should set hover state for the current chart', () => {const { result } = renderHook(() => useChartHoverState('chart1'))act(() => {@@ -94,7 +95,7 @@ describe('useChartHoverState', () => {expect(result.current.isCurrentChart).toBe(true)})- it('should clear hover state locally when sync is disabled', () => {+ it('should clear hover state for the current chart', () => {const { result } = renderHook(() => useChartHoverState('chart1'))act(() => {@@ -129,6 +130,7 @@ describe('useChartHoverState', () => {expect(result2.current.hoveredIndex).toBe(3)expect(result2.current.hoveredChart).toBe('chart1')expect(result2.current.isCurrentChart).toBe(false)+ expect(result2.current.isHovered).toBe(true)})it('should clear synced hover state globally', () => {@@ -243,21 +245,6 @@ describe('useChartHoverState', () => {expect(result3.current.hoveredIndex).toBe(7)expect(result3.current.hoveredChart).toBe('chart2')})-- it('should correctly identify current chart vs synced charts', () => {- const { result: result1 } = renderHook(() => useChartHoverState('chart1'))- const { result: result2 } = renderHook(() => useChartHoverState('chart2'))-- act(() => {- result1.current.setSyncHover(true)- result1.current.setHover(5)- })-- expect(result1.current.isCurrentChart).toBe(true)- expect(result2.current.isCurrentChart).toBe(false)- expect(result1.current.isHovered).toBe(true)- expect(result2.current.isHovered).toBe(true)- })})describe('edge cases', () => {@@ -291,59 +278,5 @@ describe('useChartHoverState', () => {expect(result.current.hoveredIndex).toBe(4)expect(result.current.hoveredChart).toBe('chart1')})-- it('should not trigger unnecessary state updates when state is the same', () => {- const { result } = renderHook(() => useChartHoverState('chart1'))-- const initialSyncHover = result.current.syncHover-- act(() => {- result.current.setSyncHover(initialSyncHover)- })-- expect(result.current.syncHover).toBe(initialSyncHover)- })- })-- describe('helper functions', () => {- it('should correctly calculate isHovered for current chart', () => {- const { result } = renderHook(() => useChartHoverState('chart1'))-- expect(result.current.hoveredIndex).toBe(null)- expect(result.current.isHovered).toBe(false)-- act(() => {- result.current.setHover(5)- })-- expect(result.current.hoveredIndex).toBe(5)- expect(result.current.isHovered).toBe(true)- })-- it('should correctly calculate isHovered for synced charts', () => {- const { result: result1 } = renderHook(() => useChartHoverState('chart1'))- const { result: result2 } = renderHook(() => useChartHoverState('chart2'))-- act(() => {- result1.current.setSyncHover(true)- result1.current.setHover(5)- })-- expect(result1.current.isHovered).toBe(true) // Current chart- expect(result2.current.isHovered).toBe(true) // Synced chart- })-- it('should correctly identify current chart', () => {- const { result: result1 } = renderHook(() => useChartHoverState('chart1'))- const { result: result2 } = renderHook(() => useChartHoverState('chart2'))-- act(() => {- result1.current.setSyncHover(true)- result1.current.setHover(5)- })-- expect(result1.current.isCurrentChart).toBe(true)- expect(result2.current.isCurrentChart).toBe(false)- })})})diff --git a/apps/studio/components/ui/DataGridResults/__tests__/DataGridResults.utils.test.ts b/apps/studio/components/ui/DataGridResults/__tests__/DataGridResults.utils.test.tsindex ddbfd2a16b8..63410e7f51b 100644--- a/apps/studio/components/ui/DataGridResults/__tests__/DataGridResults.utils.test.ts+++ b/apps/studio/components/ui/DataGridResults/__tests__/DataGridResults.utils.test.ts@@ -69,70 +69,33 @@ describe('Results.utils', () => {})describe('formatCellValue', () => {- it('returns NULL for null', () => {- expect(formatCellValue(null)).toBe('NULL')- })-- it('returns strings as-is', () => {- expect(formatCellValue('hello')).toBe('hello')- })-- it('stringifies objects', () => {- expect(formatCellValue({ a: 1 })).toBe('{"a":1}')- })-- it('stringifies numbers', () => {- expect(formatCellValue(42)).toBe('42')- })-- it('stringifies booleans', () => {- expect(formatCellValue(true)).toBe('true')+ it.each([+ [null, 'NULL'],+ ['hello', 'hello'],+ [{ a: 1 }, '{"a":1}'],+ [42, '42'],+ [true, 'true'],+ ])('formats %j as %s', (value, expected) => {+ expect(formatCellValue(value)).toBe(expected)})})describe('isLargeValue', () => {- it('returns false for null', () => {- expect(isLargeValue(null)).toBe(false)- })-- it('returns false for undefined', () => {- expect(isLargeValue(undefined)).toBe(false)- })-- it('returns false for an empty string', () => {- expect(isLargeValue('')).toBe(false)- })-- it('returns false for a short string under the threshold', () => {- expect(isLargeValue('hello')).toBe(false)- })-- it('returns false for a string at the 60-char boundary', () => {- expect(isLargeValue('a'.repeat(60))).toBe(false)- })-- it('returns true for a string just over the 60-char threshold', () => {- expect(isLargeValue('a'.repeat(61))).toBe(true)- })-- it('returns true for a short string containing a newline', () => {- expect(isLargeValue('hello\nworld')).toBe(true)- })-- it('returns true for an object', () => {- expect(isLargeValue({ a: 1 })).toBe(true)- })-- it('returns true for an array', () => {- expect(isLargeValue([1, 2, 3])).toBe(true)- })-- it('returns false for a number', () => {- expect(isLargeValue(42)).toBe(false)- })-- it('returns false for a boolean', () => {- expect(isLargeValue(true)).toBe(false)+ it.each([+ // Strings are large past 60 characters or when multi-line+ ['a'.repeat(61), true],+ ['hello\nworld', true],+ [{ a: 1 }, true],+ [[1, 2, 3], true],+ [null, false],+ [undefined, false],+ ['', false],+ ['hello', false],+ ['a'.repeat(60), false],+ [42, false],+ [true, false],+ ])('classifies %j as large: %s', (value, expected) => {+ expect(isLargeValue(value)).toBe(expected)})})})diff --git a/apps/studio/components/ui/DataGridResults/__tests__/ResultCell.test.tsx b/apps/studio/components/ui/DataGridResults/__tests__/ResultCell.test.tsxindex 39031a51209..783fdf7b142 100644--- a/apps/studio/components/ui/DataGridResults/__tests__/ResultCell.test.tsx+++ b/apps/studio/components/ui/DataGridResults/__tests__/ResultCell.test.tsx@@ -7,32 +7,18 @@ import { customRender as render } from '@/tests/lib/custom-render'const noop = () => {}-test('renders the formatted cell value', () => {+test('renders a short value without the expand button', () => {render(<ResultCell column="name" value="alice" onContextMenu={noop} onExpand={noop} />)- expect(screen.getByText('alice')).toBeTruthy()+ expect(screen.getByText('alice')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'View full cell content' })).not.toBeInTheDocument()})test('renders NULL for null values', () => {render(<ResultCell column="name" value={null} onContextMenu={noop} onExpand={noop} />)- expect(screen.getByText('NULL')).toBeTruthy()+ expect(screen.getByText('NULL')).toBeInTheDocument()})-test('does not render the expand button for short string values', () => {- render(<ResultCell column="name" value="alice" onContextMenu={noop} onExpand={noop} />)- expect(screen.queryByRole('button', { name: 'View full cell content' })).toBeNull()-})--test('renders the expand button for object values', () => {- render(<ResultCell column="data" value={{ nested: true }} onContextMenu={noop} onExpand={noop} />)- expect(screen.getByRole('button', { name: 'View full cell content' })).toBeTruthy()-})--test('renders the expand button for long string values', () => {- render(<ResultCell column="bio" value={'a'.repeat(120)} onContextMenu={noop} onExpand={noop} />)- expect(screen.getByRole('button', { name: 'View full cell content' })).toBeTruthy()-})--test('clicking the expand button calls onExpand with column and value', async () => {+test('shows the expand button for large values and calls onExpand with column and value', async () => {const onExpand = vi.fn()const value = { nested: true }render(<ResultCell column="data" value={value} onContextMenu={noop} onExpand={onExpand} />)diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckboxAsync.test.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckboxAsync.test.tsxindex 5a1e2d56dda..de7587e9efa 100644--- a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckboxAsync.test.tsx+++ b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCheckboxAsync.test.tsx@@ -336,24 +336,6 @@ describe('pathname facet filter', () => {expect(screen.getByText('12')).toBeInTheDocument()})- it('shows a validation error while keeping selected paths removable', async () => {- addProjectMock()- addAPIMock({- method: 'post',- path: '/platform/projects/:ref/analytics/endpoints/logs.all',- response: () =>- HttpResponse.json<AnalyticsResponse>({ result: [{ value: '/invalid', count: 'wrong' }] }),- })-- customRender(<PathnameFilter search={pathnameSearch({ filter: ['pathname:eq:/selected'] })} />)- fireEvent.click(screen.getByText('Pathname'))- expect(await screen.findByText('Failed to retrieve pathnames')).toBeInTheDocument()- expect(screen.queryByText('/invalid')).not.toBeInTheDocument()-- fireEvent.click(screen.getByRole('checkbox', { name: /\/selected/ }))- expect(screen.queryByRole('checkbox', { name: /\/selected/ })).not.toBeInTheDocument()- })-it('shows a validation error when the analytics response omits results', async () => {addProjectMock()addAPIMock({@@ -368,7 +350,8 @@ describe('pathname facet filter', () => {expect(screen.queryByText('No results found')).not.toBeInTheDocument()})- it.each([null, '', true, false, -1, 1.5, '-1', '1.5'])(+ // One row per schema branch: wrong type, non-numeric/fractional string, negative/fractional number+ it.each([null, true, '', 'wrong', '1.5', -1, 1.5])('rejects malformed option count %s without hiding selected paths',async (count) => {addProjectMock()diff --git a/apps/studio/components/ui/GlobalShortcuts/ShortcutsReferenceSheet.test.tsx b/apps/studio/components/ui/GlobalShortcuts/ShortcutsReferenceSheet.test.tsxindex 88909bc2f93..87fed455439 100644--- a/apps/studio/components/ui/GlobalShortcuts/ShortcutsReferenceSheet.test.tsx+++ b/apps/studio/components/ui/GlobalShortcuts/ShortcutsReferenceSheet.test.tsx@@ -131,6 +131,12 @@ const renderShortcutsReferenceSheet = (ids: ShortcutId[] = ACTIVE_SHORTCUT_IDS)return { onOpenChange }}+// Typing isn't the behaviour under test, so paste the whole query in one go+const searchFor = async (user: ReturnType<typeof userEvent.setup>, query: string) => {+ await user.click(screen.getByLabelText('Search shortcuts'))+ await user.paste(query)+}+describe('ShortcutsReferenceSheet', () => {beforeEach(() => {sequenceIdCounter = 0@@ -156,7 +162,7 @@ describe('ShortcutsReferenceSheet', () => {renderShortcutsReferenceSheet()- await user.type(screen.getByLabelText('Search shortcuts'), 'navigation')+ await searchFor(user, 'navigation')expect(screen.getByText('Navigation')).toBeInTheDocument()expect(screen.getByText('Go to Project Overview')).toBeInTheDocument()@@ -169,7 +175,7 @@ describe('ShortcutsReferenceSheet', () => {renderShortcutsReferenceSheet()- await user.type(screen.getByLabelText('Search shortcuts'), 'Go to Project Overview')+ await searchFor(user, 'Go to Project Overview')expect(screen.getByText('Navigation')).toBeInTheDocument()expect(screen.getByText('Go to Project Overview')).toBeInTheDocument()@@ -290,7 +296,7 @@ describe('ShortcutsReferenceSheet', () => {renderShortcutsReferenceSheet()- await user.type(screen.getByLabelText('Search shortcuts'), 'Go to Tables')+ await searchFor(user, 'Go to Tables')expect(screen.getByText('No matching shortcuts found')).toBeInTheDocument()expect(screen.queryByText('Database Navigation')).not.toBeInTheDocument()@@ -317,7 +323,7 @@ describe('ShortcutsReferenceSheet', () => {renderShortcutsReferenceSheet()- await user.type(screen.getByLabelText('Search shortcuts'), 'navigation')+ await searchFor(user, 'navigation')expect(screen.getByRole('button', { name: 'Clear search' })).toBeInTheDocument()@@ -333,19 +339,9 @@ describe('ShortcutsReferenceSheet', () => {renderShortcutsReferenceSheet()- await user.type(screen.getByLabelText('Search shortcuts'), query)+ await searchFor(user, query)expect(screen.getByText('No matching shortcuts found')).toBeInTheDocument()expect(screen.queryByText('Navigation')).not.toBeInTheDocument()})-- it('shows an empty state when nothing matches', async () => {- const user = userEvent.setup()-- renderShortcutsReferenceSheet()-- await user.type(screen.getByLabelText('Search shortcuts'), 'totally missing')-- expect(screen.getByText('No matching shortcuts found')).toBeInTheDocument()- })})diff --git a/apps/studio/components/ui/HelpPanel/HelpPanel.utils.test.ts b/apps/studio/components/ui/HelpPanel/HelpPanel.utils.test.tsindex 95e640f0e38..42e51041f7f 100644--- a/apps/studio/components/ui/HelpPanel/HelpPanel.utils.test.ts+++ b/apps/studio/components/ui/HelpPanel/HelpPanel.utils.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'import { getSupportLinkQueryParams } from './HelpPanel.utils'describe('getSupportLinkQueryParams', () => {- it('returns { projectRef } when project has parent_project_ref', () => {+ it('prefers parent_project_ref over routerRef', () => {expect(getSupportLinkQueryParams({ parent_project_ref: 'main-project' },@@ -31,12 +31,6 @@ describe('getSupportLinkQueryParams', () => {})})- it('returns { orgSlug } when project and routerRef are undefined but org has slug', () => {- expect(getSupportLinkQueryParams(undefined, { slug: 'acme' }, undefined)).toEqual({- orgSlug: 'acme',- })- })-it('returns undefined when project, org and routerRef give no ref', () => {expect(getSupportLinkQueryParams(undefined, undefined, undefined)).toBeUndefined()})@@ -44,14 +38,4 @@ describe('getSupportLinkQueryParams', () => {it('returns undefined when org has no slug and no projectRef', () => {expect(getSupportLinkQueryParams(undefined, {}, undefined)).toBeUndefined()})-- it('returns undefined when org is undefined and no projectRef', () => {- expect(getSupportLinkQueryParams(undefined, undefined, undefined)).toBeUndefined()- })-- it('prefers parent_project_ref over routerRef when both are present', () => {- expect(- getSupportLinkQueryParams({ parent_project_ref: 'parent-ref' }, { slug: 'org' }, 'router-ref')- ).toEqual({ projectRef: 'parent-ref' })- })})diff --git a/apps/studio/components/ui/OrganizationProjectsMultiSelect.test.tsx b/apps/studio/components/ui/OrganizationProjectsMultiSelect.test.tsxindex 8d6a96a66ee..ed57f3f3b21 100644--- a/apps/studio/components/ui/OrganizationProjectsMultiSelect.test.tsx+++ b/apps/studio/components/ui/OrganizationProjectsMultiSelect.test.tsx@@ -1,4 +1,4 @@-import { screen, waitFor, within } from '@testing-library/react'+import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { platformComponents as components } from 'api-types'import { mockIntersectionObserver } from 'jsdom-testing-mocks'@@ -119,25 +119,19 @@ async function openDropdown() {}describe('OrganizationProjectsMultiSelect', () => {- test('lists every project as an unchecked option when nothing is selected', async () => {- setupProjectsMock([makeProject('ref-1', 'Alpha'), makeProject('ref-2', 'Beta')])- renderHarness()-- await openDropdown()-- const alpha = await screen.findByRole('option', { name: /Alpha/ })- const beta = screen.getByRole('option', { name: /Beta/ })- expect(within(alpha).getByRole('checkbox')).not.toBeChecked()- expect(within(beta).getByRole('checkbox')).not.toBeChecked()- })-test('selecting a project checks it and reports the new selection', async () => {setupProjectsMock([makeProject('ref-1', 'Alpha'), makeProject('ref-2', 'Beta')])const onChange = vi.fn()renderHarness({ onChange })await openDropdown()- await userEvent.click(await screen.findByRole('option', { name: /Alpha/ }))+ const alpha = await screen.findByRole('option', { name: /Alpha/ })+ expect(within(alpha).getByRole('checkbox')).not.toBeChecked()+ expect(+ within(screen.getByRole('option', { name: /Beta/ })).getByRole('checkbox')+ ).not.toBeChecked()++ await userEvent.click(alpha)expect(onChange).toHaveBeenCalledWith(['ref-1'], [{ ref: 'ref-1', name: 'Alpha' }])await waitFor(() => {@@ -196,23 +190,27 @@ describe('OrganizationProjectsMultiSelect', () => {makeProject('ref-1', 'Alpha'),makeProject('ref-2', 'Beta'),])- renderHarness()+ // Fake clock (still ticking for findBy/waitFor) so the 500ms search debounce can be skipped+ vi.useFakeTimers({ shouldAdvanceTime: true })+ try {+ renderHarness()- await openDropdown()- await screen.findByRole('option', { name: /Alpha/ })+ await openDropdown()+ await screen.findByRole('option', { name: /Alpha/ })- await userEvent.type(screen.getByPlaceholderText('Search project...'), 'Bet')+ fireEvent.change(screen.getByPlaceholderText('Search project...'), {+ target: { value: 'Bet' },+ })+ await act(() => vi.advanceTimersByTimeAsync(500))- await waitFor(- () => {- expect(requestedSearches).toContain('Bet')- },- { timeout: 2000 }- )- await waitFor(() => {- expect(screen.queryByRole('option', { name: /Alpha/ })).not.toBeInTheDocument()- expect(screen.getByRole('option', { name: /Beta/ })).toBeInTheDocument()- })+ await waitFor(() => expect(requestedSearches).toContain('Bet'))+ await waitFor(() => {+ expect(screen.queryByRole('option', { name: /Alpha/ })).not.toBeInTheDocument()+ expect(screen.getByRole('option', { name: /Beta/ })).toBeInTheDocument()+ })+ } finally {+ vi.useRealTimers()+ }})test('a disabled (permission-locked) project cannot be deselected', async () => {diff --git a/apps/studio/components/ui/PartnerIcon.test.ts b/apps/studio/components/ui/PartnerIcon.test.tsindex 649e1af91b4..8453560cf69 100644--- a/apps/studio/components/ui/PartnerIcon.test.ts+++ b/apps/studio/components/ui/PartnerIcon.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { describe, expect, it } from 'vitest'import PartnerIcon, { getDefaultPartnerTooltipText, getPartnerTooltipText } from './PartnerIcon'diff --git a/apps/studio/components/ui/ProductMenu/SubMenu.utils.test.ts b/apps/studio/components/ui/ProductMenu/SubMenu.utils.test.tsindex 4e214205173..8f66ab600ff 100644--- a/apps/studio/components/ui/ProductMenu/SubMenu.utils.test.ts+++ b/apps/studio/components/ui/ProductMenu/SubMenu.utils.test.ts@@ -42,11 +42,6 @@ describe('convertSectionsToProductMenu', () => {expect(result[0].items[0].url).toBe('#')})- it('handles empty sections array', () => {- const result = convertSectionsToProductMenu([])- expect(result).toEqual([])- })-it('handles section with empty links', () => {const sections = [{@@ -74,17 +69,4 @@ describe('convertSectionsToProductMenu', () => {expect(result[0].title).toBeUndefined()expect(result[0].items).toHaveLength(1)})-- it('converts multiple sections', () => {- const sections = [- { key: 'a', heading: 'A', links: [{ key: 'a1', label: 'A1', href: '/a1' }] },- { key: 'b', heading: 'B', links: [{ key: 'b1', label: 'B1', href: '/b1' }] },- ]-- const result = convertSectionsToProductMenu(sections)-- expect(result).toHaveLength(2)- expect(result[0].key).toBe('a')- expect(result[1].key).toBe('b')- })})diff --git a/apps/studio/components/ui/Shortcut.test.tsx b/apps/studio/components/ui/Shortcut.test.tsxindex e6ec7a5f8a2..59f2c922803 100644--- a/apps/studio/components/ui/Shortcut.test.tsx+++ b/apps/studio/components/ui/Shortcut.test.tsx@@ -21,15 +21,6 @@ vi.mock('./ShortcutTooltip', () => ({describe('Shortcut', () => {describe('rendering', () => {- it('renders the wrapped child', () => {- render(- <Shortcut id={SHORTCUT_IDS.COMMAND_MENU_OPEN} onTrigger={() => {}}>- <button tabIndex={0}>Open</button>- </Shortcut>- )- expect(screen.getByRole('button', { name: 'Open' })).toBeInTheDocument()- })-it('wraps the child in ShortcutTooltip', () => {render(<Shortcut id={SHORTCUT_IDS.COMMAND_MENU_OPEN} onTrigger={() => {}}>@@ -149,20 +140,6 @@ describe('Shortcut', () => {)expect(mockShortcutTooltip.mock.calls.at(-1)![0].label).toBe('Go home')})-- it('omits undefined positioning props rather than fabricating them', () => {- render(- <Shortcut id={SHORTCUT_IDS.NAV_HOME} onTrigger={() => {}}>- <button tabIndex={0}>Home</button>- </Shortcut>- )- const props = mockShortcutTooltip.mock.calls.at(-1)![0]- expect(props.side).toBeUndefined()- expect(props.align).toBeUndefined()- expect(props.sideOffset).toBeUndefined()- expect(props.delayDuration).toBeUndefined()- expect(props.label).toBeUndefined()- })})describe('child interactivity', () => {@@ -181,15 +158,5 @@ describe('Shortcut', () => {expect(onClick).toHaveBeenCalledTimes(1)expect(onTrigger).not.toHaveBeenCalled()})-- it('does not invoke onTrigger during render — only the hotkey should trigger it', () => {- const onTrigger = vi.fn()- render(- <Shortcut id={SHORTCUT_IDS.COMMAND_MENU_OPEN} onTrigger={onTrigger}>- <button tabIndex={0}>Open</button>- </Shortcut>- )- expect(onTrigger).not.toHaveBeenCalled()- })})})diff --git a/apps/studio/components/ui/SteppedFlow/SteppedFlow.test.tsx b/apps/studio/components/ui/SteppedFlow/SteppedFlow.test.tsxindex c0c65150a3d..e2bdcf6021d 100644--- a/apps/studio/components/ui/SteppedFlow/SteppedFlow.test.tsx+++ b/apps/studio/components/ui/SteppedFlow/SteppedFlow.test.tsx@@ -11,70 +11,48 @@ const steps = []describe('SteppedFlow', () => {- test('does not show Back on the first step', () => {- customRender(- <SteppedFlow steps={steps} currentStep="destination" onStepChange={vi.fn()}>- Step body- </SteppedFlow>- )-- expect(screen.queryByRole('button', { name: 'Back' })).not.toBeInTheDocument()- })-- test('shows Cancel on the first step when onCancel is provided', () => {+ test('offers Cancel instead of Back on the first step, and advances when onNext is omitted', () => {const onCancel = vi.fn()+ const onStepChange = vi.fn()customRender(<SteppedFlowsteps={steps}currentStep="destination"- onStepChange={vi.fn()}+ onStepChange={onStepChange}onCancel={onCancel}>Step body</SteppedFlow>)+ expect(screen.queryByRole('button', { name: 'Back' })).not.toBeInTheDocument()fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))expect(onCancel).toHaveBeenCalledOnce()- })-- test('does not show Cancel after the first step', () => {- customRender(- <SteppedFlow steps={steps} currentStep="connection" onStepChange={vi.fn()} onCancel={vi.fn()}>- Step body- </SteppedFlow>- )- expect(screen.queryByRole('button', { name: 'Cancel' })).not.toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Next' }))+ expect(onStepChange).toHaveBeenCalledWith('connection')})- test('shows Back after the first step', () => {+ test('offers Back instead of Cancel after the first step', () => {const onStepChange = vi.fn()customRender(- <SteppedFlow steps={steps} currentStep="connection" onStepChange={onStepChange}>+ <SteppedFlow+ steps={steps}+ currentStep="connection"+ onStepChange={onStepChange}+ onCancel={vi.fn()}+ >Step body</SteppedFlow>)+ expect(screen.queryByRole('button', { name: 'Cancel' })).not.toBeInTheDocument()fireEvent.click(screen.getByRole('button', { name: 'Back' }))expect(onStepChange).toHaveBeenCalledWith('destination')})- test('advances to the next step when onNext is omitted', () => {- const onStepChange = vi.fn()-- customRender(- <SteppedFlow steps={steps} currentStep="destination" onStepChange={onStepChange}>- Step body- </SteppedFlow>- )-- fireEvent.click(screen.getByRole('button', { name: 'Next' }))- expect(onStepChange).toHaveBeenCalledWith('connection')- })-test('shows the final action on the last step instead of Next', () => {const onFinal = vi.fn()@@ -95,23 +73,12 @@ describe('SteppedFlow', () => {expect(onFinal).toHaveBeenCalledOnce()})- test('renders a step header heading', () => {+ test('renders a step header with its heading, description and optional actions', () => {customRender(<SteppedFlow steps={steps} currentStep="destination" onStepChange={vi.fn()}>- <SteppedFlowHeader title="Choose a destination" description="Where should data go?" />- </SteppedFlow>- )-- expect(screen.getByRole('heading', { name: 'Choose a destination' })).toBeInTheDocument()- expect(screen.getByText('Where should data go?')).toBeInTheDocument()- })-- test('renders optional header actions', () => {- customRender(- <SteppedFlow steps={steps} currentStep="connection" onStepChange={vi.fn()}><SteppedFlowHeader- title="Authorize the destination"- description="Name this pipeline."+ title="Choose a destination"+ description="Where should data go?"actions={<button type="button" tabIndex={0}>Docs@@ -121,23 +88,26 @@ describe('SteppedFlow', () => {</SteppedFlow>)+ expect(screen.getByRole('heading', { name: 'Choose a destination' })).toBeInTheDocument()+ expect(screen.getByText('Where should data go?')).toBeInTheDocument()expect(screen.getByRole('button', { name: 'Docs' })).toBeInTheDocument()})- test('disables Back while navigation is locked', () => {+ test('disables Back and the final action while navigation is locked', () => {customRender(<SteppedFlowsteps={steps}currentStep="review"onStepChange={vi.fn()}navigationDisabled- finalAction={{ label: 'Create and start pipeline', loading: true }}+ finalAction={{ label: 'Create and start pipeline' }}>Step body</SteppedFlow>)expect(screen.getByRole('button', { name: 'Back' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'Create and start pipeline' })).toBeDisabled()})test('disables Next while navigation is locked', () => {@@ -154,20 +124,4 @@ describe('SteppedFlow', () => {expect(screen.getByRole('button', { name: 'Next' })).toBeDisabled()})-- test('disables the final action while navigation is locked', () => {- customRender(- <SteppedFlow- steps={steps}- currentStep="review"- onStepChange={vi.fn()}- navigationDisabled- finalAction={{ label: 'Create and start pipeline' }}- >- Step body- </SteppedFlow>- )-- expect(screen.getByRole('button', { name: 'Create and start pipeline' })).toBeDisabled()- })})diff --git a/apps/studio/data/analytics/infra-monitoring-queries.test.ts b/apps/studio/data/analytics/infra-monitoring-queries.test.tsindex 472378f3947..2258cc82ee2 100644--- a/apps/studio/data/analytics/infra-monitoring-queries.test.ts+++ b/apps/studio/data/analytics/infra-monitoring-queries.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { waitFor } from '@testing-library/react'import dayjs from 'dayjs'import { HttpResponse } from 'msw'@@ -246,14 +247,6 @@ describe('2m interval aggregation', () => {expect(dayjs(result.disk_io_budget?.data[1].period_start).minute() % 2).toBe(0)})- it('does not aggregate when interval is not 2m', () => {- const result = mapResponseToAnalyticsData(mockMultiResponse, ['max_cpu_usage', 'ram_usage'])-- expect(result.max_cpu_usage?.data).toHaveLength(2)- expect(result.max_cpu_usage?.data[0].max_cpu_usage).toBe(1.5)- expect(result.max_cpu_usage?.data[1].max_cpu_usage).toBe(0)- })-it('handles odd number of 1m data points', () => {const mock1MinData: InfraMonitoringMultiResponse = {data: [@@ -351,29 +344,6 @@ describe('aggregate1MinTo2Min', () => {expect(dayjs(result[1].period_start).minute() % 2).toBe(0) // Should be even minute})- it('handles odd number of data points correctly', () => {- const dataPoints = [- {- period_start: '2024-01-02T03:00:00Z',- max_cpu_usage: 10,- },- {- period_start: '2024-01-02T03:01:00Z',- max_cpu_usage: 20,- },- {- period_start: '2024-01-02T03:02:00Z',- max_cpu_usage: 15,- },- ]-- const result = aggregate1MinTo2Min(dataPoints)-- expect(result).toHaveLength(2)- expect(result[0].max_cpu_usage).toBe(15) // (10 + 20) / 2- expect(result[1].max_cpu_usage).toBe(15) // single point in second bucket- })-it('handles single data point', () => {const dataPoints = [{@@ -448,48 +418,6 @@ describe('aggregate1MinTo2Min', () => {expect(result[0].label).toBeUndefined()})- it('handles data points across different 2-minute buckets', () => {- const dataPoints = [- {- period_start: '2024-01-02T03:00:00Z',- value: 10,- },- {- period_start: '2024-01-02T03:01:00Z',- value: 20,- },- {- period_start: '2024-01-02T03:02:00Z',- value: 15,- },- {- period_start: '2024-01-02T03:03:00Z',- value: 25,- },- {- period_start: '2024-01-02T03:04:00Z',- value: 30,- },- {- period_start: '2024-01-02T03:05:00Z',- value: 35,- },- ]-- const result = aggregate1MinTo2Min(dataPoints)-- expect(result).toHaveLength(3)- // First bucket: 03:00 and 03:01- expect(result[0].value).toBe(15) // (10 + 20) / 2- expect(dayjs(result[0].period_start).minute() % 2).toBe(0)- // Second bucket: 03:02 and 03:03- expect(result[1].value).toBe(20) // (15 + 25) / 2- expect(dayjs(result[1].period_start).minute() % 2).toBe(0)- // Third bucket: 03:04 and 03:05- expect(result[2].value).toBe(32.5) // (30 + 35) / 2- expect(dayjs(result[2].period_start).minute() % 2).toBe(0)- })-it('sorts results by period_start', () => {const dataPoints = [{@@ -511,20 +439,6 @@ describe('aggregate1MinTo2Min', () => {expect(result).toHaveLength(2)expect(dayjs(result[0].period_start).isBefore(dayjs(result[1].period_start))).toBe(true)})-- it('always includes periodStartFormatted in result', () => {- const dataPoints = [- {- period_start: '2024-01-02T03:00:00Z',- max_cpu_usage: 10,- },- ]-- const result = aggregate1MinTo2Min(dataPoints)-- expect(result[0].periodStartFormatted).toBeDefined()- expect(typeof result[0].periodStartFormatted).toBe('string')- })})describe('useInfraMonitoringQueries partial failures', () => {diff --git a/apps/studio/data/analytics/org-daily-stats-query.test.ts b/apps/studio/data/analytics/org-daily-stats-query.test.tsindex da907816ee6..162e73b847a 100644--- a/apps/studio/data/analytics/org-daily-stats-query.test.ts+++ b/apps/studio/data/analytics/org-daily-stats-query.test.ts@@ -1,122 +1,51 @@-import { describe, expect, it, vi } from 'vitest'+import { HttpResponse } from 'msw'+import { describe, expect, it } from 'vitest'import { getOrgDailyStats } from './org-daily-stats-query'+import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'++const variables = { orgSlug: 'test-org', startDate: '2025-01-01', endDate: '2025-01-31' }++describe('getOrgDailyStats', () => {+ it.each([+ [{ orgSlug: undefined }, 'Org slug is required'],+ [{ startDate: undefined }, 'Start date is required'],+ // Product currently reuses the start-date message for a missing end date.+ [{ endDate: undefined }, 'Start date is required'],+ ])('rejects when a required variable is missing: %o', async (override, message) => {+ await expect(getOrgDailyStats({ ...variables, ...override })).rejects.toThrow(message)+ })-vi.mock('@/data/fetchers', () => ({- get: vi.fn(),- handleError: vi.fn((error) => {- throw error- }),-}))--describe('org-daily-stats-query', () => {- describe('getOrgDailyStats', () => {- it('throws error when orgSlug is not provided', async () => {- await expect(- getOrgDailyStats({- orgSlug: undefined,- startDate: '2025-01-01',- endDate: '2025-01-31',- })- ).rejects.toThrow('Org slug is required')- })-- it('throws error when startDate is not provided', async () => {- await expect(- getOrgDailyStats({- orgSlug: 'test-org',- startDate: undefined,- endDate: '2025-01-31',- })- ).rejects.toThrow('Start date is required')- })-- it('throws error when endDate is not provided', async () => {- await expect(- getOrgDailyStats({- orgSlug: 'test-org',- startDate: '2025-01-01',- endDate: undefined,- })- ).rejects.toThrow('Start date is required')- })-- it('calls API with correct parameters including project_ref', async () => {- const { get } = await import('@/data/fetchers')- const mockGet = get as unknown as ReturnType<typeof vi.fn>-- const mockResponse = { usages: [] }- mockGet.mockResolvedValueOnce({ data: mockResponse, error: null })-- const result = await getOrgDailyStats({- orgSlug: 'test-org',- startDate: '2025-01-01',- endDate: '2025-01-31',- projectRef: 'test-project-ref',- })-- expect(mockGet).toHaveBeenCalledWith(- '/platform/organizations/{slug}/usage/daily',- expect.objectContaining({- params: {- path: { slug: 'test-org' },- query: {- start: '2025-01-01',- end: '2025-01-31',- project_ref: 'test-project-ref',- },- },- })- )- expect(result).toEqual(mockResponse)+ it.each([+ ['includes project_ref when provided', 'test-project-ref'],+ ['omits project_ref when not provided', undefined],+ ])('%s', async (_, projectRef) => {+ let searchParams: URLSearchParams | undefined+ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/usage/daily',+ response: ({ request, params }) => {+ expect(params.slug).toBe('test-org')+ searchParams = new URL(request.url).searchParams+ return HttpResponse.json({ usages: [] })+ },})- it('calls API without project_ref when not provided', async () => {- const { get } = await import('@/data/fetchers')- const mockGet = get as unknown as ReturnType<typeof vi.fn>-- const mockResponse = { usages: [] }- mockGet.mockResolvedValueOnce({ data: mockResponse, error: null })+ const result = await getOrgDailyStats({ ...variables, projectRef })- await getOrgDailyStats({- orgSlug: 'test-org',- startDate: '2025-01-01',- endDate: '2025-01-31',- })+ expect(result).toEqual({ usages: [] })+ expect(searchParams?.get('start')).toBe('2025-01-01')+ expect(searchParams?.get('end')).toBe('2025-01-31')+ expect(searchParams?.get('project_ref')).toBe(projectRef ?? null)+ })- expect(mockGet).toHaveBeenCalledWith(- '/platform/organizations/{slug}/usage/daily',- expect.objectContaining({- params: {- path: { slug: 'test-org' },- query: {- start: '2025-01-01',- end: '2025-01-31',- project_ref: undefined,- },- },- })- )+ it('surfaces API errors', async () => {+ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/usage/daily',+ response: () => HttpResponse.json<APIErrorBody>({ message: 'API Error' }, { status: 500 }),})- it('handles API errors correctly', async () => {- const { get, handleError } = await import('@/data/fetchers')- const mockGet = get as unknown as ReturnType<typeof vi.fn>- const mockHandleError = handleError as unknown as ReturnType<typeof vi.fn>-- const mockError = { message: 'API Error' }- mockGet.mockResolvedValueOnce({ data: null, error: mockError })- mockHandleError.mockImplementation((error) => {- throw new Error(error.message)- })-- await expect(- getOrgDailyStats({- orgSlug: 'test-org',- startDate: '2025-01-01',- endDate: '2025-01-31',- })- ).rejects.toThrow('API Error')- })+ await expect(getOrgDailyStats(variables)).rejects.toThrow('API Error')})})diff --git a/apps/studio/data/api-keys/temp-api-keys-utils.test.ts b/apps/studio/data/api-keys/temp-api-keys-utils.test.tsindex 0782f4438fd..6873de88738 100644--- a/apps/studio/data/api-keys/temp-api-keys-utils.test.ts+++ b/apps/studio/data/api-keys/temp-api-keys-utils.test.ts@@ -6,294 +6,53 @@ import {type TemporaryApiKey,} from './temp-api-keys-utils'-describe('createTemporaryUploadKey', () => {- beforeEach(() => {- vi.useFakeTimers()- })-- afterEach(() => {- vi.useRealTimers()- })-- it('should create a temporary upload key with correct apiKey', () => {- const apiKey = 'test-api-key-123'- const expiryInSeconds = 3600-- const result = createTemporaryApiKey(apiKey, expiryInSeconds)-- expect(result.apiKey).toBe(apiKey)- })-- it('should create a temporary upload key with expiry time 1 hour in the future', () => {- const now = Date.now()- vi.setSystemTime(now)-- const apiKey = 'test-api-key-123'- const expiryInSeconds = 3600 // 1 hour-- const result = createTemporaryApiKey(apiKey, expiryInSeconds)-- expect(result.expiryTimeMs).toBe(now + 3600 * 1000)- })-- it('should handle short expiry durations', () => {- const now = Date.now()- vi.setSystemTime(now)+const NOW = 1_700_000_000_000- const apiKey = 'test-api-key-123'- const expiryInSeconds = 60 // 1 minute-- const result = createTemporaryApiKey(apiKey, expiryInSeconds)-- expect(result.expiryTimeMs).toBe(now + 60 * 1000)- })-- it('should create keys with different expiry times when called at different times', () => {- const apiKey = 'test-api-key-123'- const expiryInSeconds = 3600-- const now1 = 1000000- vi.setSystemTime(now1)- const result1 = createTemporaryApiKey(apiKey, expiryInSeconds)-- const now2 = 2000000- vi.setSystemTime(now2)- const result2 = createTemporaryApiKey(apiKey, expiryInSeconds)-- expect(result1.expiryTimeMs).toBe(now1 + expiryInSeconds * 1000)- expect(result2.expiryTimeMs).toBe(now2 + expiryInSeconds * 1000)- expect(result1.expiryTimeMs).not.toBe(result2.expiryTimeMs)- })+beforeEach(() => {+ vi.useFakeTimers()+ vi.setSystemTime(NOW)})-describe('isTemporaryUploadKeyValid', () => {- beforeEach(() => {- vi.useFakeTimers()- })-- afterEach(() => {- vi.useRealTimers()- })-- it('should return false for null key', () => {- const result = isTemporaryApiKeyValid(null)-- expect(result).toBe(false)- })-- it('should return false for undefined key', () => {- const result = isTemporaryApiKeyValid(undefined)-- expect(result).toBe(false)- })-- it('should return true for a key with more than 30 seconds remaining', () => {- const now = Date.now()- vi.setSystemTime(now)-- const key: TemporaryApiKey = {- apiKey: 'test-key',- expiryTimeMs: now + 120000, // 2 minutes from now- }-- const result = isTemporaryApiKeyValid(key)-- expect(result).toBe(true)- })-- it('should return false for a key with exactly 30 seconds remaining', () => {- const now = Date.now()- vi.setSystemTime(now)-- const key: TemporaryApiKey = {- apiKey: 'test-key',- expiryTimeMs: now + 30000, // Exactly 30 seconds- }-- const result = isTemporaryApiKeyValid(key)-- expect(result).toBe(false)- })-- it('should return false for a key with less than 30 seconds remaining', () => {- const now = Date.now()- vi.setSystemTime(now)-- const key: TemporaryApiKey = {- apiKey: 'test-key',- expiryTimeMs: now + 10000, // 10 seconds from now- }-- const result = isTemporaryApiKeyValid(key)-- expect(result).toBe(false)- })-- it('should return false for an expired key', () => {- const now = Date.now()- vi.setSystemTime(now)-- const key: TemporaryApiKey = {- apiKey: 'test-key',- expiryTimeMs: now - 1000, // 1 second ago- }-- const result = isTemporaryApiKeyValid(key)-- expect(result).toBe(false)- })-- it('should return false for a key that expired long ago', () => {- const now = Date.now()- vi.setSystemTime(now)-- const key: TemporaryApiKey = {- apiKey: 'test-key',- expiryTimeMs: now - 3600000, // 1 hour ago- }-- const result = isTemporaryApiKeyValid(key)-- expect(result).toBe(false)- })-- it('should return true for a key with exactly 31 seconds remaining', () => {- const now = Date.now()- vi.setSystemTime(now)-- const key: TemporaryApiKey = {- apiKey: 'test-key',- expiryTimeMs: now + 31000, // 31 seconds from now- }-- const result = isTemporaryApiKeyValid(key)-- expect(result).toBe(true)- })-- it('should handle time advancing correctly', () => {- const now = Date.now()- vi.setSystemTime(now)-- const key: TemporaryApiKey = {- apiKey: 'test-key',- expiryTimeMs: now + 120000, // 2 minutes from now- }-- // Initially valid- expect(isTemporaryApiKeyValid(key)).toBe(true)-- // Advance time by 89 seconds (should still be valid - 31 seconds remaining)- vi.advanceTimersByTime(89000)- expect(isTemporaryApiKeyValid(key)).toBe(true)-- // Advance time by 2 more seconds (should be invalid - 29 seconds remaining)- vi.advanceTimersByTime(2000)- expect(isTemporaryApiKeyValid(key)).toBe(false)- })-- it('should return true for a key missing apiKey property', () => {- const now = Date.now()- vi.setSystemTime(now)-- const key = {- expiryTimeMs: now + 120000,- } as TemporaryApiKey-- const result = isTemporaryApiKeyValid(key)-- // While the key has expiryTime, it's missing apiKey, but since we're checking- // the structure, we expect it to still pass the time check if the expiryTime exists- // Actually, the function only checks time, not the apiKey presence- // Let's verify the actual behavior- expect(result).toBe(true)- })-- it('should return false for a key missing expiryTime property', () => {- const key = {- apiKey: 'test-key',- } as TemporaryApiKey-- const result = isTemporaryApiKeyValid(key)-- // Without expiryTime, the calculation will be NaN and fail the > 60000 check- expect(result).toBe(false)- })+afterEach(() => {+ vi.useRealTimers()})-describe('integration: createTemporaryUploadKey and isTemporaryUploadKeyValid', () => {- beforeEach(() => {- vi.useFakeTimers()- })-- afterEach(() => {- vi.useRealTimers()+describe('createTemporaryApiKey', () => {+ it('keeps the api key and sets the expiry relative to the current time', () => {+ expect(createTemporaryApiKey('test-api-key-123', 3600)).toEqual({+ apiKey: 'test-api-key-123',+ expiryTimeMs: NOW + 3600 * 1000,+ })})+})- it('should create a key that is immediately valid', () => {- const now = Date.now()- vi.setSystemTime(now)-- const key = createTemporaryApiKey('test-api-key', 3600)-- expect(isTemporaryApiKeyValid(key)).toBe(true)- })-- it('should create a key that becomes invalid after expiry time minus 30 seconds', () => {- const now = Date.now()- vi.setSystemTime(now)-- const expiryInSeconds = 120 // 2 minutes- const key = createTemporaryApiKey('test-api-key', expiryInSeconds)-- // Initially valid- expect(isTemporaryApiKeyValid(key)).toBe(true)-- // Advance to 29 seconds before expiry (should still be valid - 31 seconds remaining)- vi.advanceTimersByTime((expiryInSeconds - 31) * 1000)- expect(isTemporaryApiKeyValid(key)).toBe(true)-- // Advance to 20 seconds before expiry (should be invalid - 29 seconds remaining)- vi.advanceTimersByTime(1000)+describe('isTemporaryApiKeyValid', () => {+ it.each([null, undefined])('returns false for %s', (key) => {expect(isTemporaryApiKeyValid(key)).toBe(false)})- it('should handle very short expiry durations', () => {- const now = Date.now()- vi.setSystemTime(now)-- // Create a key that expires in 10 seconds (less than the 30 second buffer)- const key = createTemporaryApiKey('test-api-key', 10)-- // Should be invalid immediately because it will expire in less than 30 seconds- expect(isTemporaryApiKeyValid(key)).toBe(false)+ // Keys need more than a 30s buffer so they don't expire mid-use.+ it.each([+ [120_000, true],+ [31_000, true],+ [30_000, false],+ [10_000, false],+ [-1_000, false],+ ])('with %ims remaining returns %s', (remainingMs, expected) => {+ const key: TemporaryApiKey = { apiKey: 'test-key', expiryTimeMs: NOW + remainingMs }+ expect(isTemporaryApiKeyValid(key)).toBe(expected)})- it('should handle expiry duration of exactly 30 seconds', () => {- const now = Date.now()- vi.setSystemTime(now)-- // Create a key that expires in exactly 30 seconds- const key = createTemporaryApiKey('test-api-key', 30)-- // Should be invalid because it has exactly 30 seconds remaining (not more than 30)+ it('returns false for a key missing expiryTimeMs', () => {+ const key = { apiKey: 'test-key' } as TemporaryApiKeyexpect(isTemporaryApiKeyValid(key)).toBe(false)})- it('should handle expiry duration of 31 seconds', () => {- const now = Date.now()- vi.setSystemTime(now)-- // Create a key that expires in 31 seconds+ it('becomes invalid once time passes the 30s buffer', () => {const key = createTemporaryApiKey('test-api-key', 31)-- // Should be valid because it has 31 seconds remaining (more than 30)expect(isTemporaryApiKeyValid(key)).toBe(true)- // Advance by 1 secondvi.advanceTimersByTime(1000)-- // Should now be invalid because it has exactly 30 seconds remainingexpect(isTemporaryApiKeyValid(key)).toBe(false)})})diff --git a/apps/studio/data/content/content-remap.test.ts b/apps/studio/data/content/content-remap.test.tsindex fabb0d08db9..e706d3e9f84 100644--- a/apps/studio/data/content/content-remap.test.ts+++ b/apps/studio/data/content/content-remap.test.ts@@ -297,17 +297,3 @@ describe('unmapSqlContentField (notebooks)', () => {expect(result.content.cells[0]).not.toHaveProperty('_id')})})--describe('remap/unmap round-trip', () => {- it('returns the original content shape after remap then unmap for sql snippets', () => {- const result = unmapSqlContentField(remapSqlContentField(SQL_SNIPPET))-- expect(result.content).toEqual(SQL_SNIPPET.content)- })-- it('returns the original content shape after remap then unmap for log_sql snippets', () => {- const result = unmapSqlContentField(remapSqlContentField(LOG_SQL_SNIPPET))-- expect(result.content).toEqual(LOG_SQL_SNIPPET.content)- })-})diff --git a/apps/studio/data/content/notebooks/notebook-cache.test.ts b/apps/studio/data/content/notebooks/notebook-cache.test.tsindex 1fe4f86de62..7722f7736fc 100644--- a/apps/studio/data/content/notebooks/notebook-cache.test.ts+++ b/apps/studio/data/content/notebooks/notebook-cache.test.ts@@ -38,37 +38,27 @@ afterEach(() => {})describe('evictNotebookFromCaches', () => {- it('removes a saved notebook from the store and drops its cache entry', async () => {- seedNotebook('saved')- const queryClient = new QueryClient()- seedQueryData(queryClient)-- const evicted = await evictNotebookFromCaches({- queryClient,- projectRef: PROJECT_REF,- id: NOTEBOOK_ID,- })+ // Unsaved ('new') notebooks are only evicted after their caller confirms discard.+ it.each(['saved', 'new'] as const)(+ 'removes a %s notebook from the store and drops its cache entry',+ async (status) => {+ seedNotebook(status)+ const queryClient = new QueryClient()+ seedQueryData(queryClient)- expect(evicted).toBe(true)- expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeUndefined()- expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toBeUndefined()- })+ const evicted = await evictNotebookFromCaches({+ queryClient,+ projectRef: PROJECT_REF,+ id: NOTEBOOK_ID,+ })- it('removes an unsaved notebook and its cache entry after its caller confirms discard', async () => {- seedNotebook('new')- const queryClient = new QueryClient()- seedQueryData(queryClient)-- const evicted = await evictNotebookFromCaches({- queryClient,- projectRef: PROJECT_REF,- id: NOTEBOOK_ID,- })-- expect(evicted).toBe(true)- expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeUndefined()- expect(queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))).toBeUndefined()- })+ expect(evicted).toBe(true)+ expect(notebooksState.notebooks[NOTEBOOK_ID]).toBeUndefined()+ expect(+ queryClient.getQueryData(contentKeys.resource(PROJECT_REF, NOTEBOOK_ID))+ ).toBeUndefined()+ }+ )it('drops a stale cache entry when the notebook is not present in the store', async () => {const queryClient = new QueryClient()diff --git a/apps/studio/data/content/notebooks/notebooks-infinite-query.test.ts b/apps/studio/data/content/notebooks/notebooks-infinite-query.test.tsindex 5291cca30fa..0e22c207864 100644--- a/apps/studio/data/content/notebooks/notebooks-infinite-query.test.ts+++ b/apps/studio/data/content/notebooks/notebooks-infinite-query.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { waitFor } from '@testing-library/react'import { HttpResponse } from 'msw'import { describe, expect, it } from 'vitest'diff --git a/apps/studio/data/edge-functions/edge-functions-last-hour-stats-query.test.ts b/apps/studio/data/edge-functions/edge-functions-last-hour-stats-query.test.tsindex c94fc2c62f9..1c905c86b83 100644--- a/apps/studio/data/edge-functions/edge-functions-last-hour-stats-query.test.ts+++ b/apps/studio/data/edge-functions/edge-functions-last-hour-stats-query.test.ts@@ -1,20 +1,45 @@+import { HttpResponse } from 'msw'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { z } from 'zod'import { getEdgeFunctionsLastHourStats } from './edge-functions-last-hour-stats-query'-import { post } from '@/data/fetchers'+import { addAPIMock } from '@/tests/lib/msw'-vi.mock('@/data/fetchers', () => ({- post: vi.fn(),- handleError: vi.fn(),-}))+const requestBodySchema = z.object({+ sql: z.string(),+ iso_timestamp_start: z.string(),+ iso_timestamp_end: z.string(),+})-type PostResponse = Awaited<ReturnType<typeof post>>+type CapturedRequest = {+ endpoint?: string+ key?: string | null+ body?: z.infer<typeof requestBodySchema>+}++function mockLogsEndpoint(result: unknown[] = []) {+ const captured: CapturedRequest = {}+ for (const endpoint of ['logs.all', 'logs.all.otel'] as const) {+ addAPIMock({+ method: 'post',+ path: `/platform/projects/:ref/analytics/endpoints/${endpoint}`,+ response: async ({ request, params }) => {+ expect(params.ref).toBe('project-ref')+ captured.endpoint = endpoint+ captured.key = new URL(request.url).searchParams.get('key')+ captured.body = requestBodySchema.parse(await request.json())+ return HttpResponse.json({ result })+ },+ })+ }+ return captured+}describe('getEdgeFunctionsLastHourStats', () => {beforeEach(() => {- vi.useFakeTimers()+ // Only fake Date so MSW's own timers keep running.+ vi.useFakeTimers({ toFake: ['Date'] })vi.setSystemTime(new Date('2024-01-15T12:00:00.000Z'))- vi.mocked(post).mockReset()})afterEach(() => {@@ -22,35 +47,25 @@ describe('getEdgeFunctionsLastHourStats', () => {})it('requests last-hour function stats from logs.all by default', async () => {- vi.mocked(post).mockResolvedValue({ data: { result: [] }, error: null } as PostResponse)+ const captured = mockLogsEndpoint()await getEdgeFunctionsLastHourStats({projectRef: 'project-ref',functionIds: ['fn_1', 'fn_2'],})- expect(post).toHaveBeenCalledWith('/platform/projects/{ref}/analytics/endpoints/logs.all', {- params: {- path: { ref: 'project-ref' },- query: { key: 'last-hour-stats' },- },- body: expect.objectContaining({- sql: expect.stringContaining(`and function_id in ('fn_1', 'fn_2')`),- iso_timestamp_start: '2024-01-15T11:00:00.000Z',- iso_timestamp_end: '2024-01-15T12:00:00.000Z',- }),- signal: undefined,+ expect(captured.endpoint).toBe('logs.all')+ expect(captured.key).toBe('last-hour-stats')+ expect(captured.body).toMatchObject({+ iso_timestamp_start: '2024-01-15T11:00:00.000Z',+ iso_timestamp_end: '2024-01-15T12:00:00.000Z',})-- const postCalls = vi.mocked(post).mock.calls as Array<- [string, { body?: { sql?: string } } | undefined]- >-- expect(postCalls[0]?.[1]?.body?.sql).toContain('from\n function_edge_logs')+ expect(captured.body?.sql).toContain(`and function_id in ('fn_1', 'fn_2')`)+ expect(captured.body?.sql).toContain('from\n function_edge_logs')})it('requests last-hour function stats from logs.all.otel when useOtel is set', async () => {- vi.mocked(post).mockResolvedValue({ data: { result: [] }, error: null } as PostResponse)+ const captured = mockLogsEndpoint()await getEdgeFunctionsLastHourStats({projectRef: 'project-ref',@@ -58,27 +73,14 @@ describe('getEdgeFunctionsLastHourStats', () => {useOtel: true,})- expect(post).toHaveBeenCalledWith(- '/platform/projects/{ref}/analytics/endpoints/logs.all.otel',- {- params: {- path: { ref: 'project-ref' },- query: { key: 'last-hour-stats' },- },- body: expect.objectContaining({- sql: expect.stringContaining(`and log_attributes['function_id'] in ('fn_1', 'fn_2')`),- iso_timestamp_start: '2024-01-15T11:00:00.000Z',- iso_timestamp_end: '2024-01-15T12:00:00.000Z',- }),- signal: undefined,- }- )-- const postCalls = vi.mocked(post).mock.calls as Array<- [string, { body?: { sql?: string } } | undefined]- >- const sql = postCalls[0]?.[1]?.body?.sql ?? ''-+ expect(captured.endpoint).toBe('logs.all.otel')+ expect(captured.key).toBe('last-hour-stats')+ expect(captured.body).toMatchObject({+ iso_timestamp_start: '2024-01-15T11:00:00.000Z',+ iso_timestamp_end: '2024-01-15T12:00:00.000Z',+ })+ const sql = captured.body?.sql ?? ''+ expect(sql).toContain(`and log_attributes['function_id'] in ('fn_1', 'fn_2')`)expect(sql).toContain('from logs')expect(sql).toContain("source = 'function_edge_logs'")expect(sql).toContain("case when toInt32OrZero(log_attributes['response.status_code']) >= 500")@@ -86,15 +88,10 @@ describe('getEdgeFunctionsLastHourStats', () => {})it('coerces counts to numbers and computes error rates per function', async () => {- vi.mocked(post).mockResolvedValue({- data: {- result: [- { function_id: 'fn_1', requests_count: '100', server_err_count: '5' },- { function_id: 'fn_2', requests_count: 8, server_err_count: 0 },- ],- },- error: null,- } as PostResponse)+ mockLogsEndpoint([+ { function_id: 'fn_1', requests_count: '100', server_err_count: '5' },+ { function_id: 'fn_2', requests_count: 8, server_err_count: 0 },+ ])const result = await getEdgeFunctionsLastHourStats({projectRef: 'project-ref',@@ -102,39 +99,18 @@ describe('getEdgeFunctionsLastHourStats', () => {})expect(result).toEqual({- fn_1: {- functionId: 'fn_1',- requestsCount: 100,- serverErrorCount: 5,- errorRate: 5,- },- fn_2: {- functionId: 'fn_2',- requestsCount: 8,- serverErrorCount: 0,- errorRate: 0,- },+ fn_1: { functionId: 'fn_1', requestsCount: 100, serverErrorCount: 5, errorRate: 5 },+ fn_2: { functionId: 'fn_2', requestsCount: 8, serverErrorCount: 0, errorRate: 0 },})})- it('handles empty results', async () => {- vi.mocked(post).mockResolvedValue({ data: { result: [] }, error: null } as PostResponse)-- const result = await getEdgeFunctionsLastHourStats({- projectRef: 'project-ref',- functionIds: ['fn_1'],- })-- expect(result).toEqual({})- })-it('skips the logs query when there are no function ids', async () => {+ // No handler registered: an outgoing request would fail the test.const result = await getEdgeFunctionsLastHourStats({projectRef: 'project-ref',functionIds: [],})expect(result).toEqual({})- expect(post).not.toHaveBeenCalled()})})diff --git a/apps/studio/data/empty-body-diagnostics.test.ts b/apps/studio/data/empty-body-diagnostics.test.tsindex 721e64d6c31..0ff50bf0ef4 100644--- a/apps/studio/data/empty-body-diagnostics.test.ts+++ b/apps/studio/data/empty-body-diagnostics.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'const platform = vi.hoisted(() => ({ isPlatform: true }))diff --git a/apps/studio/data/handleError.test.ts b/apps/studio/data/handleError.test.tsindex 12f937e59d5..b6108619fcc 100644--- a/apps/studio/data/handleError.test.ts+++ b/apps/studio/data/handleError.test.ts@@ -21,50 +21,26 @@ function throwAndCatch(error: unknown): ResponseError {}describe('handleError — error classification', () => {- describe('known patterns', () => {- it('classifies connection timeout via message field', () => {- const err = throwAndCatch({ message: 'CONNECTION TERMINATED DUE TO CONNECTION TIMEOUT' })- expect(err).toBeInstanceOf(ConnectionTimeoutError)- expect((err as ConnectionTimeoutError).errorType).toBe('connection-timeout')- })-- it('classifies connection timeout via msg field', () => {- const err = throwAndCatch({ msg: 'ERROR: CONNECTION TERMINATED DUE TO CONNECTION TIMEOUT' })- expect(err).toBeInstanceOf(ConnectionTimeoutError)- })-- it('classification is case-insensitive', () => {- const err = throwAndCatch({ message: 'connection terminated due to connection timeout' })- expect(err).toBeInstanceOf(ConnectionTimeoutError)- })-- it('classified error is still instanceof ResponseError', () => {- const err = throwAndCatch({ message: 'CONNECTION TERMINATED DUE TO CONNECTION TIMEOUT' })- expect(err).toBeInstanceOf(ResponseError)- })+ // Pattern matching itself (case, whitespace, near-misses) is covered in error-patterns.test.ts.+ it.each([+ ['message', { message: 'CONNECTION TERMINATED DUE TO CONNECTION TIMEOUT' }],+ ['msg', { msg: 'ERROR: CONNECTION TERMINATED DUE TO CONNECTION TIMEOUT' }],+ ])('classifies a known pattern from the %s field', (_, raw) => {+ const err = throwAndCatch(raw)+ expect(err).toBeInstanceOf(ConnectionTimeoutError)+ expect(err).toBeInstanceOf(ResponseError)+ expect((err as ConnectionTimeoutError).errorType).toBe('connection-timeout')})- describe('unclassified errors', () => {- it('throws UnknownAPIResponseError for unmatched messages', () => {- const err = throwAndCatch({ message: 'something went wrong' })- expect(err).toBeInstanceOf(UnknownAPIResponseError)- expect(err).toBeInstanceOf(ResponseError)- })-- it('throws UnknownAPIResponseError for empty message', () => {- const err = throwAndCatch({ message: '' })- expect(err).toBeInstanceOf(UnknownAPIResponseError)- })-- it('throws UnknownAPIResponseError for null', () => {- const err = throwAndCatch(null)- expect(err).toBeInstanceOf(UnknownAPIResponseError)- })-- it('throws UnknownAPIResponseError for non-object', () => {- const err = throwAndCatch('raw string error')- expect(err).toBeInstanceOf(UnknownAPIResponseError)- })+ it.each([+ ['an unmatched message', { message: 'something went wrong' }],+ ['an empty message', { message: '' }],+ ['null', null],+ ['a non-object', 'raw string error'],+ ])('throws UnknownAPIResponseError for %s', (_, raw) => {+ const err = throwAndCatch(raw)+ expect(err).toBeInstanceOf(UnknownAPIResponseError)+ expect(err).toBeInstanceOf(ResponseError)})describe('field preservation', () => {diff --git a/apps/studio/data/log-drains/audit-log-drains.test.tsx b/apps/studio/data/log-drains/audit-log-drains.test.tsxdeleted file mode 100644index b1e3d300272..00000000000--- a/apps/studio/data/log-drains/audit-log-drains.test.tsx+++ /dev/null@@ -1,74 +0,0 @@-import { waitFor } from '@testing-library/react'-import { http, HttpResponse } from 'msw'-import { describe, expect, it } from 'vitest'--import { useAuditLogDrainsQuery } from './audit-log-drains-query'-import { useCreateAuditLogDrainMutation } from './create-audit-log-drain-mutation'-import { useDeleteAuditLogDrainMutation } from './delete-audit-log-drain-mutation'-import { API_URL } from '@/lib/constants'-import { customRenderHook } from '@/tests/lib/custom-render'-import { mswServer } from '@/tests/lib/msw'--const SLUG = 'my-org'-const BASE = `${API_URL}/platform/organizations/:slug/analytics/audit-log-drains`--const DRAIN = {- id: 1,- token: 'tok-1',- name: 'Audit drain',- description: '',- type: 'webhook',- config: { url: 'https://example.com' },-}--describe('org audit log drain hooks', () => {- it('lists audit log drains for an organization', async () => {- mswServer.use(http.get(BASE, () => HttpResponse.json([DRAIN])))-- const { result } = customRenderHook(() => useAuditLogDrainsQuery({ slug: SLUG }))-- await waitFor(() => expect(result.current.isSuccess).toBe(true))- expect(result.current.data).toHaveLength(1)- expect(result.current.data?.[0].name).toBe('Audit drain')- })-- it('creates an audit log drain at the org-scoped path', async () => {- let receivedSlug: string | undefined- mswServer.use(- http.post(BASE, ({ params }) => {- receivedSlug = params.slug as string- return HttpResponse.json(DRAIN)- })- )-- const { result } = customRenderHook(() => useCreateAuditLogDrainMutation())-- result.current.mutate({- slug: SLUG,- name: 'Audit drain',- description: '',- type: 'webhook',- config: {} as any,- })-- await waitFor(() => expect(result.current.isSuccess).toBe(true))- expect(receivedSlug).toBe(SLUG)- })-- it('deletes an audit log drain by token', async () => {- let receivedToken: string | undefined- mswServer.use(- http.delete(`${BASE}/:token`, ({ params }) => {- receivedToken = params.token as string- return new HttpResponse(null, { status: 204 })- })- )-- const { result } = customRenderHook(() => useDeleteAuditLogDrainMutation())-- result.current.mutate({ slug: SLUG, token: 'tok-1' })-- await waitFor(() => expect(result.current.isSuccess).toBe(true))- expect(receivedToken).toBe('tok-1')- })-})diff --git a/apps/studio/data/log-drains/log-drains.test.tsx b/apps/studio/data/log-drains/log-drains.test.tsxindex 765d527a0f5..ac5e3fc824e 100644--- a/apps/studio/data/log-drains/log-drains.test.tsx+++ b/apps/studio/data/log-drains/log-drains.test.tsx@@ -2,20 +2,87 @@ import { waitFor } from '@testing-library/react'import { http, HttpResponse } from 'msw'import { describe, expect, it } from 'vitest'+import { useAuditLogDrainsQuery } from './audit-log-drains-query'+import { useCreateAuditLogDrainMutation } from './create-audit-log-drain-mutation'+import { useDeleteAuditLogDrainMutation } from './delete-audit-log-drain-mutation'import { useTestLogDrainMutation } from './test-log-drain-mutation'import { API_URL } from '@/lib/constants'import { customRenderHook } from '@/tests/lib/custom-render'import { mswServer } from '@/tests/lib/msw'+const SLUG = 'my-org'+const AUDIT_BASE = `${API_URL}/platform/organizations/:slug/analytics/audit-log-drains`+const REF = 'my-project'-const BASE = `${API_URL}/platform/projects/:ref/analytics/log-drains`+const PROJECT_BASE = `${API_URL}/platform/projects/:ref/analytics/log-drains`++const DRAIN = {+ id: 1,+ token: 'tok-1',+ name: 'Audit drain',+ description: '',+ type: 'webhook',+ config: { url: 'https://example.com' },+}++describe('org audit log drain hooks', () => {+ it('lists audit log drains for an organization', async () => {+ mswServer.use(http.get(AUDIT_BASE, () => HttpResponse.json([DRAIN])))++ const { result } = customRenderHook(() => useAuditLogDrainsQuery({ slug: SLUG }))++ await waitFor(() => expect(result.current.isSuccess).toBe(true))+ expect(result.current.data).toHaveLength(1)+ expect(result.current.data?.[0].name).toBe('Audit drain')+ })++ it('creates an audit log drain at the org-scoped path', async () => {+ let receivedSlug: string | undefined+ mswServer.use(+ http.post(AUDIT_BASE, ({ params }) => {+ receivedSlug = params.slug as string+ return HttpResponse.json(DRAIN)+ })+ )++ const { result } = customRenderHook(() => useCreateAuditLogDrainMutation())++ result.current.mutate({+ slug: SLUG,+ name: 'Audit drain',+ description: '',+ type: 'webhook',+ config: {} as any,+ })++ await waitFor(() => expect(result.current.isSuccess).toBe(true))+ expect(receivedSlug).toBe(SLUG)+ })++ it('deletes an audit log drain by token', async () => {+ let receivedToken: string | undefined+ mswServer.use(+ http.delete(`${AUDIT_BASE}/:token`, ({ params }) => {+ receivedToken = params.token as string+ return new HttpResponse(null, { status: 204 })+ })+ )++ const { result } = customRenderHook(() => useDeleteAuditLogDrainMutation())++ result.current.mutate({ slug: SLUG, token: 'tok-1' })++ await waitFor(() => expect(result.current.isSuccess).toBe(true))+ expect(receivedToken).toBe('tok-1')+ })+})describe('project log drain hooks', () => {it('tests a log drain connection by token at the project-scoped path', async () => {let receivedRef: string | undefinedlet receivedToken: string | undefinedmswServer.use(- http.post(`${BASE}/:token/test`, ({ params }) => {+ http.post(`${PROJECT_BASE}/:token/test`, ({ params }) => {receivedRef = params.ref as stringreceivedToken = params.token as stringreturn HttpResponse.json({})diff --git a/apps/studio/data/normalizeEmptyBodyResponse.test.ts b/apps/studio/data/normalizeEmptyBodyResponse.test.tsindex 69f710e7ff3..e1e2f5729d1 100644--- a/apps/studio/data/normalizeEmptyBodyResponse.test.ts+++ b/apps/studio/data/normalizeEmptyBodyResponse.test.ts@@ -12,12 +12,18 @@ describe('normalizeEmptyBodyResponse', () => {it('adds Content-Length: 0 to an empty 201 that omits it (HTTP/3 case)', async () => {// HTTP/3 responses can drop `Content-Length: 0` on empty bodies, which makes// openapi-fetch attempt to JSON-parse the empty body and throw.- const response = new Response(null, { status: 201 })+ const response = new Response(null, {+ status: 201,+ statusText: 'Created',+ headers: { 'X-Request-Id': 'req-123' },+ })expect(response.headers.has('Content-Length')).toBe(false)const normalized = await normalizeEmptyBodyResponse(response)expect(normalized.status).toBe(201)+ expect(normalized.statusText).toBe('Created')+ expect(normalized.headers.get('X-Request-Id')).toBe('req-123')expect(normalized.headers.get('Content-Length')).toBe('0')// The normalized empty body must not throw when parsed the way openapi-fetch parses it.expect(await normalized.text()).toBe('')@@ -55,27 +61,6 @@ describe('normalizeEmptyBodyResponse', () => {expect(normalized).toBe(response)})-- it('preserves status and statusText when normalizing', async () => {- const response = new Response(null, { status: 201, statusText: 'Created' })-- const normalized = await normalizeEmptyBodyResponse(response)-- expect(normalized.status).toBe(201)- expect(normalized.statusText).toBe('Created')- })-- it('preserves other headers when adding Content-Length', async () => {- const response = new Response(null, {- status: 201,- headers: { 'X-Request-Id': 'req-123' },- })-- const normalized = await normalizeEmptyBodyResponse(response)-- expect(normalized.headers.get('X-Request-Id')).toBe('req-123')- expect(normalized.headers.get('Content-Length')).toBe('0')- })})describe('openapi-fetch client — empty 201 without Content-Length (HTTP/3)', () => {diff --git a/apps/studio/data/organizations/organization-mappers.test.ts b/apps/studio/data/organizations/organization-mappers.test.tsindex 816d17ae220..359c870fdbe 100644--- a/apps/studio/data/organizations/organization-mappers.test.ts+++ b/apps/studio/data/organizations/organization-mappers.test.ts@@ -1,13 +1,8 @@-import { describe, expect, it, vi } from 'vitest'+import { describe, expect, it } from 'vitest'-vi.mock('@/data/fetchers', () => ({- get: vi.fn(),- handleError: vi.fn(),-}))--const { castOrganizationSlugResponseToOrganization } = await import('./organization-query')-const { castOrganizationResponseToOrganization } = await import('./organizations-query')-const { MANAGED_BY } = await import('@/lib/constants/infrastructure')+import { castOrganizationSlugResponseToOrganization } from './organization-query'+import { castOrganizationResponseToOrganization } from './organizations-query'+import { MANAGED_BY } from '@/lib/constants/infrastructure'const baseOrganizationResponse = {billing_email: '[email protected]',diff --git a/apps/studio/data/privileges/table-api-access-query.test.ts b/apps/studio/data/privileges/table-api-access-query.test.tsindex 4491bce02a0..d8266813469 100644--- a/apps/studio/data/privileges/table-api-access-query.test.ts+++ b/apps/studio/data/privileges/table-api-access-query.test.ts@@ -14,40 +14,17 @@ describe('isFullyGranted', () => {expect(isFullyGranted(fullPrivileges())).toBe(true)})- it('returns false when anon is missing any CRUD privilege', () => {- const privileges = fullPrivileges()- privileges.anon = ['SELECT', 'INSERT', 'UPDATE'] // no DELETE- expect(isFullyGranted(privileges)).toBe(false)- })-- it('returns false when authenticated has no privileges at all', () => {- const privileges = fullPrivileges()- privileges.authenticated = []- expect(isFullyGranted(privileges)).toBe(false)- })-- it('returns false when service_role is missing a privilege', () => {- const privileges = fullPrivileges()- privileges.service_role = ['SELECT', 'INSERT', 'DELETE'] // no UPDATE- expect(isFullyGranted(privileges)).toBe(false)- })-- it('returns false when every role has only SELECT (partial across the board)', () => {- const privileges: ApiPrivilegesByRole = {- anon: ['SELECT'],- authenticated: ['SELECT'],- service_role: ['SELECT'],- }- expect(isFullyGranted(privileges)).toBe(false)- })-- it('returns false when no role has any privileges', () => {- const privileges: ApiPrivilegesByRole = {- anon: [],- authenticated: [],- service_role: [],- }- expect(isFullyGranted(privileges)).toBe(false)+ it.each<[string, Partial<ApiPrivilegesByRole>]>([+ ['anon is missing DELETE', { anon: ['SELECT', 'INSERT', 'UPDATE'] }],+ ['authenticated has no privileges', { authenticated: [] }],+ ['service_role is missing UPDATE', { service_role: ['SELECT', 'INSERT', 'DELETE'] }],+ [+ 'every role has only SELECT',+ { anon: ['SELECT'], authenticated: ['SELECT'], service_role: ['SELECT'] },+ ],+ ['no role has any privileges', { anon: [], authenticated: [], service_role: [] }],+ ])('returns false when %s', (_, overrides) => {+ expect(isFullyGranted({ ...fullPrivileges(), ...overrides })).toBe(false)})it('tolerates duplicate privilege entries', () => {diff --git a/apps/studio/data/projects/project-create-mutation.test.ts b/apps/studio/data/projects/project-create-mutation.test.tsindex 28d893de7ee..9f48a7ed0bd 100644--- a/apps/studio/data/projects/project-create-mutation.test.ts+++ b/apps/studio/data/projects/project-create-mutation.test.ts@@ -1,68 +1,52 @@-import { describe, expect, it, vi } from 'vitest'--vi.mock('@/data/fetchers', () => ({- post: vi.fn(),- handleError: vi.fn((error) => {- throw error- }),-}))--describe('project-create-mutation', () => {- describe('createProject', () => {- it('sends GitHub connection fields when provided', async () => {- const { post } = await import('@/data/fetchers')- const { createProject } = await import('./project-create-mutation')-- const mockPost = post as unknown as ReturnType<typeof vi.fn>- mockPost.mockResolvedValueOnce({- data: { ref: 'project-ref', organization_slug: 'test-org' },- error: null,- })-- await createProject({- name: 'test-project',- organizationSlug: 'test-org',- dbPass: 'secret-password',- dbRegion: 'West US (North California)',- githubInstallationId: 1234,- githubRepositoryId: 5678,- })-- expect(mockPost).toHaveBeenCalledWith('/platform/projects', {- body: expect.objectContaining({- name: 'test-project',- organization_slug: 'test-org',- db_pass: 'secret-password',- db_region: 'West US (North California)',- github_installation_id: 1234,- github_repository_id: 5678,- }),- })+import { HttpResponse } from 'msw'+import { describe, expect, it } from 'vitest'++import { createProject } from './project-create-mutation'+import { addAPIMock } from '@/tests/lib/msw'++const baseVariables = {+ name: 'test-project',+ organizationSlug: 'test-org',+ dbPass: 'secret-password',+ dbRegion: 'West US (North California)',+}++async function createProjectAndCaptureBody(variables: Parameters<typeof createProject>[0]) {+ let body: unknown+ addAPIMock({+ method: 'post',+ path: '/platform/projects',+ response: async ({ request }) => {+ body = await request.json()+ return HttpResponse.json(null)+ },+ })+ await createProject(variables)+ return body+}++describe('createProject', () => {+ it('sends GitHub connection fields when provided', async () => {+ const body = await createProjectAndCaptureBody({+ ...baseVariables,+ githubInstallationId: 1234,+ githubRepositoryId: 5678,})- it('does not populate GitHub connection fields when omitted', async () => {- const { post } = await import('@/data/fetchers')- const { createProject } = await import('./project-create-mutation')-- const mockPost = post as unknown as ReturnType<typeof vi.fn>- mockPost.mockResolvedValueOnce({- data: { ref: 'project-ref', organization_slug: 'test-org' },- error: null,- })+ expect(body).toMatchObject({+ name: 'test-project',+ organization_slug: 'test-org',+ db_pass: 'secret-password',+ db_region: 'West US (North California)',+ github_installation_id: 1234,+ github_repository_id: 5678,+ })+ })- await createProject({- name: 'test-project',- organizationSlug: 'test-org',- dbPass: 'secret-password',- dbRegion: 'West US (North California)',- })+ it('does not send GitHub connection fields when omitted', async () => {+ const body = await createProjectAndCaptureBody(baseVariables)- expect(mockPost).toHaveBeenCalledWith('/platform/projects', {- body: expect.objectContaining({- github_installation_id: undefined,- github_repository_id: undefined,- }),- })- })+ expect(body).not.toHaveProperty('github_installation_id')+ expect(body).not.toHaveProperty('github_repository_id')})})diff --git a/apps/studio/data/read-replicas/replicas-query.test.ts b/apps/studio/data/read-replicas/replicas-query.test.tsindex 3b9b19bf0b9..0bbf3f73073 100644--- a/apps/studio/data/read-replicas/replicas-query.test.ts+++ b/apps/studio/data/read-replicas/replicas-query.test.ts@@ -10,35 +10,19 @@ import {import { addAPIMock } from '@/tests/lib/msw'describe('getMaxReplicas', () => {- it('returns 0 for ineligible compute sizes (pico, nano, micro)', () => {- expect(getMaxReplicas('ci_pico')).toBe(0)- expect(getMaxReplicas('ci_nano')).toBe(0)- expect(getMaxReplicas('ci_micro')).toBe(0)- })-- it('returns 4 for ci_small', () => {- expect(getMaxReplicas('ci_small')).toBe(4)- })-- it('returns 4 for ci_medium', () => {- expect(getMaxReplicas('ci_medium')).toBe(4)- })-- it('returns 4 for ci_large', () => {- expect(getMaxReplicas('ci_large')).toBe(4)- })-- it('returns READ_REPLICAS_MAX_COUNT for ci_xlarge and above', () => {- expect(getMaxReplicas('ci_xlarge')).toBe(READ_REPLICAS_MAX_COUNT)- expect(getMaxReplicas('ci_2xlarge')).toBe(READ_REPLICAS_MAX_COUNT)- })-- it('returns READ_REPLICAS_MAX_COUNT for any unknown compute tier', () => {- expect(getMaxReplicas('unknown_tier')).toBe(READ_REPLICAS_MAX_COUNT)- })-- it('returns READ_REPLICAS_MAX_COUNT when no compute addon is provided', () => {- expect(getMaxReplicas(undefined)).toBe(READ_REPLICAS_MAX_COUNT)+ it.each([+ ['ci_pico', 0],+ ['ci_nano', 0],+ ['ci_micro', 0],+ ['ci_small', 4],+ ['ci_medium', 4],+ ['ci_large', 4],+ ['ci_xlarge', READ_REPLICAS_MAX_COUNT],+ ['ci_2xlarge', READ_REPLICAS_MAX_COUNT],+ ['unknown_tier', READ_REPLICAS_MAX_COUNT],+ [undefined, READ_REPLICAS_MAX_COUNT],+ ])('returns the replica cap for compute %s', (compute, expected) => {+ expect(getMaxReplicas(compute)).toBe(expected)})it('all eligible READ_REPLICA_COMPUTE_CAPS are greater than 0 and at most READ_REPLICAS_MAX_COUNT', () => {diff --git a/apps/studio/data/replication/create-destination-pipeline-mutation.test.ts b/apps/studio/data/replication/create-destination-pipeline-mutation.test.tsindex a37f8b8b8b9..b8ef0bd66f1 100644--- a/apps/studio/data/replication/create-destination-pipeline-mutation.test.ts+++ b/apps/studio/data/replication/create-destination-pipeline-mutation.test.ts@@ -154,17 +154,11 @@ describe('buildBigQueryApiConfig', () => {})})- it('sends table_options: null on update when every configured table is removed or blank', () => {- expect(- buildBigQueryUpdateApiConfig({- ...baseConfig,- tableOptions: [{ tableId: 16_408, clusterBy: [] }],- })- ).toMatchObject({ big_query: { table_options: null } })- })-- it('sends table_options: null on update when every configured table is removed', () => {- expect(buildBigQueryUpdateApiConfig({ ...baseConfig, tableOptions: [] })).toMatchObject({+ it.each([+ ['blank', [{ tableId: 16_408, clusterBy: [] }]],+ ['removed', []],+ ])('sends table_options: null on update when every configured table is %s', (_, tableOptions) => {+ expect(buildBigQueryUpdateApiConfig({ ...baseConfig, tableOptions })).toMatchObject({big_query: { table_options: null },})})diff --git a/apps/studio/data/reports/database-charts.test.ts b/apps/studio/data/reports/database-charts.test.tsindex 7360fb0fe6d..a74ed3c2b06 100644--- a/apps/studio/data/reports/database-charts.test.ts+++ b/apps/studio/data/reports/database-charts.test.ts@@ -104,22 +104,15 @@ describe('getReportAttributesV2 shared pooler chart', () => {})})+// Visibility permutations are covered by shouldShowDiskIOBurstBalanceChart below.describe('getReportAttributesV2 disk-io-burst-balance chart', () => {it('shows the chart for burstable non high availability projects', () => {expect(getBurstBalanceChart(buildProject())?.hide).toBe(false)})- it('hides the chart for high availability projects', () => {- expect(getBurstBalanceChart(buildProject({ high_availability: true }))?.hide).toBe(true)- })-it('hides the chart when the feature flag is off', () => {expect(getBurstBalanceChart(buildProject(), false)?.hide).toBe(true)})-- it('hides the chart for non burstable compute sizes', () => {- expect(getBurstBalanceChart(buildProject({ infra_compute_size: '16xlarge' }))?.hide).toBe(true)- })})describe('shouldShowDiskIOBurstBalanceChart', () => {diff --git a/apps/studio/data/reports/v2/auth-report.test.tsx b/apps/studio/data/reports/v2/auth-report.test.tsxdeleted file mode 100644index 76b265abf8a..00000000000--- a/apps/studio/data/reports/v2/auth-report.test.tsx+++ /dev/null@@ -1,61 +0,0 @@-import { describe, expect, it } from 'vitest'--import { defaultAuthReportFormatter } from './auth.config'--describe('defaultAuthReportFormatter', () => {- const timestamp = new Date('2021-01-01').getTime()-- it('should format the data correctly', () => {- const data = { result: [{ timestamp: String(timestamp), count: 1 }] }-- const attributes = [- { attribute: 'ActiveUsers', provider: 'logs', label: 'Auth Activity', enabled: true },- ]-- const result = defaultAuthReportFormatter(data, attributes)-- expect(result).toEqual({- data: [{ timestamp: String(timestamp), ActiveUsers: 1 }],- chartAttributes: attributes,- })- })-- it('should format the data correctly with multiple attributes', () => {- const data = {- result: [- { timestamp: String(timestamp), active_users: 1 },- { timestamp: String(timestamp + 1), sign_in_attempts: 2 },- ],- }-- const attributes = [- { attribute: 'active_users', label: 'Auth Activity' },- { attribute: 'sign_in_attempts', label: 'Sign In Attempts' },- ]-- const result = defaultAuthReportFormatter(data, attributes)-- expect(result).toEqual({- data: [- { timestamp: String(timestamp), active_users: 1, sign_in_attempts: 0 },- { timestamp: String(timestamp + 1), active_users: 0, sign_in_attempts: 2 },- ],- chartAttributes: attributes,- })- })-- it('should handle empty data', () => {- const data = { result: [] }-- const attributes = [- { attribute: 'ActiveUsers', provider: 'logs', label: 'Auth Activity', enabled: true },- ]-- const result = defaultAuthReportFormatter(data, attributes)-- expect(result).toEqual({- data: [],- chartAttributes: attributes,- })- })-})diff --git a/apps/studio/data/reports/v2/auth.config.otel.test.ts b/apps/studio/data/reports/v2/auth.config.otel.test.tsindex d63cb9b9bef..7ee01cf6414 100644--- a/apps/studio/data/reports/v2/auth.config.otel.test.ts+++ b/apps/studio/data/reports/v2/auth.config.otel.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'-import { AUTH_REPORT_SQL_OTEL } from './auth.config'+import { AUTH_REPORT_SQL_OTEL, defaultAuthReportFormatter } from './auth.config'const sql = (fragment: { toString(): string }) => String(fragment)@@ -190,3 +190,61 @@ describe('AUTH_REPORT_SQL_OTEL', () => {expect(out).not.toContain("JSONExtractString(event_message, 'provider')")})})++describe('defaultAuthReportFormatter', () => {+ const timestamp = new Date('2021-01-01').getTime()++ it('should format the data correctly', () => {+ const data = { result: [{ timestamp: String(timestamp), count: 1 }] }++ const attributes = [+ { attribute: 'ActiveUsers', provider: 'logs', label: 'Auth Activity', enabled: true },+ ]++ const result = defaultAuthReportFormatter(data, attributes)++ expect(result).toEqual({+ data: [{ timestamp: String(timestamp), ActiveUsers: 1 }],+ chartAttributes: attributes,+ })+ })++ it('should format the data correctly with multiple attributes', () => {+ const data = {+ result: [+ { timestamp: String(timestamp), active_users: 1 },+ { timestamp: String(timestamp + 1), sign_in_attempts: 2 },+ ],+ }++ const attributes = [+ { attribute: 'active_users', label: 'Auth Activity' },+ { attribute: 'sign_in_attempts', label: 'Sign In Attempts' },+ ]++ const result = defaultAuthReportFormatter(data, attributes)++ expect(result).toEqual({+ data: [+ { timestamp: String(timestamp), active_users: 1, sign_in_attempts: 0 },+ { timestamp: String(timestamp + 1), active_users: 0, sign_in_attempts: 2 },+ ],+ chartAttributes: attributes,+ })+ })++ it('should handle empty data', () => {+ const data = { result: [] }++ const attributes = [+ { attribute: 'ActiveUsers', provider: 'logs', label: 'Auth Activity', enabled: true },+ ]++ const result = defaultAuthReportFormatter(data, attributes)++ expect(result).toEqual({+ data: [],+ chartAttributes: attributes,+ })+ })+})diff --git a/apps/studio/data/reports/v2/edge-functions.config.otel.test.ts b/apps/studio/data/reports/v2/edge-functions.config.otel.test.tsdeleted file mode 100644index 7d53b098f09..00000000000--- a/apps/studio/data/reports/v2/edge-functions.config.otel.test.ts+++ /dev/null@@ -1,75 +0,0 @@-import { describe, expect, it } from 'vitest'--import { METRIC_SQL_OTEL } from './edge-functions.config'--const sql = (fragment: { toString(): string }) => String(fragment)--describe('METRIC_SQL_OTEL', () => {- it('queries the single OTEL logs table by source, never a per-service table', () => {- const out = sql(METRIC_SQL_OTEL.TotalInvocations('1h'))-- expect(out).toContain('from logs')- expect(out).toContain("source = 'function_edge_logs'")- expect(out).not.toContain('from function_edge_logs')- expect(out).not.toContain('cross join unnest')- })-- it('emits 16-digit unix-microsecond timestamps bucketed by granularity', () => {- expect(sql(METRIC_SQL_OTEL.TotalInvocations('1h'))).toContain(- 'toUnixTimestamp(toStartOfHour(timestamp)) * 1000000 as timestamp'- )- expect(sql(METRIC_SQL_OTEL.TotalInvocations('1d'))).toContain(- 'toUnixTimestamp(toStartOfDay(timestamp)) * 1000000 as timestamp'- )- expect(sql(METRIC_SQL_OTEL.TotalInvocations('5m'))).toContain(- 'toUnixTimestamp(toStartOfMinute(timestamp)) * 1000000 as timestamp'- )- })-- it('reads function_id from log_attributes for total invocations', () => {- const out = sql(METRIC_SQL_OTEL.TotalInvocations('1h'))- expect(out).toContain("log_attributes['function_id'] as function_id")- expect(out).toContain('count() as count')- })-- it('reads response status code from log_attributes, coerced to a number', () => {- const out = sql(METRIC_SQL_OTEL.ExecutionStatusCodes('1h'))- expect(out).toContain("toInt32OrZero(log_attributes['response.status_code']) as status_code")- })-- it('reads region from the response headers attribute and drops empty values', () => {- const out = sql(METRIC_SQL_OTEL.InvocationsByRegion('1h'))- expect(out).toContain("log_attributes['response.headers.x_sb_edge_region'] as region")- expect(out).toContain("log_attributes['response.headers.x_sb_edge_region'] != ''")- })-- it('averages execution_time_ms from log_attributes, coerced to a float', () => {- const out = sql(METRIC_SQL_OTEL.ExecutionTime('1h'))- expect(out).toContain(- "avg(toFloat64OrZero(log_attributes['execution_time_ms'])) as avg_execution_time"- )- })-- it('filters by function_id list when functions filter is set', () => {- const out = sql(METRIC_SQL_OTEL.TotalInvocations('1h', { functions: ['fn-1', 'fn-2'] } as any))- expect(out).toContain("log_attributes['function_id'] IN ('fn-1','fn-2')")- })-- it('applies the numeric status_code filter using toInt32OrZero', () => {- const out = sql(- METRIC_SQL_OTEL.ExecutionStatusCodes('1h', {- status_code: { operator: '>=', value: 500 },- } as any)- )- expect(out).toContain("AND toInt32OrZero(log_attributes['response.status_code']) >= 500")- })-- it('applies the numeric execution_time filter using toFloat64OrZero', () => {- const out = sql(- METRIC_SQL_OTEL.ExecutionTime('1h', {- execution_time: { operator: '>=', value: 100 },- } as any)- )- expect(out).toContain("AND toFloat64OrZero(log_attributes['execution_time_ms']) >= 100")- })-})diff --git a/apps/studio/data/reports/v2/edge-functions.test.tsx b/apps/studio/data/reports/v2/edge-functions.test.tsxindex e5d274c8d2e..4de8a6417a7 100644--- a/apps/studio/data/reports/v2/edge-functions.test.tsx+++ b/apps/studio/data/reports/v2/edge-functions.test.tsx@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest'import {aggregateInvocationsByTimestamp,filterToWhereClause,+ METRIC_SQL_OTEL,transformInvocationData,} from './edge-functions.config'import {@@ -429,3 +430,75 @@ describe('filterToWhereClause', () => {)})})++const sql = (fragment: { toString(): string }) => String(fragment)++describe('METRIC_SQL_OTEL', () => {+ it('queries the single OTEL logs table by source, never a per-service table', () => {+ const out = sql(METRIC_SQL_OTEL.TotalInvocations('1h'))++ expect(out).toContain('from logs')+ expect(out).toContain("source = 'function_edge_logs'")+ expect(out).not.toContain('from function_edge_logs')+ expect(out).not.toContain('cross join unnest')+ })++ it('emits 16-digit unix-microsecond timestamps bucketed by granularity', () => {+ expect(sql(METRIC_SQL_OTEL.TotalInvocations('1h'))).toContain(+ 'toUnixTimestamp(toStartOfHour(timestamp)) * 1000000 as timestamp'+ )+ expect(sql(METRIC_SQL_OTEL.TotalInvocations('1d'))).toContain(+ 'toUnixTimestamp(toStartOfDay(timestamp)) * 1000000 as timestamp'+ )+ expect(sql(METRIC_SQL_OTEL.TotalInvocations('5m'))).toContain(+ 'toUnixTimestamp(toStartOfMinute(timestamp)) * 1000000 as timestamp'+ )+ })++ it('reads function_id from log_attributes for total invocations', () => {+ const out = sql(METRIC_SQL_OTEL.TotalInvocations('1h'))+ expect(out).toContain("log_attributes['function_id'] as function_id")+ expect(out).toContain('count() as count')+ })++ it('reads response status code from log_attributes, coerced to a number', () => {+ const out = sql(METRIC_SQL_OTEL.ExecutionStatusCodes('1h'))+ expect(out).toContain("toInt32OrZero(log_attributes['response.status_code']) as status_code")+ })++ it('reads region from the response headers attribute and drops empty values', () => {+ const out = sql(METRIC_SQL_OTEL.InvocationsByRegion('1h'))+ expect(out).toContain("log_attributes['response.headers.x_sb_edge_region'] as region")+ expect(out).toContain("log_attributes['response.headers.x_sb_edge_region'] != ''")+ })++ it('averages execution_time_ms from log_attributes, coerced to a float', () => {+ const out = sql(METRIC_SQL_OTEL.ExecutionTime('1h'))+ expect(out).toContain(+ "avg(toFloat64OrZero(log_attributes['execution_time_ms'])) as avg_execution_time"+ )+ })++ it('filters by function_id list when functions filter is set', () => {+ const out = sql(METRIC_SQL_OTEL.TotalInvocations('1h', { functions: ['fn-1', 'fn-2'] } as any))+ expect(out).toContain("log_attributes['function_id'] IN ('fn-1','fn-2')")+ })++ it('applies the numeric status_code filter using toInt32OrZero', () => {+ const out = sql(+ METRIC_SQL_OTEL.ExecutionStatusCodes('1h', {+ status_code: { operator: '>=', value: 500 },+ } as any)+ )+ expect(out).toContain("AND toInt32OrZero(log_attributes['response.status_code']) >= 500")+ })++ it('applies the numeric execution_time filter using toFloat64OrZero', () => {+ const out = sql(+ METRIC_SQL_OTEL.ExecutionTime('1h', {+ execution_time: { operator: '>=', value: 100 },+ } as any)+ )+ expect(out).toContain("AND toFloat64OrZero(log_attributes['execution_time_ms']) >= 100")+ })+})diff --git a/apps/studio/data/sql/__tests__/utils.test.ts b/apps/studio/data/sql/__tests__/utils.test.tsindex 1c8df476865..4b507868b95 100644--- a/apps/studio/data/sql/__tests__/utils.test.ts+++ b/apps/studio/data/sql/__tests__/utils.test.ts@@ -43,22 +43,14 @@ describe('getSqlErrorLines', () => {])})- it('returns empty array for a single-line message so callers render the fallback', () => {- const lines = getSqlErrorLines({ message: 'permission denied for table users' })- expect(lines).toEqual([])- })-- it('returns empty array when both fields are missing', () => {- expect(getSqlErrorLines({})).toEqual([])- })-- it('returns empty array when message is an empty string', () => {- expect(getSqlErrorLines({ message: '' })).toEqual([])- })-- it('returns empty array when message only contains whitespace newlines', () => {- // Only empty segments after filtering — treated as single-line- expect(getSqlErrorLines({ message: '\n\n' })).toEqual([])+ // A single-line (or empty) message returns no lines so callers render their fallback.+ it.each([+ ['a single-line message', { message: 'permission denied for table users' }],+ ['both fields missing', {}],+ ['an empty message', { message: '' }],+ ['a message of only newlines', { message: '\n\n' }],+ ])('returns an empty array for %s', (_, error) => {+ expect(getSqlErrorLines(error)).toEqual([])})it('prefers formattedError even when message is also multi-line', () => {@@ -100,37 +92,22 @@ describe('trimTrailingSemicolons', () => {})describe('applyAutoLimit', () => {- test('Should return false if limit passed is <= 0', () => {- const sql = safeSql`select * from countries;`- const limit = -1- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return true if limit passed is > 0', () => {- const sql = safeSql`select * from countries;`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(true)- })- test('Should return false if query already has a limit', () => {- const sql = safeSql`select * from countries limit 10;`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)+ test('does not append when the limit passed is <= 0', () => {+ expect(applyAutoLimit(safeSql`select * from countries;`, -1).appendAutoLimit).toBe(false)})+test.each([- 'select * from countries limit all;',- 'select * from countries limit all',- 'SELECT * FROM countries LIMIT ALL ;',- 'select * from countries limit null;',- 'select * from countries limit all offset 5;',- 'select * from countries offset 5 limit null',- ])('Should return false if query already has LIMIT ALL / LIMIT NULL: %s', (query) => {- const { sql, appendAutoLimit } = applyAutoLimit(query as SafeSqlFragment, 100)- expect(appendAutoLimit).toBe(false)- expect(sql).toBe(query)+ ['without a semicolon', 'select * from countries'],+ ['with a semicolon', 'select * from countries;'],+ ['with multiple semicolons', 'select * from countries;;;;;;;'],+ ])('appends the limit to a query %s', (_, query) => {+ expect(applyAutoLimit(query as SafeSqlFragment, 100)).toEqual({+ sql: 'select * from countries limit 100;',+ appendAutoLimit: true,+ })})- test('Should append the limit to a CTE query', () => {++ test('appends the limit to a CTE query', () => {const sql = safeSql`WITH numbers AS (SELECT generate_series(1, 2000) AS n) SELECT n FROM numbers;`const result = applyAutoLimit(sql, 100)expect(result.appendAutoLimit).toBe(true)@@ -138,150 +115,56 @@ describe('applyAutoLimit', () => {'WITH numbers AS (SELECT generate_series(1, 2000) AS n) SELECT n FROM numbers limit 100;')})- test('Should append the limit to a recursive CTE query when the inner query has its own limit', () => {- const sql = safeSql`with recursive t as (select 1 as n limit 5) select * from t`- expect(applyAutoLimit(sql, 100).appendAutoLimit).toBe(true)- })- test('Should return false if a CTE query already has a limit', () => {- const sql = safeSql`with t as (select 1) select * from t limit 10`- expect(applyAutoLimit(sql, 100).appendAutoLimit).toBe(false)- })- test('Should append the limit to a read-only CTE whose literals or identifiers contain write keywords', () => {- const sql = safeSql`with t as (select 'update' as "delete") select * from t`- expect(applyAutoLimit(sql, 100).appendAutoLimit).toBe(true)++ test.each([+ [+ 'a recursive CTE whose inner query has its own limit',+ 'with recursive t as (select 1 as n limit 5) select * from t',+ ],+ [+ 'a read-only CTE whose literals or identifiers contain write keywords',+ `with t as (select 'update' as "delete") select * from t`,+ ],+ ])('appends the limit to %s', (_, query) => {+ expect(applyAutoLimit(query as SafeSqlFragment, 100).appendAutoLimit).toBe(true)})+test.each([+ // Existing limits, in any casing/whitespace/order, including LIMIT ALL / NULL+ 'select * from countries limit 10;',+ 'SELECT * FROM countries LIMIT 10;',+ 'select * from countries limit 10 ;',+ 'select * from countries limit 10 offset 0;',+ 'select * from countries limit 10 offset 0 ;',+ 'select * from countries offset 0 limit 1;',+ 'select * from countries limit',+ 'select * from countries limit all;',+ 'select * from countries limit all',+ 'SELECT * FROM countries LIMIT ALL ;',+ 'select * from countries limit null;',+ 'select * from countries limit all offset 5;',+ 'select * from countries offset 5 limit null',+ 'with t as (select 1) select * from t limit 10',+ // FETCH FIRST / NEXT instead of limit+ 'select * from countries FETCH FIRST 5 rows only',+ 'select * from countries fetch first 5 rows only',+ 'select * from countries offset 5 rows FETCH NEXT 5 rows only',+ // CTEs that write'with d as (delete from t returning *) select * from d','with s as (select 1) insert into t select * from s','with s as (select 1) update t set a = 1','with t as (select 1) select * into new_t from t',- ])('Should return false for a CTE query that writes: %s', (query) => {- expect(applyAutoLimit(query as SafeSqlFragment, 100).appendAutoLimit).toBe(false)- })- test('Should return false if query already has a limit (check for case-insensitiveness)', () => {- const sql = safeSql`SELECT * FROM countries LIMIT 10;`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return false if query already has a limit with whitespace before the semi colon', () => {- const sql = safeSql`select * from countries limit 10 ;`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return false if query already has a limit and offset', () => {- const sql = safeSql`select * from countries limit 10 offset 0;`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return false if query already has a limit and offset with whitespace before the semi colon', () => {- const sql = safeSql`select * from countries limit 10 offset 0 ;`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return false if query already has a limit and offset (flip order of limit and offset)', () => {- const sql = safeSql`select * from countries offset 0 limit 1;`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return false if query already has a limit, even if no value provided for limit', () => {- const sql = safeSql`select * from countries limit`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return false if query uses `FETCH FIRST` instead of limit ', () => {- const sql = safeSql`select * from countries FETCH FIRST 5 rows only`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return false if query uses `fetch first` instead of limit ', () => {- const sql = safeSql`select * from countries fetch first 5 rows only`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return false if query uses `fetch first` (with random spaces) instead of limit ', () => {- const sql = safeSql`select * from countries FETCH FIRST 5 rows only`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return false if query uses `FETCH NEXT` instead of limit ', () => {- const sql = safeSql`select * from countries offset 5 rows FETCH NEXT 5 rows only`- const { sql: result, appendAutoLimit } = applyAutoLimit(sql, 100)- expect(appendAutoLimit).toBe(false)- expect(result).toBe(sql)- })- test('Should return false if query is not a select statement', () => {- const sql = safeSql`create table test (id int8 primary key, name varchar);`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return false if there are multiple queries I', () => {- const sql1 = safeSql`select * from countries;-select * from cities;`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql1, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return false if there are multiple queries II', () => {- const sql1 = safeSql`select * from countries;-select * from cities`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql1, limit)- expect(appendAutoLimit).toBe(false)- })- // [Joshen] Opting to just avoid appending in this case to prevent making the logic overly complex atm- test('Should return false if query has with a comment I', () => {- const sql = safeSql`-- This is a comment-select * from cities`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })- test('Should return false if query has with a comment II', () => {- const sql = safeSql`select * from cities--- This is a comment`- const limit = 100- const { appendAutoLimit } = applyAutoLimit(sql, limit)- expect(appendAutoLimit).toBe(false)- })-- // [Joshen] These will just need to test the cases when appendAutoLimit returns true then- test('Should add the limit param properly if query ends without a semi colon', () => {- const sql = safeSql`select * from countries`- const limit = 100- const { sql: formattedSql } = applyAutoLimit(sql, limit)- expect(formattedSql).toBe('select * from countries limit 100;')- })- test('Should add the limit param properly if query ends with a semi colon', () => {- const sql = safeSql`select * from countries;`- const limit = 100- const { sql: formattedSql } = applyAutoLimit(sql, limit)- expect(formattedSql).toBe('select * from countries limit 100;')- })- test('Should add the limit param properly if query ends with multiple semi colon', () => {- const sql = safeSql`select * from countries;;;;;;;`- const limit = 100- const { sql: formattedSql } = applyAutoLimit(sql, limit)- expect(formattedSql).toBe('select * from countries limit 100;')- })- test('Should not append a limit if query already has one with whitespace before the semi colon', () => {- const sql = safeSql`select * from countries limit 10 ;`- const limit = 100- const { sql: formattedSql } = applyAutoLimit(sql, limit)- expect(formattedSql).toBe('select * from countries limit 10 ;')- })- test('returns the SafeSqlFragment result unchanged when no limit is appended', () => {- const sql = safeSql`select * from countries limit 10;`- const { sql: formattedSql } = applyAutoLimit(sql, 100)- expect(formattedSql).toBe(sql)+ // Non-select statements and multiple statements+ 'create table test (id int8 primary key, name varchar);',+ 'select * from countries;\nselect * from cities;',+ 'select * from countries;\nselect * from cities',+ // [Joshen] Opting to just avoid appending with comments to keep the logic simple atm+ '-- This is a comment\nselect * from cities',+ 'select * from cities\n-- This is a comment',+ ])('leaves the query unchanged: %s', (query) => {+ expect(applyAutoLimit(query as SafeSqlFragment, 100)).toEqual({+ sql: query,+ appendAutoLimit: false,+ })})})diff --git a/apps/studio/data/storage/bucket-objects-infinite-query.test.ts b/apps/studio/data/storage/bucket-objects-infinite-query.test.tsindex d70cc19f70e..a362a026676 100644--- a/apps/studio/data/storage/bucket-objects-infinite-query.test.ts+++ b/apps/studio/data/storage/bucket-objects-infinite-query.test.ts@@ -29,30 +29,22 @@ const runQueryFn = (path: string, search?: string, pageParam?: string) => {}describe('bucketObjectsInfiniteQueryOptions', () => {- it('browses the bucket root with an empty prefix', async () => {+ // list-v2 with with_delimiter:true treats a bare "photos" as a partial name match against+ // siblings like "photos-old", so browsing into a folder needs a trailing slash.+ it.each([+ ['browses the bucket root with an empty prefix', '', undefined, ''],+ ['appends a trailing slash to browse into a subfolder', 'photos', undefined, 'photos/'],+ [+ 'folds a search string into the prefix without a trailing slash',+ 'photos',+ 'inv',+ 'photos/inv',+ ],+ ['searches at the bucket root without a leading slash', '', 'inv', 'inv'],+ ])('%s', async (_, path, search, expectedPrefix) => {const getBody = captureRequestBody()- await runQueryFn('')- expect(getBody()?.prefix).toBe('')- })-- it('appends a trailing slash to browse into a subfolder', async () => {- // list-v2 with with_delimiter:true treats a bare "photos" as a partial name match- // against siblings like "photos-old" rather than descending into the folder.- const getBody = captureRequestBody()- await runQueryFn('photos')- expect(getBody()?.prefix).toBe('photos/')- })-- it('folds a search string into the prefix without a trailing slash after it', async () => {- const getBody = captureRequestBody()- await runQueryFn('photos', 'inv')- expect(getBody()?.prefix).toBe('photos/inv')- })-- it('searches at the bucket root without a leading slash', async () => {- const getBody = captureRequestBody()- await runQueryFn('', 'inv')- expect(getBody()?.prefix).toBe('inv')+ await runQueryFn(path, search)+ expect(getBody()?.prefix).toBe(expectedPrefix)})it('forwards the page param as the cursor', async () => {diff --git a/apps/studio/data/table-rows/table-rows-query.test.ts b/apps/studio/data/table-rows/table-rows-query.test.tsindex 7803ddf68a5..2eb67ba3431 100644--- a/apps/studio/data/table-rows/table-rows-query.test.ts+++ b/apps/studio/data/table-rows/table-rows-query.test.ts@@ -1,35 +1,47 @@-import { describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { executeWithRetry } from './table-rows-query'+const rateLimitError = { status: 429, headers: { get: () => '1' } }+describe('executeWithRetry', () => {- it('should return the result of the function when successful', async () => {+ beforeEach(() => {+ vi.useFakeTimers()+ })+ afterEach(() => {+ vi.useRealTimers()+ })++ it('returns the result of the function when successful', async () => {const mockFn = vi.fn().mockResolvedValue('success')- const result = await executeWithRetry(mockFn)- expect(result).toBe('success')+ await expect(executeWithRetry(mockFn)).resolves.toBe('success')expect(mockFn).toHaveBeenCalledTimes(1)})- it('should retry on 429 errors with exponential backoff', async () => {+ it('retries on 429 errors until the function succeeds', async () => {const mockFn = vi.fn()- .mockRejectedValueOnce({ status: 429, headers: { get: () => '1' } })- .mockRejectedValueOnce({ status: 429, headers: { get: () => '1' } })+ .mockRejectedValueOnce(rateLimitError)+ .mockRejectedValueOnce(rateLimitError).mockResolvedValue('success')- const result = await executeWithRetry(mockFn)- expect(result).toBe('success')+ const result = executeWithRetry(mockFn)+ await vi.runAllTimersAsync()+ await expect(result).resolves.toBe('success')expect(mockFn).toHaveBeenCalledTimes(3)})- it('should throw error after max retries', async () => {- const mockFn = vi.fn().mockRejectedValue({ status: 429, headers: { get: () => '1' } })+ it('throws after max retries', async () => {+ const mockFn = vi.fn().mockRejectedValue(rateLimitError)- await expect(executeWithRetry(mockFn, 2)).rejects.toMatchObject({ status: 429 })+ const result = executeWithRetry(mockFn, 2)+ const assertion = expect(result).rejects.toMatchObject({ status: 429 })+ await vi.runAllTimersAsync()+ await assertionexpect(mockFn).toHaveBeenCalledTimes(3) // Initial attempt + 2 retries})- it('should throw non-429 errors immediately', async () => {+ it('throws non-429 errors immediately', async () => {const mockFn = vi.fn().mockRejectedValue(new Error('Some other error'))await expect(executeWithRetry(mockFn)).rejects.toThrow('Some other error')diff --git a/apps/studio/data/usage/org-usage-query.test.ts b/apps/studio/data/usage/org-usage-query.test.tsindex 045f7b24c73..1526ed64264 100644--- a/apps/studio/data/usage/org-usage-query.test.ts+++ b/apps/studio/data/usage/org-usage-query.test.ts@@ -1,122 +1,64 @@-import { describe, expect, it, vi } from 'vitest'+import { HttpResponse } from 'msw'+import { describe, expect, it } from 'vitest'import { getOrgUsage } from './org-usage-query'+import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'++function captureUsageRequest() {+ const captured: { searchParams?: URLSearchParams } = {}+ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/usage',+ response: ({ request, params }) => {+ expect(params.slug).toBe('test-org')+ captured.searchParams = new URL(request.url).searchParams+ return HttpResponse.json({ usage_billing_enabled: true, usages: [] })+ },+ })+ return captured+}-vi.mock('@/data/fetchers', () => ({- get: vi.fn(),- handleError: vi.fn((error) => {- throw error- }),-}))--describe('org-usage-query', () => {- describe('getOrgUsage', () => {- it('throws error when orgSlug is not provided', async () => {- await expect(getOrgUsage({ orgSlug: undefined })).rejects.toThrow('orgSlug is required')- })-- it('calls API with correct parameters including project_ref', async () => {- const { get } = await import('@/data/fetchers')- const mockGet = get as unknown as ReturnType<typeof vi.fn>-- const mockResponse = { usages: [] }- mockGet.mockResolvedValueOnce({ data: mockResponse, error: null })-- const startDate = new Date('2025-01-01T00:00:00.000Z')- const endDate = new Date('2025-01-31T23:59:59.000Z')+describe('getOrgUsage', () => {+ it('throws when orgSlug is not provided', async () => {+ await expect(getOrgUsage({ orgSlug: undefined })).rejects.toThrow('orgSlug is required')+ })- const result = await getOrgUsage({- orgSlug: 'test-org',- projectRef: 'test-project-ref',- start: startDate,- end: endDate,- })+ it('sends project_ref and ISO date params when provided', async () => {+ const captured = captureUsageRequest()- expect(mockGet).toHaveBeenCalledWith(- '/platform/organizations/{slug}/usage',- expect.objectContaining({- params: {- path: { slug: 'test-org' },- query: {- project_ref: 'test-project-ref',- start: '2025-01-01T00:00:00.000Z',- end: '2025-01-31T23:59:59.000Z',- },- },- })- )- expect(result).toEqual(mockResponse)+ const result = await getOrgUsage({+ orgSlug: 'test-org',+ projectRef: 'test-project-ref',+ start: new Date('2025-01-01T00:00:00.000Z'),+ end: new Date('2025-01-31T23:59:59.000Z'),})- it('calls API without project_ref when projectRef is null', async () => {- const { get } = await import('@/data/fetchers')- const mockGet = get as unknown as ReturnType<typeof vi.fn>-- const mockResponse = { usages: [] }- mockGet.mockResolvedValueOnce({ data: mockResponse, error: null })-- await getOrgUsage({- orgSlug: 'test-org',- projectRef: null,- })-- expect(mockGet).toHaveBeenCalledWith(- '/platform/organizations/{slug}/usage',- expect.objectContaining({- params: {- path: { slug: 'test-org' },- query: {- project_ref: undefined,- start: undefined,- end: undefined,- },- },- })- )- })+ expect(result).toEqual({ usage_billing_enabled: true, usages: [] })+ expect(captured.searchParams?.get('project_ref')).toBe('test-project-ref')+ expect(captured.searchParams?.get('start')).toBe('2025-01-01T00:00:00.000Z')+ expect(captured.searchParams?.get('end')).toBe('2025-01-31T23:59:59.000Z')+ })- it('calls API without date params when start and end are undefined', async () => {- const { get } = await import('@/data/fetchers')- const mockGet = get as unknown as ReturnType<typeof vi.fn>+ it.each([+ ['projectRef is null', null],+ ['projectRef is undefined', undefined],+ ])('omits optional params when %s and no dates are given', async (_, projectRef) => {+ const captured = captureUsageRequest()- const mockResponse = { usages: [] }- mockGet.mockResolvedValueOnce({ data: mockResponse, error: null })+ await getOrgUsage({ orgSlug: 'test-org', projectRef })- await getOrgUsage({- orgSlug: 'test-org',- })+ expect(captured.searchParams?.has('project_ref')).toBe(false)+ expect(captured.searchParams?.has('start')).toBe(false)+ expect(captured.searchParams?.has('end')).toBe(false)+ })- expect(mockGet).toHaveBeenCalledWith(- '/platform/organizations/{slug}/usage',- expect.objectContaining({- params: {- path: { slug: 'test-org' },- query: {- project_ref: undefined,- start: undefined,- end: undefined,- },- },- })- )+ it('surfaces API errors', async () => {+ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/usage',+ response: () => HttpResponse.json<APIErrorBody>({ message: 'API Error' }, { status: 500 }),})- it('handles API errors correctly', async () => {- const { get, handleError } = await import('@/data/fetchers')- const mockGet = get as unknown as ReturnType<typeof vi.fn>- const mockHandleError = handleError as unknown as ReturnType<typeof vi.fn>-- const mockError = { message: 'API Error' }- mockGet.mockResolvedValueOnce({ data: null, error: mockError })- mockHandleError.mockImplementation((error) => {- throw new Error(error.message)- })-- await expect(- getOrgUsage({- orgSlug: 'test-org',- })- ).rejects.toThrow('API Error')- })+ await expect(getOrgUsage({ orgSlug: 'test-org' })).rejects.toThrow('API Error')})})diff --git a/apps/studio/evals/scorer.test.ts b/apps/studio/evals/scorer.test.tsindex 7bee6e92e58..eaa29bc8831 100644--- a/apps/studio/evals/scorer.test.ts+++ b/apps/studio/evals/scorer.test.ts@@ -93,19 +93,13 @@ describe('scorers with online (null) output', () => {})describe('toolUsageScorer', () => {- it('returns null when expected specifies neither requiredTools nor forbiddenTools', async () => {- const { trace } = mockToolTrace([])- await expect(runToolUsageScorer({}, trace)).resolves.toBeNull()- })-- it('returns null when requiredTools is an empty array and forbiddenTools is unset', async () => {- const { trace } = mockToolTrace([{ name: 'execute_sql' }])- await expect(runToolUsageScorer({ requiredTools: [] }, trace)).resolves.toBeNull()- })-- it('returns null when forbiddenTools is an empty array and requiredTools is unset', async () => {+ it.each<[string, Expected]>([+ ['neither requiredTools nor forbiddenTools is specified', {}],+ ['requiredTools is empty and forbiddenTools is unset', { requiredTools: [] }],+ ['forbiddenTools is empty and requiredTools is unset', { forbiddenTools: [] }],+ ])('returns null when %s', async (_, expected) => {const { trace } = mockToolTrace([{ name: 'execute_sql' }])- await expect(runToolUsageScorer({ forbiddenTools: [] }, trace)).resolves.toBeNull()+ await expect(runToolUsageScorer(expected, trace)).resolves.toBeNull()})it('returns null when there is no trace', async () => {diff --git a/apps/studio/hooks/analytics/useFillTimeseriesSorted.test.ts b/apps/studio/hooks/analytics/useFillTimeseriesSorted.test.tsindex 0ea09e7d3dd..15c607791b2 100644--- a/apps/studio/hooks/analytics/useFillTimeseriesSorted.test.ts+++ b/apps/studio/hooks/analytics/useFillTimeseriesSorted.test.ts@@ -1,106 +1,46 @@import { describe, expect, it } from 'vitest'import { hasValidTimestamp, sortByTimestamp } from './useFillTimeseriesSorted'+import type { Datum } from '@/components/ui/Charts/Charts.types'describe('hasValidTimestamp', () => {- it('should return true when data has valid timestamp key', () => {- const data = [{ timestamp: '2024-01-01T00:00:00Z', value: 1 }]- expect(hasValidTimestamp(data, 'timestamp')).toBe(true)- })-- it('should return false when data is empty', () => {- expect(hasValidTimestamp([], 'timestamp')).toBe(false)- })-- it('should return false when timestamp key does not exist', () => {- const data = [{ value: 1 }]- expect(hasValidTimestamp(data, 'timestamp')).toBe(false)- })-- it('should work with custom timestamp key', () => {- const data = [{ period_start: '2024-01-01T00:00:00Z', value: 1 }]- expect(hasValidTimestamp(data, 'period_start')).toBe(true)+ it.each<[string, Datum[], string, boolean]>([+ ['has the timestamp key', [{ timestamp: '2024-01-01T00:00:00Z', value: 1 }], 'timestamp', true],+ [+ 'has a custom timestamp key',+ [{ period_start: '2024-01-01T00:00:00Z' }],+ 'period_start',+ true,+ ],+ ['is empty', [], 'timestamp', false],+ ['lacks the timestamp key', [{ value: 1 }], 'timestamp', false],+ ])('when data %s', (_, data, key, expected) => {+ expect(hasValidTimestamp(data, key)).toBe(expected)})})describe('sortByTimestamp', () => {- it('should sort data in ascending order by timestamp', () => {- const data = [- { timestamp: '2024-01-03T00:00:00Z', value: 3 },- { timestamp: '2024-01-01T00:00:00Z', value: 1 },- { timestamp: '2024-01-02T00:00:00Z', value: 2 },- ]-- const sorted = sortByTimestamp(data, 'timestamp')-- expect(sorted[0].value).toBe(1)- expect(sorted[1].value).toBe(2)- expect(sorted[2].value).toBe(3)- })-- it('should handle already sorted data', () => {- const data = [- { timestamp: '2024-01-01T00:00:00Z', value: 1 },- { timestamp: '2024-01-02T00:00:00Z', value: 2 },- ]-- const sorted = sortByTimestamp(data, 'timestamp')-- expect(sorted[0].value).toBe(1)- expect(sorted[1].value).toBe(2)- })-- it('should handle empty array', () => {- const sorted = sortByTimestamp([], 'timestamp')- expect(sorted).toEqual([])- })-- it('should handle single item', () => {- const data = [{ timestamp: '2024-01-01T00:00:00Z', value: 1 }]- const sorted = sortByTimestamp(data, 'timestamp')- expect(sorted).toEqual(data)- })-- it('should work with custom timestamp key', () => {+ it('sorts data in ascending order by the given timestamp key', () => {const data = [{ period_start: '2024-01-03T00:00:00Z', value: 3 },- { period_start: '2024-01-01T00:00:00Z', value: 1 },+ { period_start: '2024-01-01T12:00:00Z', value: 1 },{ period_start: '2024-01-02T00:00:00Z', value: 2 },]- const sorted = sortByTimestamp(data, 'period_start')-- expect(sorted[0].value).toBe(1)- expect(sorted[1].value).toBe(2)- expect(sorted[2].value).toBe(3)+ expect(sortByTimestamp(data, 'period_start').map((d) => d.value)).toEqual([1, 2, 3])})- it('should handle timestamps with different time zones', () => {- const data = [- { timestamp: '2024-01-01T12:00:00Z', value: 2 },- { timestamp: '2024-01-01T00:00:00Z', value: 1 },- { timestamp: '2024-01-01T18:00:00Z', value: 3 },- ]-- const sorted = sortByTimestamp(data, 'timestamp')-- expect(sorted[0].value).toBe(1)- expect(sorted[1].value).toBe(2)- expect(sorted[2].value).toBe(3)+ it('handles an empty array', () => {+ expect(sortByTimestamp([], 'timestamp')).toEqual([])})- it('should maintain stable sort for equal timestamps', () => {+ it('keeps the original order for equal timestamps', () => {const data = [- { timestamp: '2024-01-01T00:00:00Z', value: 1, id: 'a' },- { timestamp: '2024-01-01T00:00:00Z', value: 2, id: 'b' },- { timestamp: '2024-01-01T00:00:00Z', value: 3, id: 'c' },+ { timestamp: '2024-01-01T00:00:00Z', id: 'a' },+ { timestamp: '2024-01-01T00:00:00Z', id: 'b' },+ { timestamp: '2024-01-01T00:00:00Z', id: 'c' },]- const sorted = sortByTimestamp(data, 'timestamp')-- // Should maintain original order for equal timestamps- expect(sorted[0].id).toBe('a')- expect(sorted[1].id).toBe('b')- expect(sorted[2].id).toBe('c')+ expect(sortByTimestamp(data, 'timestamp').map((d) => d.id)).toEqual(['a', 'b', 'c'])})})diff --git a/apps/studio/hooks/custom-content/useCustomContent.test.ts b/apps/studio/hooks/custom-content/useCustomContent.test.tsindex eb978c3190f..e3df5139a18 100644--- a/apps/studio/hooks/custom-content/useCustomContent.test.ts+++ b/apps/studio/hooks/custom-content/useCustomContent.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { cleanup, renderHook } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'diff --git a/apps/studio/hooks/misc/__tests__/useDataApiRevokeOnCreateDefault.test.ts b/apps/studio/hooks/misc/__tests__/useDataApiRevokeOnCreateDefault.test.tsindex ee275f597ef..b9e74ce8a82 100644--- a/apps/studio/hooks/misc/__tests__/useDataApiRevokeOnCreateDefault.test.ts+++ b/apps/studio/hooks/misc/__tests__/useDataApiRevokeOnCreateDefault.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { renderHook } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -27,66 +28,36 @@ vi.mock('@/lib/telemetry/track', () => ({}))describe('isInDataApiRevokeTreatment', () => {- it('returns true for boolean true (current rollout shape)', () => {- expect(isInDataApiRevokeTreatment(true)).toBe(true)- })-- it("returns true for the 'test' variant (future multivariate shape)", () => {- expect(isInDataApiRevokeTreatment('test')).toBe(true)- })-- it('returns false for boolean false', () => {- expect(isInDataApiRevokeTreatment(false)).toBe(false)- })-- it("returns false for the 'control' variant", () => {- expect(isInDataApiRevokeTreatment('control')).toBe(false)- })-- it('returns false for undefined (flag not resolved)', () => {- expect(isInDataApiRevokeTreatment(undefined)).toBe(false)- })-- it('returns false for unrelated string values', () => {- expect(isInDataApiRevokeTreatment('something-else')).toBe(false)- expect(isInDataApiRevokeTreatment('')).toBe(false)+ // `true` is the current rollout shape; 'test'/'control' the future multivariate shape.+ it.each([+ [true, true],+ ['test', true],+ [false, false],+ ['control', false],+ [undefined, false],+ ['something-else', false],+ ['', false],+ ])('maps flag %s to %s', (flag, expected) => {+ expect(isInDataApiRevokeTreatment(flag)).toBe(expected)})})+// Flag-shape permutations are covered by isInDataApiRevokeTreatment above.describe('useDataApiRevokeOnCreateDefaultEnabled', () => {afterEach(() => {vi.restoreAllMocks()vi.mocked(constants, { partial: true }).IS_TEST_ENV = false})- it('returns false when the PostHog flag is undefined (not yet resolved)', () => {- vi.mocked(usePHFlag).mockReturnValue(undefined)- const { result } = renderHook(() => useDataApiRevokeOnCreateDefaultEnabled())- expect(result.current).toBe(false)- })-- it('returns false when the PostHog flag is false', () => {- vi.mocked(usePHFlag).mockReturnValue(false)- const { result } = renderHook(() => useDataApiRevokeOnCreateDefaultEnabled())- expect(result.current).toBe(false)- })-- it('returns true when the PostHog flag is true', () => {- vi.mocked(usePHFlag).mockReturnValue(true)+ it.each([+ [undefined, false],+ ['control', false],+ [true, true],+ ['test', true],+ ])('maps PostHog flag %s to %s', (flag, expected) => {+ vi.mocked(usePHFlag).mockReturnValue(flag)const { result } = renderHook(() => useDataApiRevokeOnCreateDefaultEnabled())- expect(result.current).toBe(true)- })-- it("returns true when the PostHog flag is the 'test' variant string", () => {- vi.mocked(usePHFlag).mockReturnValue('test')- const { result } = renderHook(() => useDataApiRevokeOnCreateDefaultEnabled())- expect(result.current).toBe(true)- })-- it("returns false when the PostHog flag is the 'control' variant string", () => {- vi.mocked(usePHFlag).mockReturnValue('control')- const { result } = renderHook(() => useDataApiRevokeOnCreateDefaultEnabled())- expect(result.current).toBe(false)+ expect(result.current).toBe(expected)})it('returns false in test env regardless of flag value', () => {diff --git a/apps/studio/hooks/misc/__tests__/useDeploymentMode.test.ts b/apps/studio/hooks/misc/__tests__/useDeploymentMode.test.tsindex 4f540cb8330..e0d33ca459f 100644--- a/apps/studio/hooks/misc/__tests__/useDeploymentMode.test.ts+++ b/apps/studio/hooks/misc/__tests__/useDeploymentMode.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { renderHook } from '@testing-library/react'import { beforeEach, describe, expect, test, vi } from 'vitest'@@ -41,43 +42,18 @@ describe('useDeploymentMode', () => {})})- test('non-platform, loading window (data undefined): defaults to CLI', () => {- // `?? true` flip — see useDeploymentMode for the asymmetry rationale.- // `'direct'` is the only universally-valid method, so CLI-during-loading- // is the safe guess that avoids pinning an invalid `connectionMethod`.- mockUseDeploymentModeQuery.mockReturnValue({ data: undefined })-- const { result } = renderHook(() => useDeploymentMode())-- expect(result.current).toEqual({- isPlatform: false,- isCli: true,- isSelfHosted: false,- })- })-- test('non-platform, resolved is_cli_mode=true: CLI', () => {- mockUseDeploymentModeQuery.mockReturnValue({ data: { is_cli_mode: true } })-- const { result } = renderHook(() => useDeploymentMode())-- expect(result.current).toEqual({- isPlatform: false,- isCli: true,- isSelfHosted: false,- })- })-- test('non-platform, resolved is_cli_mode=false: self-hosted', () => {- mockUseDeploymentModeQuery.mockReturnValue({ data: { is_cli_mode: false } })+ // Loading (data undefined) defaults to CLI via the `?? true` flip — see useDeploymentMode for+ // the asymmetry rationale: `'direct'` is the only universally-valid connection method.+ test.each([+ ['loading window (data undefined)', undefined, { isCli: true, isSelfHosted: false }],+ ['resolved is_cli_mode=true', { is_cli_mode: true }, { isCli: true, isSelfHosted: false }],+ ['resolved is_cli_mode=false', { is_cli_mode: false }, { isCli: false, isSelfHosted: true }],+ ])('non-platform, %s', (_, data, expected) => {+ mockUseDeploymentModeQuery.mockReturnValue({ data })const { result } = renderHook(() => useDeploymentMode())- expect(result.current).toEqual({- isPlatform: false,- isCli: false,- isSelfHosted: true,- })+ expect(result.current).toEqual({ isPlatform: false, ...expected })})test('returns a stable reference across renders when primitive flags do not change', () => {diff --git a/apps/studio/hooks/misc/__tests__/useEnabledIdentityProviders.test.ts b/apps/studio/hooks/misc/__tests__/useEnabledIdentityProviders.test.tsindex 705ffd20a93..69152e47639 100644--- a/apps/studio/hooks/misc/__tests__/useEnabledIdentityProviders.test.ts+++ b/apps/studio/hooks/misc/__tests__/useEnabledIdentityProviders.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { renderHook } from '@testing-library/react'import { describe, expect, it, vi } from 'vitest'@@ -21,43 +22,16 @@ function mockFeatures({ github = false, chatgpt = true }: { github?: boolean; ch}describe('useEnabledIdentityProviders', () => {- it('returns every provider when all flags are enabled', () => {- mockFeatures({ github: true, chatgpt: true })+ it.each([+ [{ github: true, chatgpt: true }, [GITHUB_IDENTITY_PROVIDER, CHATGPT_IDENTITY_PROVIDER]],+ [{ github: true, chatgpt: false }, [GITHUB_IDENTITY_PROVIDER]],+ [{ github: false, chatgpt: true }, [CHATGPT_IDENTITY_PROVIDER]],+ [{ github: false, chatgpt: false }, []],+ ])('returns only the providers whose flags are enabled: %o', (flags, expected) => {+ mockFeatures(flags)const { result } = renderHook(() => useEnabledIdentityProviders())- expect(result.current).toEqual([GITHUB_IDENTITY_PROVIDER, CHATGPT_IDENTITY_PROVIDER])- })-- it('returns no providers when all flags are disabled', () => {- mockFeatures({ github: false, chatgpt: false })-- const { result } = renderHook(() => useEnabledIdentityProviders())-- expect(result.current).toEqual([])- })-- it('includes ChatGPT when its feature flag is enabled', () => {- mockFeatures({ chatgpt: true })-- const { result } = renderHook(() => useEnabledIdentityProviders())-- expect(result.current).toEqual([CHATGPT_IDENTITY_PROVIDER])- })-- it('excludes ChatGPT when its feature flag is disabled', () => {- mockFeatures({ github: true, chatgpt: false })-- const { result } = renderHook(() => useEnabledIdentityProviders())-- expect(result.current).toEqual([GITHUB_IDENTITY_PROVIDER])- })-- it('excludes GitHub when its feature flag is disabled', () => {- mockFeatures({ github: false, chatgpt: true })-- const { result } = renderHook(() => useEnabledIdentityProviders())-- expect(result.current).toEqual([CHATGPT_IDENTITY_PROVIDER])+ expect(result.current).toEqual(expected)})})diff --git a/apps/studio/hooks/misc/__tests__/useInboundBranding.test.ts b/apps/studio/hooks/misc/__tests__/useInboundBranding.test.tsindex d54755ce913..d5576854f68 100644--- a/apps/studio/hooks/misc/__tests__/useInboundBranding.test.ts+++ b/apps/studio/hooks/misc/__tests__/useInboundBranding.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport mockRouter from 'next-router-mock'import { beforeEach, describe, expect, it, vi } from 'vitest'diff --git a/apps/studio/hooks/misc/__tests__/useLocalStorageQuery.test.ts b/apps/studio/hooks/misc/__tests__/useLocalStorageQuery.test.tsindex 44b163141a3..b916a11b5da 100644--- a/apps/studio/hooks/misc/__tests__/useLocalStorageQuery.test.ts+++ b/apps/studio/hooks/misc/__tests__/useLocalStorageQuery.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, renderHook, waitFor } from '@testing-library/react'import React from 'react'diff --git a/apps/studio/hooks/misc/__tests__/useLongRunningTransitionState.test.ts b/apps/studio/hooks/misc/__tests__/useLongRunningTransitionState.test.tsindex d770446353c..ff4230c57c1 100644--- a/apps/studio/hooks/misc/__tests__/useLongRunningTransitionState.test.ts+++ b/apps/studio/hooks/misc/__tests__/useLongRunningTransitionState.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { act, renderHook } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'diff --git a/apps/studio/hooks/misc/__tests__/useShowMultigresLogs.test.ts b/apps/studio/hooks/misc/__tests__/useShowMultigresLogs.test.tsindex 0dac534c708..5693838106d 100644--- a/apps/studio/hooks/misc/__tests__/useShowMultigresLogs.test.ts+++ b/apps/studio/hooks/misc/__tests__/useShowMultigresLogs.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { renderHook } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'diff --git a/apps/studio/hooks/misc/__tests__/useShowUpgradeCta.test.ts b/apps/studio/hooks/misc/__tests__/useShowUpgradeCta.test.tsindex d616c3b7eca..27b3d28cf5d 100644--- a/apps/studio/hooks/misc/__tests__/useShowUpgradeCta.test.ts+++ b/apps/studio/hooks/misc/__tests__/useShowUpgradeCta.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { renderHook } from '@testing-library/react'import { beforeEach, describe, expect, test, vi } from 'vitest'diff --git a/apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx b/apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsxindex cc9630d40b2..d498fcc99f7 100644--- a/apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx+++ b/apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx@@ -10,7 +10,7 @@ import {} from '@tanstack/react-router'import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import { useMemo } from 'react'-import { describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import Link from '@/compat/next/link'import { useSyncFiltersToUrl } from '@/components/grid/hooks/useFilterLifeCycle'@@ -75,10 +75,18 @@ function TablePage() {}// Allow the production filter synchronizer's 500ms debounce to finish before traversing.-const settleFilters = () => act(async () => new Promise((resolve) => setTimeout(resolve, 650)))+const settleFilters = () => act(() => vi.advanceTimersByTimeAsync(650))for (const basepath of ['/', '/dashboard']) {describe(`table filter history at ${basepath}`, () => {+ // Fake time still advances on its own so waitFor polling and router microtasks keep working.+ beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+ })+ afterEach(() => {+ vi.useRealTimers()+ })+it.each([false, true])('preserves repeated Back/Forward with retained application state: %s',async (hasApplicationState) => {@@ -142,7 +150,7 @@ for (const basepath of ['/', '/dashboard']) {// Leaving before the next debounce must cancel the old table's pending URL update.fireEvent.click(screen.getByText('Change filter'))- await act(async () => new Promise((resolve) => setTimeout(resolve, 0)))+ await act(() => vi.advanceTimersByTimeAsync(0))fireEvent.click(screen.getByText('Table A'))await waitFor(() => expect(screen.getByTestId('table')).toHaveTextContent('17489'))await settleFilters()@@ -154,8 +162,7 @@ for (const basepath of ['/', '/dashboard']) {push.mockRestore()history.destroy()}- },- 10000+ })})}diff --git a/apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.test.ts b/apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.test.tsindex a0ebb9225a1..4fbf2de8b3c 100644--- a/apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.test.ts+++ b/apps/studio/hooks/misc/__tests__/useTableEditorFiltersSort.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { act, renderHook } from '@testing-library/react'import mockRouter from 'next-router-mock'import { useRouter } from 'next/router'@@ -9,25 +10,7 @@ import { useTableEditorFiltersSort } from '../useTableEditorFiltersSort'vi.mock('next/router', () => import('next-router-mock'))describe('useTableEditorFilters', () => {- it('should support old syntax', async () => {- const url =- '/test?filter=id:eq:123&filter=created_at:eq:2021-01-01&filter=id:eq:456&sort=id:asc'-- const expected = ['id:eq:123', 'created_at:eq:2021-01-01', 'id:eq:456']-- const router = renderHook(() => useRouter()).result.current- router.push(url)-- const { result } = renderHook(() => useTableEditorFiltersSort(), {- wrapper: withNuqsTestingAdapter(),- })-- expect(result.current.filters).toEqual(expected)-- expect(result.current.sorts).toEqual(['id:asc'])- })-- it('should support new syntax', async () => {+ it('reads repeated filter and sort params from the URL', async () => {const router = renderHook(() => useRouter()).result.currentrouter.push('/test?filter=id:eq:123&filter=created_at:eq:2021-01-01&filter=id:eq:456&sort=id:asc'@@ -41,7 +24,7 @@ describe('useTableEditorFilters', () => {expect(result.current.sorts).toEqual(['id:asc'])})- it('should return empty array if no filters are present', async () => {+ it('returns empty arrays when filters or sorts are absent', async () => {const router = renderHook(() => useRouter()).result.currentrouter.push('/test')@@ -50,16 +33,6 @@ describe('useTableEditorFilters', () => {})expect(result.current.filters).toEqual([])- })-- it('should return empty array if no sorts are present', async () => {- const router = renderHook(() => useRouter()).result.current- router.push('/test?filter=id:eq:123&filter=created_at:eq:2021-01-01&filter=id:eq:456')-- const { result } = renderHook(() => useTableEditorFiltersSort(), {- wrapper: withNuqsTestingAdapter(),- })-expect(result.current.sorts).toEqual([])})diff --git a/apps/studio/hooks/misc/__tests__/useUserProjectRegions.test.ts b/apps/studio/hooks/misc/__tests__/useUserProjectRegions.test.tsindex 589ef910568..14bece9af85 100644--- a/apps/studio/hooks/misc/__tests__/useUserProjectRegions.test.ts+++ b/apps/studio/hooks/misc/__tests__/useUserProjectRegions.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { waitFor } from '@testing-library/react'import { platformComponents as components } from 'api-types'import { HttpResponse } from 'msw'diff --git a/apps/studio/hooks/misc/useDashboardHistory.test.tsx b/apps/studio/hooks/misc/useDashboardHistory.test.tsxindex 84b489acd33..c017c6980e6 100644--- a/apps/studio/hooks/misc/useDashboardHistory.test.tsx+++ b/apps/studio/hooks/misc/useDashboardHistory.test.tsx@@ -17,14 +17,6 @@ describe('useDashboardHistory', () => {localStorage.clear()})- it('stores the last visited snippet', async () => {- const { result } = await renderDashboardHistory()-- act(() => result.current.setLastVisitedSnippet('snippet-a'))-- await waitFor(() => expect(result.current.history.sql).toBe('snippet-a'))- })-describe('clearSnippetsFromHistory', () => {it('purges the last visited snippet when it is one of the deleted ids', async () => {const { result } = await renderDashboardHistory()@@ -66,16 +58,6 @@ describe('useDashboardHistory', () => {})describe('setLastVisitedExplorerTab', () => {- it('stores the last visited Explorer tab', async () => {- const { result } = await renderDashboardHistory()-- act(() => result.current.setLastVisitedExplorerTab({ type: 'notebook', id: 'notebook-1' }))-- await waitFor(() =>- expect(result.current.history.explorer).toEqual({ type: 'notebook', id: 'notebook-1' })- )- })-it('clears the last visited Explorer tab when called with undefined', async () => {const { result } = await renderDashboardHistory()diff --git a/apps/studio/hooks/ui/useConfirmOnClose.test.tsx b/apps/studio/hooks/ui/useConfirmOnClose.test.tsxindex 6759ca5279f..cd1a4fff9da 100644--- a/apps/studio/hooks/ui/useConfirmOnClose.test.tsx+++ b/apps/studio/hooks/ui/useConfirmOnClose.test.tsx@@ -22,24 +22,6 @@ describe('useConfirmOnClose', () => {expect(result.current.modalProps.visible).toBe(false)})- it('opens the confirmation modal when the form is dirty', () => {- const onClose = vi.fn()-- const { result } = renderHook(() =>- useConfirmOnClose({- checkIsDirty: () => true,- onClose,- })- )-- act(() => {- result.current.confirmOnClose()- })-- expect(onClose).not.toHaveBeenCalled()- expect(result.current.modalProps.visible).toBe(true)- })-it('ignores open events and handles close events via handleOpenChange', () => {const onClose = vi.fn()diff --git a/apps/studio/lib/__tests__/theme-overrides.test.ts b/apps/studio/lib/__tests__/theme-overrides.test.tsindex 63823bf4af9..fe4ee559689 100644--- a/apps/studio/lib/__tests__/theme-overrides.test.ts+++ b/apps/studio/lib/__tests__/theme-overrides.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { describe, expect, it } from 'vitest'import {@@ -24,14 +25,22 @@ const knob = (key: string) => {}describe.each<ThemeOverrideMode>(['dark', 'light'])('%s theme slider mappings', (mode) => {- it.each(THEME_OVERRIDE_KNOBS)('maps $label endpoints to its safe range', (setting) => {- const range = getThemeOverrideRange(setting, mode)-- expect(sliderValueToThemeOverride(setting, mode, 0)).toBe(range.min)- expect(sliderValueToThemeOverride(setting, mode, 100)).toBe(range.max)- expect(themeOverrideToSliderValue(setting, mode, range.min)).toBe(0)- expect(themeOverrideToSliderValue(setting, mode, range.max)).toBe(100)- })+ it.each(THEME_OVERRIDE_KNOBS)(+ 'maps $label endpoints to its safe range and clamps outside it',+ (setting) => {+ const range = getThemeOverrideRange(setting, mode)++ expect(sliderValueToThemeOverride(setting, mode, 0)).toBe(range.min)+ expect(sliderValueToThemeOverride(setting, mode, 100)).toBe(range.max)+ expect(themeOverrideToSliderValue(setting, mode, range.min)).toBe(0)+ expect(themeOverrideToSliderValue(setting, mode, range.max)).toBe(100)++ expect(themeOverrideToSliderValue(setting, mode, Number.NEGATIVE_INFINITY)).toBe(0)+ expect(themeOverrideToSliderValue(setting, mode, Number.POSITIVE_INFINITY)).toBe(100)+ expect(sliderValueToThemeOverride(setting, mode, -1)).toBe(range.min)+ expect(sliderValueToThemeOverride(setting, mode, 101)).toBe(range.max)+ }+ )it.each(THEME_OVERRIDE_KNOBS)('round trips $label positions', (setting) => {for (const sliderValue of [0, 17, 50, 83, 100]) {@@ -39,17 +48,6 @@ describe.each<ThemeOverrideMode>(['dark', 'light'])('%s theme slider mappings',expect(themeOverrideToSliderValue(setting, mode, rawValue)).toBe(sliderValue)}})-- it.each(THEME_OVERRIDE_KNOBS)('clamps $label outside the safe range', (setting) => {- expect(themeOverrideToSliderValue(setting, mode, Number.NEGATIVE_INFINITY)).toBe(0)- expect(themeOverrideToSliderValue(setting, mode, Number.POSITIVE_INFINITY)).toBe(100)- expect(sliderValueToThemeOverride(setting, mode, -1)).toBe(- getThemeOverrideRange(setting, mode).min- )- expect(sliderValueToThemeOverride(setting, mode, 101)).toBe(- getThemeOverrideRange(setting, mode).max- )- })})describe('dark theme surface elevation', () => {diff --git a/apps/studio/lib/ai/message-utils.test.ts b/apps/studio/lib/ai/message-utils.test.tsindex d5acac0b328..6dfe9d55dff 100644--- a/apps/studio/lib/ai/message-utils.test.ts+++ b/apps/studio/lib/ai/message-utils.test.ts@@ -130,23 +130,6 @@ describe('prepareMessagesForAPI', () => {expect(result[6].parts[0]).toEqual({ type: 'text', text: 'Message 9' })})- it('should remove results property from assistant messages', () => {- const messages = [- {- id: 'msg-1',- role: 'assistant',- parts: [{ type: 'text', text: 'Response' }],- results: { data: 'some data' },- },- ] as Array<UIMessage & { results?: unknown }>-- const result = prepareMessagesForAPI(messages)-- expect(result).toHaveLength(1)- expect(result[0]).not.toHaveProperty('results')- expect(result[0].parts[0]).toEqual({ type: 'text', text: 'Response' })- })-it('should preserve messages without results', () => {const messages: UIMessage[] = [{@@ -168,28 +151,6 @@ describe('prepareMessagesForAPI', () => {expect(result[1]).toEqual(messages[1])})- it('should handle empty array', () => {- const messages: UIMessage[] = []-- const result = prepareMessagesForAPI(messages)-- expect(result).toHaveLength(0)- expect(result).toEqual([])- })-- it('should handle array with fewer than 7 messages', () => {- const messages: UIMessage[] = [- { id: 'msg-1', role: 'user', parts: [{ type: 'text', text: 'Message 1' }] },- { id: 'msg-2', role: 'assistant', parts: [{ type: 'text', text: 'Message 2' }] },- { id: 'msg-3', role: 'user', parts: [{ type: 'text', text: 'Message 3' }] },- ]-- const result = prepareMessagesForAPI(messages)-- expect(result).toHaveLength(3)- expect(result).toEqual(messages)- })-it('should handle array with exactly 7 messages', () => {const messages: UIMessage[] = Array.from({ length: 7 }, (_, i) => ({id: `msg-${i}`,@@ -227,39 +188,4 @@ describe('prepareMessagesForAPI', () => {// Assistant message has results removedexpect(result[1]).not.toHaveProperty('results')})-- it('should handle mixed messages with and without results', () => {- const messages = [- {- id: 'msg-1',- role: 'assistant',- parts: [{ type: 'text', text: 'First' }],- results: { data: 'data1' },- },- {- id: 'msg-2',- role: 'user',- parts: [{ type: 'text', text: 'Second' }],- },- {- id: 'msg-3',- role: 'assistant',- parts: [{ type: 'text', text: 'Third' }],- },- {- id: 'msg-4',- role: 'assistant',- parts: [{ type: 'text', text: 'Fourth' }],- results: { data: 'data2' },- },- ] as Array<UIMessage & { results?: unknown }>-- const result = prepareMessagesForAPI(messages)-- expect(result).toHaveLength(4)- expect(result[0]).not.toHaveProperty('results')- expect(result[1]).toEqual(messages[1])- expect(result[2]).toEqual(messages[2])- expect(result[3]).not.toHaveProperty('results')- })})diff --git a/apps/studio/lib/ai/tools/incident-tools.test.ts b/apps/studio/lib/ai/tools/incident-tools.test.tsindex 215f1b41cca..5e13064ba38 100644--- a/apps/studio/lib/ai/tools/incident-tools.test.ts+++ b/apps/studio/lib/ai/tools/incident-tools.test.ts@@ -36,38 +36,6 @@ describe('ai/tools/incident-tools', () => {})describe('getIncidentTools', () => {- it('should return an object with get_active_incidents tool', () => {- const tools = getIncidentTools({- baseUrl: 'https://supabase.com/dashboard',- aiOptInLevel: 'schema',- })-- expect(tools).toBeDefined()- expect(tools.get_active_incidents).toBeDefined()- })-- it('should have correct description for get_active_incidents', () => {- const tools = getIncidentTools({- baseUrl: 'https://supabase.com/dashboard',- aiOptInLevel: 'schema',- })-- expect(tools.get_active_incidents.description).toContain('Check for active incidents')- expect(tools.get_active_incidents.description).toContain('Supabase service')- })-- it('should have empty input schema', () => {- const tools = getIncidentTools({- baseUrl: 'https://supabase.com/dashboard',- aiOptInLevel: 'schema',- })- const schema = tools.get_active_incidents.inputSchema-- // The schema is a Zod object that accepts empty object- expect(schema).toBeDefined()- expect((schema as any)._def.typeName).toBe('ZodObject')- })-describe('execute function', () => {it('should return empty incidents when not on platform', async () => {const common = await import('common')diff --git a/apps/studio/lib/ai/tools/mock-tools.test.ts b/apps/studio/lib/ai/tools/mock-tools.test.tsindex 2e0568a5ba5..1977f77337a 100644--- a/apps/studio/lib/ai/tools/mock-tools.test.ts+++ b/apps/studio/lib/ai/tools/mock-tools.test.ts@@ -121,11 +121,14 @@ describe('ai/tools/mock-tools getMockTools', () => {})})- it('overrides create_notebook needsApproval to false, unlike the real tool', async () => {+ it('overrides needsApproval to false for notebook mutations, unlike the real tools', async () => {const mockTools = await getMockTools(undefined)+ const realTools = getNotebookTools({ aiOptInLevel: 'schema' })- expect(getNotebookTools({ aiOptInLevel: 'schema' }).create_notebook.needsApproval).toBe(true)- expect(mockTools.create_notebook.needsApproval).toBe(false)+ for (const name of ['create_notebook', 'update_notebook', 'delete_notebook'] as const) {+ expect(realTools[name].needsApproval).toBe(true)+ expect(mockTools[name].needsApproval).toBe(false)+ }})it('create_notebook stores a new notebook visible via get_notebook and list_notebooks', async () => {@@ -164,13 +167,6 @@ describe('ai/tools/mock-tools getMockTools', () => {expect(newEntry?.cell_count).toBe(2)})- it('overrides update_notebook needsApproval to false, unlike the real tool', async () => {- const mockTools = await getMockTools(undefined)-- expect(getNotebookTools({ aiOptInLevel: 'schema' }).update_notebook.needsApproval).toBe(true)- expect(mockTools.update_notebook.needsApproval).toBe(false)- })-it('update_notebook inserts and deletes cells, and list_notebooks reflects the new cell count', async () => {const mockTools = await getMockTools(undefined)if (!mockTools.get_notebook.execute) throw new Error('execute is undefined')@@ -246,13 +242,6 @@ describe('ai/tools/mock-tools getMockTools', () => {expect(after.cells.map((cell) => cell._tag)).toEqual(['markdown_cell', 'log_cell'])})- it('overrides delete_notebook needsApproval to false, unlike the real tool', async () => {- const mockTools = await getMockTools(undefined)-- expect(getNotebookTools({ aiOptInLevel: 'schema' }).delete_notebook.needsApproval).toBe(true)- expect(mockTools.delete_notebook.needsApproval).toBe(false)- })-it('delete_notebook removes the notebook, and list_notebooks no longer returns it', async () => {const mockTools = await getMockTools(undefined)if (!mockTools.delete_notebook.execute) throw new Error('execute is undefined')diff --git a/apps/studio/lib/ai/tools/notebook-tools.test.ts b/apps/studio/lib/ai/tools/notebook-tools.test.tsindex 717b0fd3257..b9728329720 100644--- a/apps/studio/lib/ai/tools/notebook-tools.test.ts+++ b/apps/studio/lib/ai/tools/notebook-tools.test.ts@@ -86,7 +86,7 @@ const NOTEBOOK_CONTENT = {],}-function mockGetNotebook() {+function mockGetNotebook(content: unknown = NOTEBOOK_CONTENT) {addAPIMock({method: 'get',path: '/platform/projects/:ref/content/item/:id',@@ -103,7 +103,7 @@ function mockGetNotebook() {owner_id: 1,project_id: 1,type: 'notebook',- content: NOTEBOOK_CONTENT,+ content,// The generated response type expects a stricter cell union than this hand-written// fixture provides; the cells themselves are exercised by the schema tests above.} as unknown as GetUserContentByIdResponse),@@ -212,28 +212,6 @@ describe('ai/tools/notebook-tools', () => {})describe('run_notebook', () => {- function mockGetNotebook(content: unknown = NOTEBOOK_CONTENT) {- addAPIMock({- method: 'get',- path: '/platform/projects/:ref/content/item/:id',- response: () =>- HttpResponse.json<GetUserContentByIdResponse>({- id: 'notebook-1',- name: 'Signup funnel',- description: undefined,- visibility: 'project',- favorite: false,- folder_id: null,- inserted_at: '2026-01-01T00:00:00.000Z',- updated_at: '2026-01-01T00:00:00.000Z',- owner_id: 1,- project_id: 1,- type: 'notebook',- content,- } as unknown as GetUserContentByIdResponse),- })- }-it('runs database and log cells in notebook order and skips markdown', async () => {mockGetNotebook()const executionOrder: string[] = []@@ -584,25 +562,7 @@ describe('ai/tools/notebook-tools', () => {describe('get_notebook', () => {it('should resolve markdown text and SQL for every cell', async () => {- addAPIMock({- method: 'get',- path: '/platform/projects/:ref/content/item/:id',- response: () =>- HttpResponse.json<GetUserContentByIdResponse>({- id: 'notebook-1',- name: 'Signup funnel',- description: undefined,- visibility: 'project',- favorite: false,- folder_id: null,- inserted_at: '2026-01-01T00:00:00.000Z',- updated_at: '2026-01-01T00:00:00.000Z',- owner_id: 1,- project_id: 1,- type: 'notebook',- content: NOTEBOOK_CONTENT,- } as unknown as GetUserContentByIdResponse),- })+ mockGetNotebook()const tools = getNotebookTools({ projectRef: 'test-project', aiOptInLevel: 'schema' })if (!tools.get_notebook.execute) throw new Error('execute is undefined')@@ -722,7 +682,7 @@ describe('ai/tools/notebook-tools', () => {expect(result.success).toBe(true)})- it('should PUT a notebook with promoted SQL and no cell ids', async () => {+ it('should PUT a notebook with promoted SQL and no cell ids, returning the id it generated', async () => {let sentBody: Record<string, unknown> | undefinedaddAPIMock({method: 'put',@@ -736,7 +696,7 @@ describe('ai/tools/notebook-tools', () => {const tools = getNotebookTools({ projectRef: 'test-project', aiOptInLevel: 'schema' })if (!tools.create_notebook.execute) throw new Error('execute is undefined')- await tools.create_notebook.execute(+ const result = await tools.create_notebook.execute({ name: 'Signup funnel', content: VALID_AGENT_CONTENT },{ toolCallId: 'test', messages: [], context: {} })@@ -754,87 +714,46 @@ describe('ai/tools/notebook-tools', () => {expect(logCell.sql).toBe("select timestamp, event_message from edge_logs where source = 'edge_logs' limit 10")- })-- it('should return the id it generated and sent, since a successful create response has no body', async () => {- let sentBody: Record<string, unknown> | undefined- addAPIMock({- method: 'put',- path: '/platform/projects/:ref/content',- response: async ({ request }) => {- sentBody = (await request.json()) as Record<string, unknown>- return new HttpResponse(null)- },- })-- const tools = getNotebookTools({ projectRef: 'test-project', aiOptInLevel: 'schema' })- if (!tools.create_notebook.execute) throw new Error('execute is undefined')-- const result = await tools.create_notebook.execute(- { name: 'Signup funnel', content: VALID_AGENT_CONTENT },- { toolCallId: 'test', messages: [], context: {} }- )+ // A successful create response has no body, so the tool returns the id it sentexpect(typeof sentBody?.id).toBe('string')expect(result).toEqual({ id: sentBody?.id, name: 'Signup funnel' })})- it('should throw an assistant-exposable error instead of PUTting when a database_cell carries an unknown database_identifier', async () => {- mockDatabases(['test-project', 'test-project-replica-1'])-- const tools = getNotebookTools({ projectRef: 'test-project', aiOptInLevel: 'schema' })- if (!tools.create_notebook.execute) throw new Error('execute is undefined')-- const execute = tools.create_notebook.execute(- {- name: 'Signup funnel',- content: {- schema_version: 1,- cells: [- {- _tag: 'database_cell',- sql: 'select 1',- row_limit: 100,- database_identifier: 'made-up-replica',- },- ],- },- },- { toolCallId: 'test', messages: [], context: {} }- )-- await expect(execute).rejects.toThrow(/made-up-replica/)- await expect(execute).rejects.toBeInstanceOf(NotebookToolError)- await expect(execute).rejects.toMatchObject({ metadata: { exposeToAssistant: true } })- })-- it('should throw an assistant-exposable error instead of PUTting when a database_cell carries an empty database_identifier', async () => {- mockDatabases(['test-project', 'test-project-replica-1'])+ it.each([+ ['an unknown', 'made-up-replica', /made-up-replica/],+ ['an empty', '', NotebookToolError],+ ])(+ 'should throw an assistant-exposable error instead of PUTting when a database_cell carries %s database_identifier',+ async (_, databaseIdentifier, expectedError) => {+ mockDatabases(['test-project', 'test-project-replica-1'])- const tools = getNotebookTools({ projectRef: 'test-project', aiOptInLevel: 'schema' })- if (!tools.create_notebook.execute) throw new Error('execute is undefined')+ const tools = getNotebookTools({ projectRef: 'test-project', aiOptInLevel: 'schema' })+ if (!tools.create_notebook.execute) throw new Error('execute is undefined')- const execute = tools.create_notebook.execute(- {- name: 'Signup funnel',- content: {- schema_version: 1,- cells: [- {- _tag: 'database_cell',- sql: 'select 1',- row_limit: 100,- database_identifier: '',- },- ],+ const execute = tools.create_notebook.execute(+ {+ name: 'Signup funnel',+ content: {+ schema_version: 1,+ cells: [+ {+ _tag: 'database_cell',+ sql: 'select 1',+ row_limit: 100,+ database_identifier: databaseIdentifier,+ },+ ],+ },},- },- { toolCallId: 'test', messages: [], context: {} }- )+ { toolCallId: 'test', messages: [], context: {} }+ )- await expect(execute).rejects.toBeInstanceOf(NotebookToolError)- await expect(execute).rejects.toMatchObject({ metadata: { exposeToAssistant: true } })- })+ await expect(execute).rejects.toThrow(expectedError)+ await expect(execute).rejects.toBeInstanceOf(NotebookToolError)+ await expect(execute).rejects.toMatchObject({ metadata: { exposeToAssistant: true } })+ }+ )it('should succeed when a database_cell carries a database_identifier that matches a real database', async () => {mockDatabases(['test-project', 'test-project-replica-1'])@@ -996,169 +915,68 @@ describe('ai/tools/notebook-tools', () => {await expect(execute).rejects.toMatchObject({ metadata: { exposeToAssistant: true } })})- it('should throw an assistant-exposable error instead of PUTting when a resulting database_cell carries an unknown database_identifier', async () => {- mockGetNotebook()- mockDatabases(['test-project'])-- const tools = getNotebookTools({ projectRef: 'test-project', aiOptInLevel: 'schema' })- if (!tools.update_notebook.execute) throw new Error('execute is undefined')+ describe.each(['replace_cell', 'insert_cell'] as const)(+ 'when a %s operation introduces a database_cell',+ (operationTag) => {+ const executeWithIdentifier = (databaseIdentifier: string) => {+ const tools = getNotebookTools({ projectRef: 'test-project', aiOptInLevel: 'schema' })+ if (!tools.update_notebook.execute) throw new Error('execute is undefined')- const execute = tools.update_notebook.execute(- {- id: 'notebook-1',- expected_updated_at: '2026-01-01T00:00:00.000Z',- operations: [+ const cell = {+ _tag: 'database_cell' as const,+ sql: 'select * from auth.users limit 100',+ row_limit: 100,+ database_identifier: databaseIdentifier,+ }+ return tools.update_notebook.execute({- _tag: 'replace_cell',- cell_id: 'cell-2',- cell: {- _tag: 'database_cell',- sql: 'select * from auth.users limit 100',- row_limit: 100,- database_identifier: 'made-up-replica',- },+ id: 'notebook-1',+ expected_updated_at: '2026-01-01T00:00:00.000Z',+ operations: [+ operationTag === 'replace_cell'+ ? { _tag: 'replace_cell', cell_id: 'cell-2', cell }+ : { _tag: 'insert_cell', after_cell_id: 'cell-1', cell },+ ],},- ],- },- { toolCallId: 'test', messages: [], context: {} }- )+ { toolCallId: 'test', messages: [], context: {} }+ )+ }- await expect(execute).rejects.toThrow(/made-up-replica/)- await expect(execute).rejects.toBeInstanceOf(NotebookToolError)- await expect(execute).rejects.toMatchObject({ metadata: { exposeToAssistant: true } })- })+ it('should throw an assistant-exposable error instead of PUTting for an unknown database_identifier', async () => {+ mockGetNotebook()+ mockDatabases(['test-project'])- it('should succeed when a resulting database_cell carries a database_identifier that matches a real database', async () => {- mockGetNotebook()- mockDatabases(['test-project', 'test-project-replica-1'])- addAPIMock({- method: 'put',- path: '/platform/projects/:ref/content',- response: () => new HttpResponse(null),- })+ const execute = executeWithIdentifier('made-up-replica')- const tools = getNotebookTools({ projectRef: 'test-project', aiOptInLevel: 'schema' })- if (!tools.update_notebook.execute) throw new Error('execute is undefined')+ await expect(execute).rejects.toThrow(/made-up-replica/)+ await expect(execute).rejects.toBeInstanceOf(NotebookToolError)+ await expect(execute).rejects.toMatchObject({ metadata: { exposeToAssistant: true } })+ })- await expect(- tools.update_notebook.execute(- {- id: 'notebook-1',- expected_updated_at: '2026-01-01T00:00:00.000Z',- operations: [- {- _tag: 'replace_cell',- cell_id: 'cell-2',- cell: {- _tag: 'database_cell',- sql: 'select * from auth.users limit 100',- row_limit: 100,- database_identifier: 'test-project-replica-1',- },- },- ],- },- { toolCallId: 'test', messages: [], context: {} }- )- ).resolves.toMatchObject({ id: 'notebook-1', name: 'Signup funnel' })- })-- it('should throw an assistant-exposable error instead of PUTting when an inserted database_cell carries an unknown database_identifier', async () => {- mockGetNotebook()- mockDatabases(['test-project'])+ it('should succeed for a database_identifier that matches a real database', async () => {+ mockGetNotebook()+ mockDatabases(['test-project', 'test-project-replica-1'])+ mockCreateNotebookPut()- const tools = getNotebookTools({ projectRef: 'test-project', aiOptInLevel: 'schema' })- if (!tools.update_notebook.execute) throw new Error('execute is undefined')-- const execute = tools.update_notebook.execute(- {- id: 'notebook-1',- expected_updated_at: '2026-01-01T00:00:00.000Z',- operations: [- {- _tag: 'insert_cell',- after_cell_id: 'cell-1',- cell: {- _tag: 'database_cell',- sql: 'select * from auth.users limit 100',- row_limit: 100,- database_identifier: 'made-up-replica',- },- },- ],- },- { toolCallId: 'test', messages: [], context: {} }- )-- await expect(execute).rejects.toThrow(/made-up-replica/)- await expect(execute).rejects.toBeInstanceOf(NotebookToolError)- await expect(execute).rejects.toMatchObject({ metadata: { exposeToAssistant: true } })- })-- it('should succeed when an inserted database_cell carries a database_identifier that matches a real database', async () => {- mockGetNotebook()- mockDatabases(['test-project', 'test-project-replica-1'])- addAPIMock({- method: 'put',- path: '/platform/projects/:ref/content',- response: () => new HttpResponse(null),- })-- const tools = getNotebookTools({ projectRef: 'test-project', aiOptInLevel: 'schema' })- if (!tools.update_notebook.execute) throw new Error('execute is undefined')-- await expect(- tools.update_notebook.execute(- {+ await expect(executeWithIdentifier('test-project-replica-1')).resolves.toMatchObject({id: 'notebook-1',- expected_updated_at: '2026-01-01T00:00:00.000Z',- operations: [- {- _tag: 'insert_cell',- after_cell_id: 'cell-1',- cell: {- _tag: 'database_cell',- sql: 'select * from auth.users limit 100',- row_limit: 100,- database_identifier: 'test-project-replica-1',- },- },- ],- },- { toolCallId: 'test', messages: [], context: {} }- )- ).resolves.toMatchObject({ id: 'notebook-1', name: 'Signup funnel' })- })+ name: 'Signup funnel',+ })+ })+ }+ )it('should succeed without validating or fetching databases when no operation introduces a database_cell', async () => {// cell-2 already carries an identifier that wouldn't validate today (e.g. its// replica was since removed) — but this update never touches it, so it must not// be re-checked, and the databases endpoint must not be called at all.- addAPIMock({- method: 'get',- path: '/platform/projects/:ref/content/item/:id',- response: () =>- HttpResponse.json<GetUserContentByIdResponse>({- id: 'notebook-1',- name: 'Signup funnel',- description: undefined,- visibility: 'project',- favorite: false,- folder_id: null,- inserted_at: '2026-01-01T00:00:00.000Z',- updated_at: '2026-01-01T00:00:00.000Z',- owner_id: 1,- project_id: 1,- type: 'notebook',- content: {- ...NOTEBOOK_CONTENT,- cells: NOTEBOOK_CONTENT.cells.map((cell) =>- cell._tag === 'database_cell'- ? { ...cell, database_identifier: 'stale-replica-removed-long-ago' }- : cell- ),- },- }),+ mockGetNotebook({+ ...NOTEBOOK_CONTENT,+ cells: NOTEBOOK_CONTENT.cells.map((cell) =>+ cell._tag === 'database_cell'+ ? { ...cell, database_identifier: 'stale-replica-removed-long-ago' }+ : cell+ ),})addAPIMock({method: 'put',diff --git a/apps/studio/lib/ai/tools/registry.test.ts b/apps/studio/lib/ai/tools/registry.test.tsindex 39f81e3ac9e..d6129ea8044 100644--- a/apps/studio/lib/ai/tools/registry.test.ts+++ b/apps/studio/lib/ai/tools/registry.test.ts@@ -210,7 +210,9 @@ describe('read-only contracts', () => {output,} as ToolUIPart- it.each(levels)('shows the output unchanged on replay at %s', (level) => {+ it.each(levels)('shows the output unchanged, live and on replay, at %s', (level) => {+ const contract: ToolContract = TOOL_CONTRACTS[name as keyof typeof outputs]+ expect(contract.toModelOutput(output, level)).toEqual(output)expect(sanitizeContractPart(part, level)?.output).toEqual(output)})@@ -219,11 +221,6 @@ describe('read-only contracts', () => {undefined)})-- it.each(levels)('shows the live output unchanged at %s', (level) => {- const contract: ToolContract = TOOL_CONTRACTS[name as keyof typeof outputs]- expect(contract.toModelOutput(output, level)).toEqual(output)- })})it.each(['escalate_to_human', 'resolve_support_conversation'] as const)(diff --git a/apps/studio/lib/ai/tools/studio-tools.test.ts b/apps/studio/lib/ai/tools/studio-tools.test.tsindex 5a0954f93d5..d925d6017cf 100644--- a/apps/studio/lib/ai/tools/studio-tools.test.ts+++ b/apps/studio/lib/ai/tools/studio-tools.test.ts@@ -15,56 +15,26 @@ describe('ai/tools/studio-tools', () => {})describe('getStudioTools', () => {- it('should return an object with tool definitions', () => {+ it('should expose exactly the studio tools', () => {const tools = getStudioTools({ aiOptInLevel: 'schema' })- expect(tools).toBeDefined()- expect(typeof tools).toBe('object')- })-- it('should include execute_sql tool', () => {- const tools = getStudioTools({ aiOptInLevel: 'schema' })-- expect(tools.execute_sql).toBeDefined()- expect(tools.execute_sql.description).toContain('execute a SQL statement')- })-- it('should include deploy_edge_function tool', () => {- const tools = getStudioTools({ aiOptInLevel: 'schema' })-- expect(tools.deploy_edge_function).toBeDefined()- expect(tools.deploy_edge_function.description).toContain('deploy a Supabase Edge Function')- })-- it('should include rename_chat tool', () => {- const tools = getStudioTools({ aiOptInLevel: 'schema' })-- expect(tools.rename_chat).toBeDefined()- expect(tools.rename_chat.description).toContain('Rename the current chat session')- })-- it('should have exactly 4 tools', () => {- const tools = getStudioTools({ aiOptInLevel: 'schema' })- const toolNames = Object.keys(tools)-- expect(toolNames).toHaveLength(4)- expect(toolNames).toContain('load_knowledge')- expect(toolNames).toContain('execute_sql')- expect(toolNames).toContain('deploy_edge_function')- expect(toolNames).toContain('rename_chat')+ expect(Object.keys(tools).sort()).toEqual([+ 'deploy_edge_function',+ 'execute_sql',+ 'load_knowledge',+ 'rename_chat',+ ])})it('should include logs in the load_knowledge schema', () => {const tools = getStudioTools({ aiOptInLevel: 'schema' })const schema = tools.load_knowledge.inputSchema- if ('safeParse' in schema) {- expect(schema.safeParse({ name: 'logs' }).success).toBe(true)- expect(schema.safeParse({ name: 'pg_best_practices' }).success).toBe(true)- expect(schema.safeParse({ name: 'not_a_topic' }).success).toBe(false)- } else {- expect(schema).toBeDefined()- }+ if (!('safeParse' in schema)) throw new Error('inputSchema has no safeParse')++ expect(schema.safeParse({ name: 'logs' }).success).toBe(true)+ expect(schema.safeParse({ name: 'pg_best_practices' }).success).toBe(true)+ expect(schema.safeParse({ name: 'not_a_topic' }).success).toBe(false)})it('should return ClickHouse logs knowledge for load_knowledge logs', async () => {@@ -82,38 +52,10 @@ describe('ai/tools/studio-tools', () => {expect(result).toContain('interactive query cell')})- it('should have execute_sql with correct input schema fields', () => {- const tools = getStudioTools({ aiOptInLevel: 'schema' })- const executeSqlTool = tools.execute_sql-- // Check that the tool has an input schema- expect(executeSqlTool.inputSchema).toBeDefined()-- // Verify the schema exists and is a Zod object- const schema = executeSqlTool.inputSchema- expect(schema).toBeDefined()- expect((schema as any)._def.typeName).toBe('ZodObject')- })-- it('should have deploy_edge_function with input schema', () => {- const tools = getStudioTools({ aiOptInLevel: 'schema' })- const deployTool = tools.deploy_edge_function-- expect(deployTool.inputSchema).toBeDefined()-- // Verify the schema exists and is a Zod object- expect(deployTool.inputSchema).toBeDefined()- expect((deployTool.inputSchema as any)._def.typeName).toBe('ZodObject')- })-- it('should have rename_chat with execute function', async () => {+ it('should have rename_chat hand the rename off to the client', async () => {const tools = getStudioTools({ aiOptInLevel: 'schema' })const renameTool = tools.rename_chat- expect(renameTool.execute).toBeDefined()- expect(typeof renameTool.execute).toBe('function')-- // Test the execute functionif (!renameTool.execute) throw new Error('execute is undefined')const result = await renameTool.execute({ newName: 'Test Chat' },@@ -126,36 +68,32 @@ describe('ai/tools/studio-tools', () => {const tools = getStudioTools({ aiOptInLevel: 'schema' })const schema = tools.execute_sql.inputSchema- // Check if schema is a Zod schema with safeParse- if ('safeParse' in schema) {- // Valid input- const validInput = {- sql: safeSql`SELECT * FROM users`,- label: 'Get users',- chartConfig: { view: 'table' as const },- isWriteQuery: false,- }- expect(schema.safeParse(validInput).success).toBe(true)-- // Valid chart config- const validChartInput = {- sql: safeSql`SELECT count(*) FROM users`,- label: 'User count',- chartConfig: { view: 'chart' as const, xAxis: 'date', yAxis: 'count' },- isWriteQuery: false,- }- expect(schema.safeParse(validChartInput).success).toBe(true)-- // Missing required field- const invalidInput = {- sql: safeSql`SELECT * FROM users`,- // missing label, chartConfig, isWriteQuery- }- expect(schema.safeParse(invalidInput).success).toBe(false)- } else {- // Skip test if schema doesn't have safeParse- expect(schema).toBeDefined()+ if (!('safeParse' in schema)) throw new Error('inputSchema has no safeParse')++ // Valid input+ const validInput = {+ sql: safeSql`SELECT * FROM users`,+ label: 'Get users',+ chartConfig: { view: 'table' as const },+ isWriteQuery: false,}+ expect(schema.safeParse(validInput).success).toBe(true)++ // Valid chart config+ const validChartInput = {+ sql: safeSql`SELECT count(*) FROM users`,+ label: 'User count',+ chartConfig: { view: 'chart' as const, xAxis: 'date', yAxis: 'count' },+ isWriteQuery: false,+ }+ expect(schema.safeParse(validChartInput).success).toBe(true)++ // Missing required field+ const invalidInput = {+ sql: safeSql`SELECT * FROM users`,+ // missing label, chartConfig, isWriteQuery+ }+ expect(schema.safeParse(invalidInput).success).toBe(false)})it('should require approval for read and write SQL queries', () => {@@ -325,26 +263,6 @@ describe('ai/tools/studio-tools', () => {value: { rows: rows.slice(0, 100), note: 'Only the first 100 of 150 rows are included.' },})})-- it('should validate rename_chat input schema correctly', () => {- const tools = getStudioTools({ aiOptInLevel: 'schema' })- const schema = tools.rename_chat.inputSchema-- // Check if schema is a Zod schema with safeParse- if ('safeParse' in schema) {- // Valid input- expect(schema.safeParse({ newName: 'My Chat' }).success).toBe(true)-- // Invalid input - missing newName- expect(schema.safeParse({}).success).toBe(false)-- // Invalid input - wrong type- expect(schema.safeParse({ newName: 123 }).success).toBe(false)- } else {- // Skip test if schema doesn't have safeParse- expect(schema).toBeDefined()- }- })})})diff --git a/apps/studio/lib/ai/tools/tool-sanitizer.test.ts b/apps/studio/lib/ai/tools/tool-sanitizer.test.tsindex 396f71b92bf..2f1c52e20ea 100644--- a/apps/studio/lib/ai/tools/tool-sanitizer.test.ts+++ b/apps/studio/lib/ai/tools/tool-sanitizer.test.ts@@ -13,6 +13,7 @@ import {import { NO_DATA_PERMISSIONS } from './execute-sql-output'import { INVALID_NOTEBOOK_RUN_OUTPUT_MESSAGE, type NotebookRunOutput } from './notebook-run-output'import { sanitizeMessagePart } from './tool-sanitizer'+import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'const notebookRunPart = {type: 'tool-run_notebook',@@ -89,108 +90,32 @@ describe('messages are sanitized based on opt-in level', () => {)})- test('messages are sanitized at disabled level', () => {+ // Prepares messages as the frontend would, then sanitizes them as the API endpoint would+ const sanitizeExecuteSqlConversation = (level: AiOptInLevel) => {const messages = [createAssistantMessageWithExecuteSqlTool('SELECT email FROM users', [{ email: '[email protected]' },]),]-- // Prepare messages as frontend would- const preparedMessages = prepareMessagesForAPI(messages)-- // Sanitize messages as API endpoint would- const processedMessages = preparedMessages.map((msg) => {- if (msg.role === 'assistant' && msg.parts) {- const processedParts = msg.parts.map((part) => {- return sanitizeMessagePart(part, 'disabled')- })-- return { ...msg, parts: processedParts }- }- return msg- })-- const output = (processedMessages[0].parts[1] as ToolUIPart).output- expect(output).toMatch(NO_DATA_PERMISSIONS)- })-- test('messages are sanitized at schema level', () => {- const messages = [- createAssistantMessageWithExecuteSqlTool('SELECT email FROM users', [- { email: '[email protected]' },- ]),- ]-- // Prepare messages as frontend would- const preparedMessages = prepareMessagesForAPI(messages)-- // Sanitize messages as API endpoint would- const processedMessages = preparedMessages.map((msg) => {- if (msg.role === 'assistant' && msg.parts) {- const processedParts = msg.parts.map((part) => {- return sanitizeMessagePart(part, 'schema')- })-- return { ...msg, parts: processedParts }- }- return msg- })-- const output = (processedMessages[0].parts[1] as ToolUIPart).output- expect(output).toMatch(NO_DATA_PERMISSIONS)- })-- test('messages are sanitized at schema and log level', () => {- const messages = [- createAssistantMessageWithExecuteSqlTool('SELECT email FROM users', [- { email: '[email protected]' },- ]),- ]-- // Prepare messages as frontend would- const preparedMessages = prepareMessagesForAPI(messages)-- // Sanitize messages as API endpoint would- const processedMessages = preparedMessages.map((msg) => {- if (msg.role === 'assistant' && msg.parts) {- const processedParts = msg.parts.map((part) => {- return sanitizeMessagePart(part, 'schema_and_log')- })-- return { ...msg, parts: processedParts }- }- return msg- })-- const output = (processedMessages[0].parts[1] as ToolUIPart).output- expect(output).toMatch(NO_DATA_PERMISSIONS)- })-- test('messages are not sanitized at data level', () => {- const messages = [- createAssistantMessageWithExecuteSqlTool('SELECT email FROM users', [- { email: '[email protected]' },- ]),- ]-- // Prepare messages as frontend would- const preparedMessages = prepareMessagesForAPI(messages)-- // Sanitize messages as API endpoint would- const processedMessages = preparedMessages.map((msg) => {- if (msg.role === 'assistant' && msg.parts) {- const processedParts = msg.parts.map((part) => {- return sanitizeMessagePart(part, 'schema_and_log_and_data')- })-- return { ...msg, parts: processedParts }- }- return msg- })-- const output = (processedMessages[0].parts[1] as ToolUIPart).output- expect(output).toEqual([{ email: '[email protected]' }])+ const processedMessages = prepareMessagesForAPI(messages).map((msg) =>+ msg.role === 'assistant' && msg.parts+ ? { ...msg, parts: msg.parts.map((part) => sanitizeMessagePart(part, level)) }+ : msg+ )+ return (processedMessages[0].parts[1] as ToolUIPart).output+ }++ test.each(['disabled', 'schema', 'schema_and_log'] as const)(+ 'execute_sql rows are hidden at %s level',+ (level) => {+ expect(sanitizeExecuteSqlConversation(level)).toMatch(NO_DATA_PERMISSIONS)+ }+ )++ test('execute_sql rows are not sanitized at data level', () => {+ expect(sanitizeExecuteSqlConversation('schema_and_log_and_data')).toEqual([+ { email: '[email protected]' },+ ])})test('multiple tool parts in message are sanitized', () => {diff --git a/apps/studio/lib/api/filterHelpers.test.ts b/apps/studio/lib/api/filterHelpers.test.tsindex 0272c3692fb..eb0f47f5ae6 100644--- a/apps/studio/lib/api/filterHelpers.test.ts+++ b/apps/studio/lib/api/filterHelpers.test.ts@@ -28,41 +28,11 @@ describe('isFilterGroup', () => {})describe('serializeOptions', () => {- test('returns undefined for undefined input', () => {- expect(serializeOptions(undefined)).toBeUndefined()+ test.each([undefined, null, []])('returns undefined for %o', (input) => {+ expect(serializeOptions(input as Parameters<typeof serializeOptions>[0])).toBeUndefined()})- test('returns undefined for non-array input', () => {- expect(serializeOptions(null as any)).toBeUndefined()- })-- test('returns undefined for empty array', () => {- expect(serializeOptions([])).toBeUndefined()- })-- test('handles string options', () => {- expect(serializeOptions(['option1', 'option2'])).toEqual(['option1', 'option2'])- })-- test('extracts label from object options', () => {- expect(serializeOptions([{ label: 'Label 1' }, { label: 'Label 2' }])).toEqual([- 'Label 1',- 'Label 2',- ])- })-- test('falls back to value when label is not present', () => {- expect(serializeOptions([{ value: 'value1' }, { value: 'value2' }])).toEqual([- 'value1',- 'value2',- ])- })-- test('prefers label over value', () => {- expect(serializeOptions([{ label: 'Label', value: 'value' }])).toEqual(['Label'])- })-- test('handles mixed option types', () => {+ test('serializes strings as-is and objects by label, falling back to value', () => {expect(serializeOptions(['string',@@ -79,48 +49,19 @@ describe('serializeOptions', () => {})describe('serializeOperators', () => {- test('returns default ["="] for undefined input', () => {- expect(serializeOperators(undefined)).toEqual(['='])+ test.each([undefined, null, []])('returns default ["="] for %o', (input) => {+ expect(serializeOperators(input as Parameters<typeof serializeOperators>[0])).toEqual(['='])})- test('returns default ["="] for empty array', () => {- expect(serializeOperators([])).toEqual(['='])- })-- test('returns default ["="] for non-array input', () => {- expect(serializeOperators(null as any)).toEqual(['='])- })-- test('handles string operators', () => {- expect(serializeOperators(['=', '>', '<'])).toEqual(['=', '>', '<'])- })-- test('extracts value from object operators', () => {+ test('serializes strings as-is and objects by value, falling back to label', () => {expect(serializeOperators([- { value: '=', label: 'equals' },- { value: '>', label: 'greater than' },+ '=',+ { value: '>' },+ { label: 'less than' },+ { value: '!=', label: 'ne' },])- ).toEqual(['=', '>'])- })-- test('falls back to label when value is not present', () => {- expect(serializeOperators([{ label: 'equals' }, { label: 'greater than' }])).toEqual([- 'equals',- 'greater than',- ])- })-- test('prefers value over label', () => {- expect(serializeOperators([{ value: '=', label: 'equals' }])).toEqual(['='])- })-- test('handles mixed operator types', () => {- expect(serializeOperators(['=', { value: '>' }, { label: 'less than' }])).toEqual([- '=',- '>',- 'less than',- ])+ ).toEqual(['=', '>', 'less than', '!='])})test('returns default if all operators are invalid', () => {diff --git a/apps/studio/lib/api/snippets.utils.test.ts b/apps/studio/lib/api/snippets.utils.test.tsindex c2c5a2da6ad..f4de48f3241 100644--- a/apps/studio/lib/api/snippets.utils.test.ts+++ b/apps/studio/lib/api/snippets.utils.test.ts@@ -32,185 +32,135 @@ vi.mock('fs/promises', () => ({}))const mockedFS = vi.mocked(fs)-// Mock SNIPPETS_DIR from constantsvi.mock('./snippets.constants', () => ({SNIPPETS_DIR: '/mock/snippets/dir',}))-describe('snippets.utils', () => {- const MOCK_SNIPPETS_DIR = '/mock/snippets/dir'+const MOCK_SNIPPETS_DIR = '/mock/snippets/dir'+const DEFAULT_BIRTHTIME = new Date('2023-01-01')++const file = (name: string) => ({ name, isDirectory: () => false, isFile: () => true })+const dir = (name: string) => ({ name, isDirectory: () => true, isFile: () => false })+type Dirent = ReturnType<typeof file>++/**+ * Mocks an existing snippets directory. `root` lists entries at the top level, `folders` maps+ * folder names to their entries. File contents default to `content` unless `contents` has an+ * entry for the file name.+ */+function mockTree({+ root,+ folders = {},+ content = 'SELECT 1;',+ contents = {},+}: {+ root: Dirent[]+ folders?: Record<string, Dirent[]>+ content?: string+ contents?: Record<string, string>+}) {+ mockedFS.access.mockResolvedValue(undefined)+ mockedFS.readdir.mockImplementation(((dirPath: string) => {+ if (dirPath === MOCK_SNIPPETS_DIR) return Promise.resolve(root)+ const folderName = path.relative(MOCK_SNIPPETS_DIR, dirPath)+ return Promise.resolve(folders[folderName] ?? [])+ }) as never)+ mockedFS.readFile.mockImplementation(((filePath: string) =>+ Promise.resolve(contents[path.basename(filePath)] ?? content)) as never)+ mockedFS.stat.mockResolvedValue({ birthtime: DEFAULT_BIRTHTIME } as never)+}++const makeSnippet = (overrides: Partial<Snippet>): Snippet => ({+ id: 'test-id',+ inserted_at: '2023-01-01T00:00:00.000Z',+ updated_at: '2023-01-01T00:00:00.000Z',+ type: 'sql',+ name: 'test-snippet',+ description: '',+ favorite: false,+ content: { sql: 'SELECT * FROM test;', content_id: 'content-id', schema_version: '1.0' },+ visibility: 'user',+ project_id: 1,+ folder_id: null,+ owner_id: 1,+ owner: { id: 1, username: 'testuser' },+ updated_by: { id: 1, username: 'testuser' },+ ...overrides,+})++const errnoError = (message: string, code: string) =>+ Object.assign(new Error(message), { code }) satisfies NodeJS.ErrnoException++const UNSAFE_NAMES = [+ ['../ traversal', '../malicious'],+ ['nested directories', 'foo/bar/malicious'],+ ['null bytes', 'malicious\0name'],+ ['absolute path', '/etc/passwd'],+]+describe('snippets.utils', () => {afterEach(() => {vi.resetAllMocks()})describe('getFilesystemEntries', () => {it('should create the snippets directory if it does not exist', async () => {- const accessError = new Error('Directory not found')- mockedFS.access.mockRejectedValue(accessError)+ mockedFS.access.mockRejectedValue(new Error('Directory not found'))mockedFS.mkdir.mockResolvedValue(undefined)mockedFS.readdir.mockResolvedValue([])await getFilesystemEntries()- expect(mockedFS.access).toHaveBeenCalledWith(MOCK_SNIPPETS_DIR)expect(mockedFS.mkdir).toHaveBeenCalledWith(MOCK_SNIPPETS_DIR, { recursive: true })})- it('should read and parse SQL files from the snippets directory', async () => {- const files = [- {- name: 'snippet1.sql',- isDirectory: () => false,- isFile: () => true,- },- {- name: 'snippet2.sql',- isDirectory: () => false,- isFile: () => true,+ it('should read SQL files from the root and from folders, ignoring non-SQL files', async () => {+ mockTree({+ root: [file('root-snippet.sql'), dir('folder1'), file('not-sql.txt')],+ folders: { folder1: [file('folder1-snippet.sql')] },+ contents: {+ 'root-snippet.sql': 'SELECT * FROM root;',+ 'folder1-snippet.sql': 'SELECT * FROM folder1_table;',},- {- name: 'not-sql.txt',- isDirectory: () => false,- isFile: () => true,- },- ]-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue(files as any)- mockedFS.readFile- .mockResolvedValueOnce('SELECT * FROM users;')- .mockResolvedValueOnce('SELECT * FROM posts;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const entries = await getFilesystemEntries()-- expect(entries).toHaveLength(2)- expect(entries[0].name).toBe('snippet1')- expect(entries[0].content).toBe('SELECT * FROM users;')- expect(entries[0].type).toBe('file')- expect(entries[1].name).toBe('snippet2')- expect(entries[1].content).toBe('SELECT * FROM posts;')- expect(entries[1].type).toBe('file')- expect(mockedFS.readFile).toHaveBeenCalledTimes(2)- })-- it('should return empty array when no SQL files exist', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'not-sql.txt', isDirectory: () => false, isFile: () => true },- ] as any)-- const entries = await getFilesystemEntries()-- expect(entries).toEqual([])- })-- it('should read SQL files from subdirectories (folders)', async () => {- // Mock fs.Dirent objects for different file types- const createMockDirent = (name: string, isDirectory: boolean) => ({- name,- isDirectory: () => isDirectory,- isFile: () => !isDirectory,- })-- // Mock the main directory structure- const mainDirItems = [- createMockDirent('root-snippet.sql', false),- createMockDirent('folder1', true),- createMockDirent('not-sql.txt', false),- ]-- // Mock folder1 contents- const folder1Items = [createMockDirent('folder1-snippet.sql', false)]-- mockedFS.access.mockResolvedValue(undefined)-- // Mock readdir to return different results based on the path- mockedFS.readdir.mockImplementation((dirPath: any) => {- if (dirPath === MOCK_SNIPPETS_DIR) {- return Promise.resolve(mainDirItems as any)- } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'folder1')) {- return Promise.resolve(folder1Items as any)- }- return Promise.resolve([])})- // Mock readFile to return different content based on the file- mockedFS.readFile.mockImplementation((filePath: any) => {- const fileName = path.basename(filePath as string)- switch (fileName) {- case 'root-snippet.sql':- return Promise.resolve('SELECT * FROM root;')- case 'folder1-snippet.sql':- return Promise.resolve('SELECT * FROM folder1_table;')- default:- return Promise.reject(new Error('File not found'))- }- })- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-const entries = await getFilesystemEntries()- // Should find 1 folder and 2 SQL filesexpect(entries).toHaveLength(3)-- const folders = entries.filter((e) => e.type === 'folder')- const files = entries.filter((e) => e.type === 'file')-- expect(folders).toHaveLength(1)- expect(folders[0].name).toBe('folder1')- expect(folders[0].folderId).toBe(null) // Folders are always at root level-- expect(files).toHaveLength(2)- const rootFile = files.find((f) => f.name === 'root-snippet')- const folderFile = files.find((f) => f.name === 'folder1-snippet')-- expect(rootFile?.folderId).toBe(null)- expect(folderFile?.folderId).toBe(generateDeterministicUuid(['folder1']))+ expect(entries).toContainEqual(+ expect.objectContaining({ type: 'folder', name: 'folder1', folderId: null })+ )+ expect(entries).toContainEqual(+ expect.objectContaining({+ type: 'file',+ name: 'root-snippet',+ content: 'SELECT * FROM root;',+ folderId: null,+ })+ )+ expect(entries).toContainEqual(+ expect.objectContaining({+ type: 'file',+ name: 'folder1-snippet',+ content: 'SELECT * FROM folder1_table;',+ folderId: generateDeterministicUuid(['folder1']),+ })+ )})it('should skip subdirectories inside folders (not supported)', async () => {- const createMockDirent = (name: string, isDirectory: boolean) => ({- name,- isDirectory: () => isDirectory,- isFile: () => !isDirectory,+ mockTree({+ root: [dir('folder1')],+ folders: { folder1: [file('snippet.sql'), dir('subfolder')] },})- const mainDirItems = [createMockDirent('folder1', true)]- const folder1Items = [- createMockDirent('snippet.sql', false),- createMockDirent('subfolder', true), // This should be skipped- ]-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockImplementation((dirPath: any) => {- if (dirPath === MOCK_SNIPPETS_DIR) {- return Promise.resolve(mainDirItems as any)- } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'folder1')) {- return Promise.resolve(folder1Items as any)- }- return Promise.resolve([])- })-- mockedFS.readFile.mockResolvedValue('SELECT * FROM table;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-const entries = await getFilesystemEntries()- // Should only find 1 folder and 1 file (subfolder should be skipped)- expect(entries).toHaveLength(2)- expect(entries.filter((e) => e.type === 'folder')).toHaveLength(1)- expect(entries.filter((e) => e.type === 'file')).toHaveLength(1)+ expect(entries.map((e) => e.type).sort()).toEqual(['file', 'folder'])})it('should handle empty SQL files', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'empty.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ mockTree({ root: [file('empty.sql')], content: '' })const entries = await getFilesystemEntries()@@ -218,17 +168,14 @@ describe('snippets.utils', () => {expect(entries[0].content).toBe('')})- it('should handle file read errors gracefully', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'error.sql', isDirectory: () => false, isFile: () => true },- ] as any)+ it('should propagate file read errors', async () => {+ mockTree({ root: [file('error.sql')] })mockedFS.readFile.mockRejectedValue(new Error('Permission denied'))await expect(getFilesystemEntries()).rejects.toThrow('Permission denied')})- it('should handle mkdir failure', async () => {+ it('should propagate mkdir failure', async () => {mockedFS.access.mockRejectedValue(new Error('Directory not found'))mockedFS.mkdir.mockRejectedValue(new Error('Permission denied'))@@ -236,18 +183,12 @@ describe('snippets.utils', () => {})it('should skip reading file content when includeContent is false', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },- { name: 'snippet2.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ mockTree({ root: [file('snippet1.sql'), file('snippet2.sql')] })const entries = await getFilesystemEntries({ includeContent: false })- const files = entries.filter((e) => e.type === 'file')- expect(files).toHaveLength(2)- expect(files.every((f) => f.content === undefined)).toBe(true)+ expect(entries).toHaveLength(2)+ expect(entries.every((f) => f.content === undefined)).toBe(true)// Listings should never touch file contents off disk.expect(mockedFS.readFile).not.toHaveBeenCalled()})@@ -255,60 +196,36 @@ describe('snippets.utils', () => {describe('getSnippet', () => {it('should get a specific snippet by id', async () => {- const snippetName = 'test-snippet'- const snippetId = generateDeterministicUuid([`${snippetName}.sql`])-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'test-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT * FROM test;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const snippet = await getSnippet(snippetId)-- // The snippet ID is generated from the full filename in buildSnippet- expect(snippet.id).toBe(generateDeterministicUuid([`${snippetName}.sql`]))- expect(snippet.name).toBe(snippetName)- expect(snippet.content.sql).toBe('SELECT * FROM test;')- expect(snippet.folder_id).toBe(null)- })+ mockTree({ root: [file('test-snippet.sql')], content: 'SELECT * FROM test;' })- it('should get a snippet from a folder', async () => {- const folderName = 'my-folder'- const folderId = generateDeterministicUuid([folderName])- const snippetName = 'folder-snippet'- const snippetId = generateDeterministicUuid([folderId, `${snippetName}.sql`])-- const createMockDirent = (name: string, isDirectory: boolean) => ({- name,- isDirectory: () => isDirectory,- isFile: () => !isDirectory,+ const snippet = await getSnippet(generateDeterministicUuid(['test-snippet.sql']))++ expect(snippet).toMatchObject({+ name: 'test-snippet',+ content: { sql: 'SELECT * FROM test;' },+ folder_id: null,})+ })- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockImplementation((dirPath: any) => {- if (dirPath === MOCK_SNIPPETS_DIR) {- return Promise.resolve([createMockDirent(folderName, true)] as any)- } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, folderName)) {- return Promise.resolve([createMockDirent(`${snippetName}.sql`, false)] as any)- }- return Promise.resolve([])+ it('should get a snippet from a folder', async () => {+ const folderId = generateDeterministicUuid(['my-folder'])+ mockTree({+ root: [dir('my-folder')],+ folders: { 'my-folder': [file('folder-snippet.sql')] },+ content: 'SELECT * FROM folder_table;',})- mockedFS.readFile.mockResolvedValue('SELECT * FROM folder_table;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)- const snippet = await getSnippet(snippetId)+ const snippet = await getSnippet(generateDeterministicUuid([folderId, 'folder-snippet.sql']))- expect(snippet.id).toBe(generateDeterministicUuid([folderId, `${snippetName}.sql`]))- expect(snippet.name).toBe(snippetName)- expect(snippet.content.sql).toBe('SELECT * FROM folder_table;')- expect(snippet.folder_id).toBe(generateDeterministicUuid(['my-folder']))+ expect(snippet).toMatchObject({+ name: 'folder-snippet',+ content: { sql: 'SELECT * FROM folder_table;' },+ folder_id: folderId,+ })})it('should throw error when snippet not found', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])+ mockTree({ root: [] })await expect(getSnippet('non-existent-id')).rejects.toThrow('Snippet with id non-existent-id not found'@@ -317,272 +234,126 @@ describe('snippets.utils', () => {})describe('getSnippets', () => {- it('should get all snippets from root folder', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },- { name: 'snippet2.sql', isDirectory: () => false, isFile: () => true },- { name: 'folder1', isDirectory: () => true, isFile: () => false },- ] as any)- mockedFS.readFile- .mockResolvedValueOnce('SELECT * FROM table1;')- .mockResolvedValueOnce('SELECT * FROM table2;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ it('should get only root snippets when folderId is null', async () => {+ mockTree({+ root: [file('snippet1.sql'), file('snippet2.sql'), dir('folder1')],+ folders: { folder1: [file('nested.sql')] },+ })const result = await getSnippets({ folderId: null, sort: 'name', sortOrder: 'asc' })- expect(result.snippets).toHaveLength(2)- expect(result.snippets[0].name).toBe('snippet1')- expect(result.snippets[1].name).toBe('snippet2')- expect(result.snippets[0].folder_id).toBe(null)- expect(result.snippets[1].folder_id).toBe(null)+ expect(result.snippets.map((s) => s.name)).toEqual(['snippet1', 'snippet2'])+ expect(result.snippets.every((s) => s.folder_id === null)).toBe(true)expect(result.cursor).toBeUndefined()})it('should get snippets from a specific folder', async () => {const folderId = generateDeterministicUuid(['my-folder'])-- const createMockDirent = (name: string, isDirectory: boolean) => ({- name,- isDirectory: () => isDirectory,- isFile: () => !isDirectory,- })-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockImplementation((dirPath: any) => {- if (dirPath === MOCK_SNIPPETS_DIR) {- return Promise.resolve([createMockDirent('my-folder', true)] as any)- } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'my-folder')) {- return Promise.resolve([createMockDirent('folder-snippet.sql', false)] as any)- }- return Promise.resolve([])+ mockTree({+ root: [file('root-snippet.sql'), dir('my-folder')],+ folders: { 'my-folder': [file('folder-snippet.sql')] },})- mockedFS.readFile.mockResolvedValue('SELECT * FROM folder_table;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)const result = await getSnippets({ folderId })expect(result.snippets).toHaveLength(1)- expect(result.snippets[0].name).toBe('folder-snippet')- expect(result.snippets[0].folder_id).toBe(folderId)+ expect(result.snippets[0]).toMatchObject({ name: 'folder-snippet', folder_id: folderId })})it('should return empty result when no snippets in folder', async () => {- const folderId = generateDeterministicUuid(['empty-folder'])+ mockTree({ root: [] })- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])-- const result = await getSnippets({ folderId })+ const result = await getSnippets({ folderId: generateDeterministicUuid(['empty-folder']) })expect(result.snippets).toEqual([])expect(result.cursor).toBeUndefined()})- it('should filter snippets by search term across all folders', async () => {- const createMockDirent = (name: string, isDirectory: boolean) => ({- name,- isDirectory: () => isDirectory,- isFile: () => !isDirectory,+ it('should filter by search term case-insensitively across all folders', async () => {+ mockTree({+ root: [+ file('USER-query.sql'),+ file('admin-report.sql'),+ file('Test-User-Data.sql'),+ dir('my-folder'),+ ],+ folders: { 'my-folder': [file('user-permissions.sql')] },})- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockImplementation((dirPath: any) => {- if (dirPath === MOCK_SNIPPETS_DIR) {- return Promise.resolve([- createMockDirent('user-query.sql', false),- createMockDirent('admin-report.sql', false),- createMockDirent('test-user-data.sql', false),- createMockDirent('my-folder', true),- ] as any)- } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'my-folder')) {- return Promise.resolve([createMockDirent('user-permissions.sql', false)] as any)- }- return Promise.resolve([])- })- mockedFS.readFile.mockImplementation((filePath: any) => {- const fileName = path.basename(filePath as string)- return Promise.resolve(`SELECT * FROM ${fileName.replace('.sql', '')};`)- })- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-const result = await getSnippets({ searchTerm: 'user', sort: 'name', sortOrder: 'asc' })- expect(result.snippets).toHaveLength(3)expect(result.snippets.map((s) => s.name)).toEqual([- 'test-user-data',+ 'Test-User-Data','user-permissions',- 'user-query',+ 'USER-query',])})- it('should sort snippets by name in ascending order', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'zebra.sql', isDirectory: () => false, isFile: () => true },- { name: 'apple.sql', isDirectory: () => false, isFile: () => true },- { name: 'banana.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT 1;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ it('should ignore a whitespace-only search term and filter by folderId', async () => {+ const folderId = generateDeterministicUuid(['my-folder'])+ mockTree({+ root: [file('root-snippet.sql'), dir('my-folder')],+ folders: { 'my-folder': [file('folder-snippet.sql')] },+ })- const result = await getSnippets({ sort: 'name', sortOrder: 'asc' })+ const result = await getSnippets({ searchTerm: ' ', folderId })- expect(result.snippets.map((s) => s.name)).toEqual(['apple', 'banana', 'zebra'])+ expect(result.snippets.map((s) => s.name)).toEqual(['folder-snippet'])})- it('should sort snippets by name in descending order', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'zebra.sql', isDirectory: () => false, isFile: () => true },- { name: 'apple.sql', isDirectory: () => false, isFile: () => true },- { name: 'banana.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT 1;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ it.each([+ ['asc', ['Apple', 'banana', 'zebra']],+ ['desc', ['zebra', 'banana', 'Apple']],+ ] as const)('should sort by name case-insensitively (%s)', async (sortOrder, expected) => {+ mockTree({ root: [file('zebra.sql'), file('Apple.sql'), file('banana.sql')] })- const result = await getSnippets({ sort: 'name', sortOrder: 'desc' })+ const result = await getSnippets({ sort: 'name', sortOrder })- expect(result.snippets.map((s) => s.name)).toEqual(['zebra', 'banana', 'apple'])+ expect(result.snippets.map((s) => s.name)).toEqual(expected)})it('should sort snippets by creation date', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'newest.sql', isDirectory: () => false, isFile: () => true },- { name: 'oldest.sql', isDirectory: () => false, isFile: () => true },- { name: 'middle.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT 1;')- mockedFS.stat.mockImplementation((filePath: any) => {- const fileName = path.basename(filePath as string)- switch (fileName) {- case 'newest.sql':- return Promise.resolve({ birthtime: new Date('2023-03-01') } as any)- case 'oldest.sql':- return Promise.resolve({ birthtime: new Date('2023-01-01') } as any)- case 'middle.sql':- return Promise.resolve({ birthtime: new Date('2023-02-01') } as any)- default:- return Promise.resolve({ birthtime: new Date('2023-01-01') } as any)- }- })+ mockTree({ root: [file('newest.sql'), file('oldest.sql'), file('middle.sql')] })+ const birthtimes: Record<string, string> = {+ 'newest.sql': '2023-03-01',+ 'oldest.sql': '2023-01-01',+ 'middle.sql': '2023-02-01',+ }+ mockedFS.stat.mockImplementation(((filePath: string) =>+ Promise.resolve({ birthtime: new Date(birthtimes[path.basename(filePath)]) })) as never)- // Test descending order (newest first - default behavior)const resultDesc = await getSnippets({ sort: 'inserted_at', sortOrder: 'desc' })expect(resultDesc.snippets.map((s) => s.name)).toEqual(['newest', 'middle', 'oldest'])- // Test ascending order (oldest first)const resultAsc = await getSnippets({ sort: 'inserted_at', sortOrder: 'asc' })expect(resultAsc.snippets.map((s) => s.name)).toEqual(['oldest', 'middle', 'newest'])})- it('should paginate results with limit', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },- { name: 'snippet2.sql', isDirectory: () => false, isFile: () => true },- { name: 'snippet3.sql', isDirectory: () => false, isFile: () => true },- { name: 'snippet4.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT 1;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const result = await getSnippets({ limit: 2, sort: 'name', sortOrder: 'asc' })-- expect(result.snippets).toHaveLength(2)- expect(result.snippets.map((s) => s.name)).toEqual(['snippet1', 'snippet2'])- expect(result.cursor).toBeDefined() // Should have a cursor for next page- })+ it('should paginate with limit and cursor', async () => {+ mockTree({ root: [file('snippet1.sql'), file('snippet2.sql'), file('snippet3.sql')] })- it('should use cursor for pagination', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },- { name: 'snippet2.sql', isDirectory: () => false, isFile: () => true },- { name: 'snippet3.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT 1;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- // Get first page- const firstPage = await getSnippets({ limit: 1, sort: 'name', sortOrder: 'asc' })- expect(firstPage.snippets).toHaveLength(1)- expect(firstPage.snippets[0].name).toBe('snippet1')+ const firstPage = await getSnippets({ limit: 2, sort: 'name', sortOrder: 'asc' })+ expect(firstPage.snippets.map((s) => s.name)).toEqual(['snippet1', 'snippet2'])expect(firstPage.cursor).toBeDefined()- // Get second page using cursorconst secondPage = await getSnippets({cursor: firstPage.cursor,- limit: 1,+ limit: 2,sort: 'name',sortOrder: 'asc',})- expect(secondPage.snippets).toHaveLength(1)- expect(secondPage.snippets[0].name).toBe('snippet2')+ expect(secondPage.snippets.map((s) => s.name)).toEqual(['snippet3'])})- it('should handle invalid cursor gracefully', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT 1;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ it('should ignore an invalid cursor', async () => {+ mockTree({ root: [file('snippet1.sql')] })const result = await getSnippets({ cursor: 'invalid-cursor-id' })- expect(result.snippets).toHaveLength(1) // Should return all snippets- expect(result.snippets[0].name).toBe('snippet1')+ expect(result.snippets.map((s) => s.name)).toEqual(['snippet1'])})- it('should use default parameters when none provided', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT 1;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const result = await getSnippets({})-- expect(result.snippets).toHaveLength(1)- expect(result.cursor).toBeUndefined()- // Default sort should be by inserted_at desc- })-- it('should handle empty search term', async () => {- const folderId = generateDeterministicUuid(['my-folder'])-- const createMockDirent = (name: string, isDirectory: boolean) => ({- name,- isDirectory: () => isDirectory,- isFile: () => !isDirectory,- })-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockImplementation((dirPath: any) => {- if (dirPath === MOCK_SNIPPETS_DIR) {- return Promise.resolve([- createMockDirent('root-snippet.sql', false),- createMockDirent('my-folder', true),- ] as any)- } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'my-folder')) {- return Promise.resolve([createMockDirent('folder-snippet.sql', false)] as any)- }- return Promise.resolve([])- })- mockedFS.readFile.mockResolvedValue('SELECT 1;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- // Empty search term should filter by folderId- const result = await getSnippets({ searchTerm: ' ', folderId })-- expect(result.snippets).toHaveLength(1)- expect(result.snippets[0].name).toBe('folder-snippet')- })-- it('should handle filesystem errors', async () => {+ it('should propagate filesystem errors', async () => {mockedFS.access.mockRejectedValue(new Error('Directory not accessible'))mockedFS.mkdir.mockRejectedValue(new Error('Directory not accessible'))@@ -590,120 +361,51 @@ describe('snippets.utils', () => {})it('should return correct snippet structure', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'test-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT * FROM users;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01T10:00:00Z') } as any)+ mockTree({ root: [file('test-snippet.sql')], content: 'SELECT * FROM users;' })+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01T10:00:00Z') } as never)const result = await getSnippets({})expect(result.snippets).toHaveLength(1)- const snippet = result.snippets[0]-- expect(snippet).toMatchObject({+ expect(result.snippets[0]).toMatchObject({+ id: expect.any(String),name: 'test-snippet',type: 'sql',- content: {- sql: 'SELECT * FROM users;',- schema_version: '1.0',- },+ content: { sql: 'SELECT * FROM users;', schema_version: '1.0' },visibility: 'user',- project_id: 1,folder_id: null,- owner_id: 1,- owner: { id: 1, username: 'johndoe' },- updated_by: { id: 1, username: 'johndoe' },+ inserted_at: '2023-01-01T10:00:00.000Z',+ updated_at: '2023-01-01T10:00:00.000Z',})-- expect(snippet.id).toBeDefined()- expect(snippet.inserted_at).toBe('2023-01-01T10:00:00.000Z')- expect(snippet.updated_at).toBe('2023-01-01T10:00:00.000Z')- })-- it('should perform case-insensitive search', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'USER-query.sql', isDirectory: () => false, isFile: () => true },- { name: 'admin-report.sql', isDirectory: () => false, isFile: () => true },- { name: 'Test-User-Data.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT 1;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const result = await getSnippets({ searchTerm: 'user', sort: 'name', sortOrder: 'asc' })-- expect(result.snippets).toHaveLength(2)- expect(result.snippets.map((s) => s.name)).toEqual(['Test-User-Data', 'USER-query'])- })-- it('should perform case-insensitive name sorting', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'zebra.sql', isDirectory: () => false, isFile: () => true },- { name: 'Apple.sql', isDirectory: () => false, isFile: () => true },- { name: 'banana.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT 1;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const result = await getSnippets({ sort: 'name', sortOrder: 'asc' })-- expect(result.snippets.map((s) => s.name)).toEqual(['Apple', 'banana', 'zebra'])})- it('should validate limit parameter', async () => {+ it('should validate the limit parameter', async () => {await expect(getSnippets({ limit: 0 })).rejects.toThrow('Limit must be a positive number')await expect(getSnippets({ limit: -5 })).rejects.toThrow('Limit must be a positive number')await expect(getSnippets({ limit: 1001 })).rejects.toThrow('Limit cannot exceed 1000')- })-- it('should handle large valid limit', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT 1;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)- const result = await getSnippets({ limit: 1000 })-- expect(result.snippets).toHaveLength(1)+ mockTree({ root: [file('snippet1.sql')] })+ await expect(getSnippets({ limit: 1000 })).resolves.toMatchObject({+ snippets: [expect.objectContaining({ name: 'snippet1' })],+ })})it('should omit content but keep metadata when includeContent is false', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'test-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01T10:00:00Z') } as any)+ mockTree({ root: [file('test-snippet.sql')] })const result = await getSnippets({ includeContent: false })expect(result.snippets).toHaveLength(1)const snippet = result.snippets[0]-// Matches the Management API folder-listing contract: metadata, no SQL body.expect(snippet).not.toHaveProperty('content')- expect(snippet).toMatchObject({- name: 'test-snippet',- type: 'sql',- visibility: 'user',- folder_id: null,- })- expect(snippet.id).toBeDefined()+ expect(snippet).toMatchObject({ name: 'test-snippet', type: 'sql', folder_id: null })// Listing must not read file contents off disk.expect(mockedFS.readFile).not.toHaveBeenCalled()})it('searches by name without reading content when includeContent is false', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'user-query.sql', isDirectory: () => false, isFile: () => true },- { name: 'admin-report.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ mockTree({ root: [file('user-query.sql'), file('admin-report.sql')] })const result = await getSnippets({ searchTerm: 'user', includeContent: false })@@ -713,455 +415,131 @@ describe('snippets.utils', () => {})describe('saveSnippet', () => {- it('should save a snippet to the filesystem', async () => {- const mockSnippet: Snippet = {- id: 'test-id',- inserted_at: '2023-01-01T00:00:00.000Z',- updated_at: '2023-01-01T00:00:00.000Z',- type: 'sql',- name: 'test-snippet',- description: 'Test snippet',- favorite: false,- content: {- sql: 'SELECT * FROM test;',- content_id: 'content-id',- schema_version: '1.0',- },- visibility: 'user',- project_id: 1,- folder_id: null,- owner_id: 1,- owner: { id: 1, username: 'testuser' },- updated_by: { id: 1, username: 'testuser' },- }-- // Mock that no existing snippet exists- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])- mockedFS.writeFile.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ it.each([+ ['regular content', 'test-snippet', 'SELECT * FROM test;'],+ ['empty content', 'empty-snippet', ''],+ ['special characters in the name', 'my-snippet_v2 (copy)', 'SELECT 1;'],+ ])('should save a snippet with %s', async (_, name, sql) => {+ mockTree({ root: [] })- const result = await saveSnippet(mockSnippet)-- expect(mockedFS.writeFile).toHaveBeenCalledWith(- path.join(MOCK_SNIPPETS_DIR, 'test-snippet.sql'),- 'SELECT * FROM test;',- 'utf-8'+ const result = await saveSnippet(+ makeSnippet({ name, content: { sql, content_id: 'c', schema_version: '1.0' } }))- expect(result.name).toBe('test-snippet')- expect(result.content.sql).toBe('SELECT * FROM test;')- })-- it('should handle empty content', async () => {- const mockSnippet: Snippet = {- id: 'test-id',- inserted_at: '2023-01-01T00:00:00.000Z',- updated_at: '2023-01-01T00:00:00.000Z',- type: 'sql',- name: 'empty-snippet',- description: '',- favorite: false,- content: {- sql: '',- content_id: 'content-id',- schema_version: '1.0',- },- visibility: 'user',- project_id: 1,- folder_id: null,- owner_id: 1,- owner: { id: 1, username: 'testuser' },- updated_by: { id: 1, username: 'testuser' },- }-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])- mockedFS.writeFile.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const result = await saveSnippet(mockSnippet)expect(mockedFS.writeFile).toHaveBeenCalledWith(- path.join(MOCK_SNIPPETS_DIR, 'empty-snippet.sql'),- '',+ path.join(MOCK_SNIPPETS_DIR, `${name}.sql`),+ sql,'utf-8')- expect(result.content.sql).toBe('')+ expect(result.name).toBe(name)+ expect(result.content.sql).toBe(sql)})it('should throw error when snippet already exists', async () => {- const mockSnippet: Snippet = {+ const snippet = makeSnippet({id: generateDeterministicUuid(['existing-snippet.sql']),- inserted_at: '2023-01-01T00:00:00.000Z',- updated_at: '2023-01-01T00:00:00.000Z',- type: 'sql',name: 'existing-snippet',- description: '',- favorite: false,- content: {- sql: 'SELECT * FROM test;',- content_id: 'content-id',- schema_version: '1.0',- },- visibility: 'user',- project_id: 1,- folder_id: null,- owner_id: 1,- owner: { id: 1, username: 'testuser' },- updated_by: { id: 1, username: 'testuser' },- }-- // Mock that snippet already exists- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT * FROM existing;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ })+ mockTree({ root: [file('existing-snippet.sql')] })- await expect(saveSnippet(mockSnippet)).rejects.toThrow(- `Snippet with id ${mockSnippet.id} already exists`+ await expect(saveSnippet(snippet)).rejects.toThrow(+ `Snippet with id ${snippet.id} already exists`)})it('should save snippet to a folder when folder_id is provided', async () => {- const mockSnippet: Snippet = {- id: 'test-id',- inserted_at: '2023-01-01T00:00:00.000Z',- updated_at: '2023-01-01T00:00:00.000Z',- type: 'sql',- name: 'folder-snippet',- description: '',- favorite: false,- content: {- sql: 'SELECT * FROM folder_table;',- content_id: 'content-id',- schema_version: '1.0',- },- visibility: 'user',- project_id: 1,- folder_id: generateDeterministicUuid(['test-folder']),- owner_id: 1,- owner: { id: 1, username: 'testuser' },- updated_by: { id: 1, username: 'testuser' },- }+ const folderId = generateDeterministicUuid(['test-folder'])+ mockTree({ root: [dir('test-folder')] })- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'test-folder', isDirectory: () => true, isFile: () => false },- ] as any)- mockedFS.writeFile.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const result = await saveSnippet(mockSnippet)+ const result = await saveSnippet(makeSnippet({ name: 'folder-snippet', folder_id: folderId }))expect(mockedFS.writeFile).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'test-folder', 'folder-snippet.sql'),- 'SELECT * FROM folder_table;',+ 'SELECT * FROM test;','utf-8')- expect(result.folder_id).toBe(generateDeterministicUuid(['test-folder']))+ expect(result.folder_id).toBe(folderId)})it('should throw error when folder_id is provided but folder does not exist', async () => {- const mockSnippet: Snippet = {- id: 'test-id',- inserted_at: '2023-01-01T00:00:00.000Z',- updated_at: '2023-01-01T00:00:00.000Z',- type: 'sql',- name: 'orphan-snippet',- description: '',- favorite: false,- content: {- sql: 'SELECT * FROM table;',- content_id: 'content-id',- schema_version: '1.0',- },- visibility: 'user',- project_id: 1,- folder_id: 'non-existent-folder-id',- owner_id: 1,- owner: { id: 1, username: 'testuser' },- updated_by: { id: 1, username: 'testuser' },- }+ mockTree({ root: [] })- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])-- await expect(saveSnippet(mockSnippet)).rejects.toThrow(- 'Folder with id non-existent-folder-id not found'- )+ await expect(+ saveSnippet(makeSnippet({ folder_id: 'non-existent-folder-id' }))+ ).rejects.toThrow('Folder with id non-existent-folder-id not found')})- it('should reject path traversal attempts with ../', async () => {- const mockSnippet: Snippet = {- id: 'test-id',- inserted_at: '2023-01-01T00:00:00.000Z',- updated_at: '2023-01-01T00:00:00.000Z',- type: 'sql',- name: '../malicious-snippet',- description: '',- favorite: false,- content: {- sql: 'SELECT * FROM test;',- content_id: 'content-id',- schema_version: '1.0',- },- visibility: 'user',- project_id: 1,- folder_id: null,- owner_id: 1,- owner: { id: 1, username: 'testuser' },- updated_by: { id: 1, username: 'testuser' },- }-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])+ it.each(UNSAFE_NAMES)('should reject unsafe names (%s)', async (_, name) => {+ mockTree({ root: [] })- await expect(saveSnippet(mockSnippet)).rejects.toThrow(+ await expect(saveSnippet(makeSnippet({ name }))).rejects.toThrow('Invalid name: path traversal or null bytes detected')- })-- it('should reject path traversal attempts with nested directories', async () => {- const mockSnippet: Snippet = {- id: 'test-id',- inserted_at: '2023-01-01T00:00:00.000Z',- updated_at: '2023-01-01T00:00:00.000Z',- type: 'sql',- name: 'foo/bar/snippet',- description: '',- favorite: false,- content: {- sql: 'SELECT * FROM test;',- content_id: 'content-id',- schema_version: '1.0',- },- visibility: 'user',- project_id: 1,- folder_id: null,- owner_id: 1,- owner: { id: 1, username: 'testuser' },- updated_by: { id: 1, username: 'testuser' },- }-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])-- await expect(saveSnippet(mockSnippet)).rejects.toThrow(- 'Invalid name: path traversal or null bytes detected'- )- })-- it('should reject names with null bytes', async () => {- const mockSnippet: Snippet = {- id: 'test-id',- inserted_at: '2023-01-01T00:00:00.000Z',- updated_at: '2023-01-01T00:00:00.000Z',- type: 'sql',- name: 'malicious\0snippet',- description: '',- favorite: false,- content: {- sql: 'SELECT * FROM test;',- content_id: 'content-id',- schema_version: '1.0',- },- visibility: 'user',- project_id: 1,- folder_id: null,- owner_id: 1,- owner: { id: 1, username: 'testuser' },- updated_by: { id: 1, username: 'testuser' },- }-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])-- await expect(saveSnippet(mockSnippet)).rejects.toThrow(- 'Invalid name: path traversal or null bytes detected'- )- })-- it('should reject absolute path attempts', async () => {- const mockSnippet: Snippet = {- id: 'test-id',- inserted_at: '2023-01-01T00:00:00.000Z',- updated_at: '2023-01-01T00:00:00.000Z',- type: 'sql',- name: '/etc/passwd',- description: '',- favorite: false,- content: {- sql: 'SELECT * FROM test;',- content_id: 'content-id',- schema_version: '1.0',- },- visibility: 'user',- project_id: 1,- folder_id: null,- owner_id: 1,- owner: { id: 1, username: 'testuser' },- updated_by: { id: 1, username: 'testuser' },- }-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])-- await expect(saveSnippet(mockSnippet)).rejects.toThrow(- 'Invalid name: path traversal or null bytes detected'- )- })-- it('should allow valid names with special characters', async () => {- const mockSnippet: Snippet = {- id: 'test-id',- inserted_at: '2023-01-01T00:00:00.000Z',- updated_at: '2023-01-01T00:00:00.000Z',- type: 'sql',- name: 'my-snippet_v2 (copy)',- description: '',- favorite: false,- content: {- sql: 'SELECT * FROM test;',- content_id: 'content-id',- schema_version: '1.0',- },- visibility: 'user',- project_id: 1,- folder_id: null,- owner_id: 1,- owner: { id: 1, username: 'testuser' },- updated_by: { id: 1, username: 'testuser' },- }-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])- mockedFS.writeFile.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const result = await saveSnippet(mockSnippet)-- expect(result.name).toBe('my-snippet_v2 (copy)')- expect(mockedFS.writeFile).toHaveBeenCalledWith(- path.join(MOCK_SNIPPETS_DIR, 'my-snippet_v2 (copy).sql'),- 'SELECT * FROM test;',- 'utf-8'- )+ expect(mockedFS.writeFile).not.toHaveBeenCalled()})})describe('deleteSnippet', () => {it('should delete a snippet file', async () => {- const snippetId = generateDeterministicUuid(['test-snippet.sql'])+ mockTree({ root: [file('test-snippet.sql')] })- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'test-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT * FROM test;')- mockedFS.unlink.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ await deleteSnippet(generateDeterministicUuid(['test-snippet.sql']))- await deleteSnippet(snippetId)-- expect(mockedFS.unlink).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, `test-snippet.sql`))+ expect(mockedFS.unlink).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'test-snippet.sql'))})- it('should not throw error when file does not exist', async () => {- const snippetId = generateDeterministicUuid(['test-snippet.sql'])-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'test-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT * FROM test;')+ it('should delete a snippet file from a folder', async () => {+ const folderId = generateDeterministicUuid(['my-folder'])+ mockTree({+ root: [dir('my-folder')],+ folders: { 'my-folder': [file('folder-snippet.sql')] },+ })- const error = new Error('File not found') as NodeJS.ErrnoException- error.code = 'ENOENT'- mockedFS.unlink.mockRejectedValue(error)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ await deleteSnippet(generateDeterministicUuid([folderId, 'folder-snippet.sql']))- await expect(deleteSnippet(snippetId)).resolves.not.toThrow()+ expect(mockedFS.unlink).toHaveBeenCalledWith(+ path.join(MOCK_SNIPPETS_DIR, 'my-folder', 'folder-snippet.sql')+ )})- it('should throw error for other filesystem errors', async () => {- const snippetId = generateDeterministicUuid(['test-snippet.sql'])+ it('should not throw when the file is already gone (ENOENT)', async () => {+ mockTree({ root: [file('test-snippet.sql')] })+ mockedFS.unlink.mockRejectedValue(errnoError('File not found', 'ENOENT'))- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'test-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT * FROM test;')+ await expect(+ deleteSnippet(generateDeterministicUuid(['test-snippet.sql']))+ ).resolves.toBeUndefined()+ })- const error = new Error('Permission denied') as NodeJS.ErrnoException- error.code = 'EACCES'- mockedFS.unlink.mockRejectedValue(error)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ it('should throw for other filesystem errors', async () => {+ mockTree({ root: [file('test-snippet.sql')] })+ mockedFS.unlink.mockRejectedValue(errnoError('Permission denied', 'EACCES'))- await expect(deleteSnippet(snippetId)).rejects.toThrow('Permission denied')+ await expect(deleteSnippet(generateDeterministicUuid(['test-snippet.sql']))).rejects.toThrow(+ 'Permission denied'+ )})it('should throw error when snippet not found', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])+ mockTree({ root: [] })await expect(deleteSnippet('non-existent-id')).rejects.toThrow('Snippet with id non-existent-id not found')})-- it('should delete a snippet file from a folder', async () => {- const folderName = 'my-folder'- const folderId = generateDeterministicUuid([folderName])- const snippetName = 'folder-snippet'- const snippetId = generateDeterministicUuid([folderId, `${snippetName}.sql`])-- const createMockDirent = (name: string, isDirectory: boolean) => ({- name,- isDirectory: () => isDirectory,- isFile: () => !isDirectory,- })-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockImplementation((dirPath: any) => {- if (dirPath === MOCK_SNIPPETS_DIR) {- return Promise.resolve([createMockDirent(folderName, true)] as any)- } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, folderName)) {- return Promise.resolve([createMockDirent('folder-snippet.sql', false)] as any)- }- return Promise.resolve([])- })- mockedFS.readFile.mockResolvedValue('SELECT * FROM folder_table;')- mockedFS.unlink.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- await deleteSnippet(snippetId)-- expect(mockedFS.unlink).toHaveBeenCalledWith(- path.join(MOCK_SNIPPETS_DIR, 'my-folder', 'folder-snippet.sql')- )- })})describe('updateSnippet', () => {- it('should update an existing snippet', async () => {- const id = generateDeterministicUuid(['existing-snippet.sql'])-- mockedFS.access.mockResolvedValue(undefined)-- // First call to getFilesystemEntries - find existing snippet- mockedFS.readdir.mockResolvedValue([- { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)-- // Read the existing snippet content- mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ const id = generateDeterministicUuid(['existing-snippet.sql'])+ const targetFolderId = generateDeterministicUuid(['target-folder'])- const updates = { name: 'updated-snippet', content: { sql: 'SELECT * FROM new;' } }+ it('should rename and update content, removing the old file', async () => {+ mockTree({ root: [file('existing-snippet.sql')], content: 'SELECT * FROM old;' })- const result = await updateSnippet(id, updates)+ const result = await updateSnippet(id, {+ name: 'updated-snippet',+ content: { sql: 'SELECT * FROM new;' },+ })expect(mockedFS.unlink).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'existing-snippet.sql')@@ -1175,525 +553,217 @@ describe('snippets.utils', () => {expect(result.content.sql).toBe('SELECT * FROM new;')})- it('should throw error when snippet not found', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])-- await expect(updateSnippet('non-existent-id', {})).rejects.toThrow(- 'Snippet with id non-existent-id not found'- )- })-it('should update only provided fields', async () => {- const id = generateDeterministicUuid(['existing-snippet.sql'])-- mockedFS.access.mockResolvedValue(undefined)- // Mock readdir for both getFilesystemEntries calls (initial and final)- mockedFS.readdir.mockResolvedValue([- { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)- // Mock readFile for both calls (initial and final)- mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)- mockedFS.writeFile.mockResolvedValue(undefined)-- const updates = {- name: 'new-name',- }+ mockTree({ root: [file('existing-snippet.sql')], content: 'SELECT * FROM old;' })- const result = await updateSnippet(id, updates)+ const result = await updateSnippet(id, { name: 'new-name' })expect(result.name).toBe('new-name')expect(result.content.sql).toBe('SELECT * FROM old;')})- it('should move snippet to a folder when folder_id is updated', async () => {- const id = generateDeterministicUuid(['existing-snippet.sql'])- const targetFolderId = generateDeterministicUuid(['target-folder'])-- const createMockDirent = (name: string, isDirectory: boolean) => ({- name,- isDirectory: () => isDirectory,- isFile: () => !isDirectory,- })-- // Mock existing snippet in root directory- mockedFS.access.mockResolvedValue(undefined)-- // Mock multiple readdir calls - the function calls getFilesystemEntries twice- mockedFS.readdir.mockImplementation((dirPath: any) => {- if (dirPath === MOCK_SNIPPETS_DIR) {- return Promise.resolve([- createMockDirent('existing-snippet.sql', false),- createMockDirent('target-folder', true),- ] as any)- } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'target-folder')) {- return Promise.resolve([])- }- return Promise.resolve([])- })-- mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')- mockedFS.writeFile.mockResolvedValue(undefined)- mockedFS.unlink.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const updates = { folder_id: targetFolderId }-- const result = await updateSnippet(id, updates)-- // Should write to the folder path- expect(mockedFS.writeFile).toHaveBeenCalledWith(- path.join(MOCK_SNIPPETS_DIR, 'target-folder', 'existing-snippet.sql'),- 'SELECT * FROM old;',- 'utf-8'- )- // Should delete the old file from root- expect(mockedFS.unlink).toHaveBeenCalledWith(- path.join(MOCK_SNIPPETS_DIR, 'existing-snippet.sql')- )- expect(result.folder_id).toBe(targetFolderId)- })-- it('should move snippet from folder to root when folder_id is set to null', async () => {- const folderName = 'source-folder'- const folderId = generateDeterministicUuid([folderName])- const id = generateDeterministicUuid([folderId, 'existing-snippet.sql'])-- const createMockDirent = (name: string, isDirectory: boolean) => ({- name,- isDirectory: () => isDirectory,- isFile: () => !isDirectory,- })-- mockedFS.access.mockResolvedValue(undefined)-- // Mock existing snippet in a folder - the function expects the snippet to have folder_id set- mockedFS.readdir.mockImplementation((dirPath: any) => {- if (dirPath === MOCK_SNIPPETS_DIR) {- return Promise.resolve([createMockDirent(folderName, true)] as any)- } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, folderName)) {- return Promise.resolve([createMockDirent('existing-snippet.sql', false)] as any)- }- return Promise.resolve([])- })-- mockedFS.readFile.mockResolvedValue('SELECT * FROM folder;')- mockedFS.writeFile.mockResolvedValue(undefined)- mockedFS.unlink.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const updates = { folder_id: null }+ it('should update content to empty string', async () => {+ mockTree({ root: [file('existing-snippet.sql')], content: 'SELECT * FROM old;' })- const result = await updateSnippet(id, updates)+ const result = await updateSnippet(id, { content: { sql: '' } })- // Should write to the root path+ expect(result.content.sql).toBe('')expect(mockedFS.writeFile).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'existing-snippet.sql'),- 'SELECT * FROM folder;',+ '','utf-8')- // Should delete the old file from folder- expect(mockedFS.unlink).toHaveBeenCalledWith(- path.join(MOCK_SNIPPETS_DIR, 'source-folder', 'existing-snippet.sql')- )- expect(result.folder_id).toBe(null)})- it('should throw error when trying to move to non-existent folder', async () => {- const id = generateDeterministicUuid(['existing-snippet.sql'])- const nonExistentFolderId = 'non-existent-folder-id'-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT * FROM table;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const updates = { folder_id: nonExistentFolderId }+ it('should throw error when snippet not found', async () => {+ mockTree({ root: [] })- await expect(updateSnippet(id, updates)).rejects.toThrow(- `Folder with id ${nonExistentFolderId} not found`+ await expect(updateSnippet('non-existent-id', {})).rejects.toThrow(+ 'Snippet with id non-existent-id not found')})- it('should handle renaming snippet while moving to folder', async () => {- const id = generateDeterministicUuid(['existing-snippet.sql'])- const targetFolderId = generateDeterministicUuid(['target-folder'])-- const createMockDirent = (name: string, isDirectory: boolean) => ({- name,- isDirectory: () => isDirectory,- isFile: () => !isDirectory,+ it('should move snippet to a folder, renaming it at the same time', async () => {+ mockTree({+ root: [file('existing-snippet.sql'), dir('target-folder')],+ content: 'SELECT * FROM old;',})- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockImplementation((dirPath: any) => {- if (dirPath === MOCK_SNIPPETS_DIR) {- return Promise.resolve([- createMockDirent('existing-snippet.sql', false),- createMockDirent('target-folder', true),- ] as any)- } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'target-folder')) {- return Promise.resolve([])- }- return Promise.resolve([])- })-- mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')- mockedFS.writeFile.mockResolvedValue(undefined)- mockedFS.unlink.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const updates = {+ const result = await updateSnippet(id, {name: 'renamed-snippet',folder_id: targetFolderId,content: { sql: 'SELECT * FROM new;' },- }-- const result = await updateSnippet(id, updates as any)+ })- // Should write to the folder path with new nameexpect(mockedFS.writeFile).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'target-folder', 'renamed-snippet.sql'),'SELECT * FROM new;','utf-8')- // Should delete the old file from root with old nameexpect(mockedFS.unlink).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'existing-snippet.sql'))- expect(result.name).toBe('renamed-snippet')- expect(result.folder_id).toBe(targetFolderId)- expect(result.content.sql).toBe('SELECT * FROM new;')+ expect(result).toMatchObject({ name: 'renamed-snippet', folder_id: targetFolderId })})- it('should update content to empty string', async () => {- const id = generateDeterministicUuid(['existing-snippet.sql'])-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')- mockedFS.writeFile.mockResolvedValue(undefined)- mockedFS.unlink.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const updates = { content: { sql: '' } }+ it('should move snippet from folder to root when folder_id is set to null', async () => {+ const folderId = generateDeterministicUuid(['source-folder'])+ mockTree({+ root: [dir('source-folder')],+ folders: { 'source-folder': [file('existing-snippet.sql')] },+ content: 'SELECT * FROM folder;',+ })- const result = await updateSnippet(id, updates as any)+ const result = await updateSnippet(+ generateDeterministicUuid([folderId, 'existing-snippet.sql']),+ { folder_id: null }+ )- expect(result.content.sql).toBe('')expect(mockedFS.writeFile).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'existing-snippet.sql'),- '',+ 'SELECT * FROM folder;','utf-8')+ expect(mockedFS.unlink).toHaveBeenCalledWith(+ path.join(MOCK_SNIPPETS_DIR, 'source-folder', 'existing-snippet.sql')+ )+ expect(result.folder_id).toBe(null)})- it('should handle old file deletion errors other than ENOENT', async () => {- const id = generateDeterministicUuid(['existing-snippet.sql'])-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ it('should throw error when trying to move to non-existent folder', async () => {+ mockTree({ root: [file('existing-snippet.sql')] })- const error = new Error('Permission denied') as NodeJS.ErrnoException- error.code = 'EACCES'- mockedFS.unlink.mockRejectedValue(error)+ await expect(updateSnippet(id, { folder_id: 'non-existent-folder-id' })).rejects.toThrow(+ 'Folder with id non-existent-folder-id not found'+ )+ })- const updates = { name: 'new-name' }+ it('should throw when the target folder already contains a snippet with the same name', async () => {+ mockTree({+ root: [file('existing-snippet.sql'), dir('target-folder')],+ folders: { 'target-folder': [file('existing-snippet.sql')] },+ })- await expect(updateSnippet(id, updates)).rejects.toThrow('Permission denied')+ await expect(updateSnippet(id, { folder_id: targetFolderId })).rejects.toThrow(+ 'Snippet named "existing-snippet" already exists in the specified folder'+ )})- it('should continue when old file deletion fails with ENOENT', async () => {- const id = generateDeterministicUuid(['existing-snippet.sql'])-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },- ] as any)- mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')- mockedFS.writeFile.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ it('should throw when old file deletion fails with an error other than ENOENT', async () => {+ mockTree({ root: [file('existing-snippet.sql')] })+ mockedFS.unlink.mockRejectedValue(errnoError('Permission denied', 'EACCES'))- const error = new Error('File not found') as NodeJS.ErrnoException- error.code = 'ENOENT'- mockedFS.unlink.mockRejectedValue(error)+ await expect(updateSnippet(id, { name: 'new-name' })).rejects.toThrow('Permission denied')+ })- const updates = { name: 'new-name' }+ it('should continue when old file deletion fails with ENOENT', async () => {+ mockTree({ root: [file('existing-snippet.sql')], content: 'SELECT * FROM old;' })+ mockedFS.unlink.mockRejectedValue(errnoError('File not found', 'ENOENT'))- const result = await updateSnippet(id, updates)+ const result = await updateSnippet(id, { name: 'new-name' })expect(result.name).toBe('new-name')expect(result.content.sql).toBe('SELECT * FROM old;')})-- it('should throw error when moving snippet to folder that already contains snippet with same name', async () => {- const snippetName = 'existing-snippet'- const existingSnippetId = generateDeterministicUuid([`${snippetName}.sql`])- const targetFolderId = generateDeterministicUuid(['target-folder'])-- const createMockDirent = (name: string, isDirectory: boolean) => ({- name,- isDirectory: () => isDirectory,- isFile: () => !isDirectory,- })-- mockedFS.access.mockResolvedValue(undefined)-- // Mock filesystem structure with:- // - existing-snippet.sql in root- // - target-folder/ with existing-snippet.sql inside- mockedFS.readdir.mockImplementation((dirPath: any) => {- if (dirPath === MOCK_SNIPPETS_DIR) {- return Promise.resolve([- createMockDirent('existing-snippet.sql', false),- createMockDirent('target-folder', true),- ] as any)- } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'target-folder')) {- return Promise.resolve([createMockDirent(`${snippetName}.sql`, false)] as any)- }- return Promise.resolve([])- })-- mockedFS.readFile.mockResolvedValue('SELECT * FROM table;')- mockedFS.unlink.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)-- const updates = { folder_id: targetFolderId }-- await expect(updateSnippet(existingSnippetId, updates)).rejects.toThrow(- `Snippet named "${snippetName}" already exists in the specified folder`- )- })})describe('getFolders', () => {- it('should read directories from the snippets folder', async () => {- const mockDirents = [- { name: 'folder1', isDirectory: () => true, isFile: () => false },- { name: 'folder2', isDirectory: () => true, isFile: () => false },- { name: 'snippet.sql', isDirectory: () => false, isFile: () => true },- ]-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir- .mockResolvedValueOnce(mockDirents as any) // First call for getFilesystemEntries- .mockResolvedValueOnce([]) // folder1 contents (empty)- .mockResolvedValueOnce([]) // folder2 contents (empty)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ it('should return only directories, with deterministic ids', async () => {+ mockTree({ root: [dir('folder1'), dir('folder2'), file('snippet.sql')] })const folders = await getFolders()- expect(folders).toHaveLength(2)- expect(folders[0].name).toBe('folder1')- expect(folders[1].name).toBe('folder2')- expect(folders[0].id).toBe(generateDeterministicUuid(['folder1']))- expect(folders[1].id).toBe(generateDeterministicUuid(['folder2']))+ expect(folders.map((f) => ({ id: f.id, name: f.name }))).toEqual([+ { id: generateDeterministicUuid(['folder1']), name: 'folder1' },+ { id: generateDeterministicUuid(['folder2']), name: 'folder2' },+ ])})it('should return empty array when no directories exist', async () => {- const mockDirents = [{ name: 'snippet.sql', isDirectory: () => false, isFile: () => true }]-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue(mockDirents as any)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ mockTree({ root: [file('snippet.sql')] })- const folders = await getFolders()-- expect(folders).toEqual([])- })-- it('should handle directory creation when it does not exist', async () => {- mockedFS.access.mockRejectedValue(new Error('Directory does not exist'))- mockedFS.readdir.mockResolvedValue([])-- const folders = await getFolders()-- expect(folders).toEqual([])+ expect(await getFolders()).toEqual([])})})describe('createFolder', () => {it('should create a new folder as an actual directory', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([]) // No existing folders- mockedFS.mkdir.mockResolvedValue(undefined)+ const name = 'Folder with spaces & symbols!'+ mockTree({ root: [] })- const result = await createFolder('New Folder')+ const result = await createFolder(name)- expect(result.id).toBe(generateDeterministicUuid(['New Folder']))- expect(result.name).toBe('New Folder')- expect(result.owner_id).toBe(1)- expect(mockedFS.mkdir).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'New Folder'), {+ expect(result.id).toBe(generateDeterministicUuid([name]))+ expect(result.name).toBe(name)+ expect(mockedFS.mkdir).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, name), {recursive: true,})})- it('should handle folder creation with special characters in name', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])- mockedFS.mkdir.mockResolvedValue(undefined)-- const result = await createFolder('Folder with spaces & symbols!')-- expect(result.id).toBe(generateDeterministicUuid(['Folder with spaces & symbols!']))- expect(result.name).toBe('Folder with spaces & symbols!')- expect(mockedFS.mkdir).toHaveBeenCalledWith(- path.join(MOCK_SNIPPETS_DIR, 'Folder with spaces & symbols!'),- { recursive: true }- )- })-it('should throw error when folder already exists', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'Existing Folder', isDirectory: () => true, isFile: () => false },- ] as any)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ mockTree({ root: [dir('Existing Folder')] })await expect(createFolder('Existing Folder')).rejects.toThrow('Folder with name Existing Folder already exists')})- it('should handle mkdir errors', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])+ it('should propagate mkdir errors', async () => {+ mockTree({ root: [] })mockedFS.mkdir.mockRejectedValue(new Error('Permission denied'))await expect(createFolder('New Folder')).rejects.toThrow('Permission denied')})- it('should create directory when snippets directory does not exist', async () => {- mockedFS.access.mockRejectedValue(new Error('Directory does not exist'))- mockedFS.readdir.mockResolvedValue([])- mockedFS.mkdir.mockResolvedValue(undefined)+ it.each(UNSAFE_NAMES)('should reject unsafe names (%s)', async (_, name) => {+ mockTree({ root: [] })- const result = await createFolder('New Folder')-- expect(result.name).toBe('New Folder')- expect(mockedFS.mkdir).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'New Folder'), {- recursive: true,- })- })-- it('should reject path traversal attempts with ../', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])-- await expect(createFolder('../malicious-folder')).rejects.toThrow(- 'Invalid name: path traversal or null bytes detected'- )- })-- it('should reject path traversal attempts with nested directories', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])-- await expect(createFolder('foo/bar/folder')).rejects.toThrow(- 'Invalid name: path traversal or null bytes detected'- )- })-- it('should reject names with null bytes', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])-- await expect(createFolder('malicious\0folder')).rejects.toThrow(- 'Invalid name: path traversal or null bytes detected'- )- })-- it('should reject absolute path attempts', async () => {- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])-- await expect(createFolder('/etc/malicious')).rejects.toThrow(+ await expect(createFolder(name)).rejects.toThrow('Invalid name: path traversal or null bytes detected')+ expect(mockedFS.mkdir).not.toHaveBeenCalled()})})describe('deleteFolder', () => {- it('should delete an existing folder directory', async () => {- const folderId = generateDeterministicUuid(['Delete Me'])-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'Delete Me', isDirectory: () => true, isFile: () => false, folderId: null },- { name: 'Keep Me', isDirectory: () => true, isFile: () => false, folderId: null },- ] as any)- mockedFS.rm.mockResolvedValue(undefined)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ it('should delete only the targeted folder directory', async () => {+ mockTree({ root: [dir('Delete Me'), dir('Keep Me')] })- await deleteFolder(folderId)+ await deleteFolder(generateDeterministicUuid(['Delete Me']))expect(mockedFS.rm).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'Delete Me'), {recursive: true,force: true,})+ expect(mockedFS.rm).not.toHaveBeenCalledWith(+ path.join(MOCK_SNIPPETS_DIR, 'Keep Me'),+ expect.anything()+ )})it('should throw error when folder not found', async () => {- const nonExistentId = 'non-existent-folder-id'+ mockTree({ root: [] })- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([])-- await expect(deleteFolder(nonExistentId)).rejects.toThrow(- `Folder with id ${nonExistentId} not found`+ await expect(deleteFolder('non-existent-folder-id')).rejects.toThrow(+ 'Folder with id non-existent-folder-id not found')})- it('should handle directory deletion errors gracefully', async () => {- const folderId = generateDeterministicUuid(['Test Folder'])-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'Test Folder', isDirectory: () => true, isFile: () => false, folderId: null },- ] as any)-- const error = new Error('Permission denied') as NodeJS.ErrnoException- error.code = 'EACCES'- mockedFS.rm.mockRejectedValue(error)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ it('should propagate directory deletion errors', async () => {+ mockTree({ root: [dir('Test Folder')] })+ mockedFS.rm.mockRejectedValue(errnoError('Permission denied', 'EACCES'))- await expect(deleteFolder(folderId)).rejects.toThrow('Permission denied')+ await expect(deleteFolder(generateDeterministicUuid(['Test Folder']))).rejects.toThrow(+ 'Permission denied'+ )})- it('should throw original error when directory does not exist during deletion', async () => {+ it('should report not found when the directory disappears during deletion (ENOENT)', async () => {const folderId = generateDeterministicUuid(['Test Folder'])-- mockedFS.access.mockResolvedValue(undefined)- mockedFS.readdir.mockResolvedValue([- { name: 'Test Folder', isDirectory: () => true, isFile: () => false, folderId: null },- ] as any)-- const error = new Error('Directory not found') as NodeJS.ErrnoException- error.code = 'ENOENT'- mockedFS.rm.mockRejectedValue(error)- mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)+ mockTree({ root: [dir('Test Folder')] })+ mockedFS.rm.mockRejectedValue(errnoError('Directory not found', 'ENOENT'))await expect(deleteFolder(folderId)).rejects.toThrow(`Folder with id ${folderId} not found`)})-- it('should handle case when snippets directory needs to be created first', async () => {- const nonExistentId = 'non-existent-folder-id'-- mockedFS.access.mockRejectedValue(new Error('Directory does not exist'))- mockedFS.readdir.mockResolvedValue([])-- await expect(deleteFolder(nonExistentId)).rejects.toThrow(- `Folder with id ${nonExistentId} not found`- )- })})})diff --git a/apps/studio/lib/api/status-page.utils.test.ts b/apps/studio/lib/api/status-page.utils.test.tsindex cc93bf75a6b..b12ba09e7aa 100644--- a/apps/studio/lib/api/status-page.utils.test.ts+++ b/apps/studio/lib/api/status-page.utils.test.ts@@ -20,29 +20,17 @@ function entriesWith(fieldId: string, values: CustomFieldEntry['values']): Array}describe('readCustomFieldFlag', () => {- test('matches via value_option', () => {- const entries = entriesWith(FIELD_ID, [{ value_option: { value: 'true' } }])- expect(readCustomFieldFlag(entries, FIELD_ID)).toBe(true)- })-- test('matches via value_text', () => {- const entries = entriesWith(FIELD_ID, [{ value_text: 'true' }])- expect(readCustomFieldFlag(entries, FIELD_ID)).toBe(true)- })-- test('matches via value_numeric (non-zero → true)', () => {- const entries = entriesWith(FIELD_ID, [{ value_numeric: '5' }])- expect(readCustomFieldFlag(entries, FIELD_ID)).toBe(true)- })-- test('value_numeric of 0 → false', () => {- const entries = entriesWith(FIELD_ID, [{ value_numeric: '0' }])- expect(readCustomFieldFlag(entries, FIELD_ID)).toBe(false)- })-- test('value_numeric negative → false', () => {- const entries = entriesWith(FIELD_ID, [{ value_numeric: '-5' }])- expect(readCustomFieldFlag(entries, FIELD_ID)).toBe(false)+ test.each<[string, CustomFieldEntry['values'], boolean]>([+ ['value_option', [{ value_option: { value: 'true' } }], true],+ ['value_text', [{ value_text: 'true' }], true],+ ['non-zero value_numeric', [{ value_numeric: '5' }], true],+ ['zero value_numeric', [{ value_numeric: '0' }], false],+ ['negative value_numeric', [{ value_numeric: '-5' }], false],+ ['uppercase value_option', [{ value_option: { value: 'TRUE' } }], true],+ ['mixed-case "Yes"', [{ value_text: 'Yes' }], true],+ ['whitespace-padded value', [{ value_text: ' true ' }], true],+ ])('reads %s', (_, values, expected) => {+ expect(readCustomFieldFlag(entriesWith(FIELD_ID, values), FIELD_ID)).toBe(expected)})test('missing entry → false', () => {@@ -54,50 +42,18 @@ describe('readCustomFieldFlag', () => {const entries = entriesWith(FIELD_ID, [{ value_text: 'true' }])expect(readCustomFieldFlag(entries, '')).toBe(false)})-- test('is case-insensitive', () => {- const entries = entriesWith(FIELD_ID, [{ value_option: { value: 'TRUE' } }])- expect(readCustomFieldFlag(entries, FIELD_ID)).toBe(true)-- const entries2 = entriesWith(FIELD_ID, [{ value_text: 'Yes' }])- expect(readCustomFieldFlag(entries2, FIELD_ID)).toBe(true)- })-- test('trims whitespace', () => {- const entries = entriesWith(FIELD_ID, [{ value_text: ' true ' }])- expect(readCustomFieldFlag(entries, FIELD_ID)).toBe(true)- })})describe('readCustomFieldNumber', () => {- test('reads a valid positive value via value_numeric', () => {- const entries = entriesWith(FIELD_ID, [{ value_numeric: '7' }])- expect(readCustomFieldNumber(entries, FIELD_ID)).toBe(7)- })-- test('reads a valid positive value via value_option', () => {- const entries = entriesWith(FIELD_ID, [{ value_option: { value: '3' } }])- expect(readCustomFieldNumber(entries, FIELD_ID)).toBe(3)- })-- test('reads a valid positive value via value_text', () => {- const entries = entriesWith(FIELD_ID, [{ value_text: '10' }])- expect(readCustomFieldNumber(entries, FIELD_ID)).toBe(10)- })-- test('0 → null', () => {- const entries = entriesWith(FIELD_ID, [{ value_numeric: '0' }])- expect(readCustomFieldNumber(entries, FIELD_ID)).toBe(null)- })-- test('negative number → null', () => {- const entries = entriesWith(FIELD_ID, [{ value_numeric: '-5' }])- expect(readCustomFieldNumber(entries, FIELD_ID)).toBe(null)- })-- test('non-numeric string (NaN) → null', () => {- const entries = entriesWith(FIELD_ID, [{ value_text: 'not-a-number' }])- expect(readCustomFieldNumber(entries, FIELD_ID)).toBe(null)+ test.each<[string, CustomFieldEntry['values'], number | null]>([+ ['value_numeric', [{ value_numeric: '7' }], 7],+ ['value_option', [{ value_option: { value: '3' } }], 3],+ ['value_text', [{ value_text: '10' }], 10],+ ['zero as null', [{ value_numeric: '0' }], null],+ ['negative as null', [{ value_numeric: '-5' }], null],+ ['non-numeric as null', [{ value_text: 'not-a-number' }], null],+ ])('reads %s', (_, values, expected) => {+ expect(readCustomFieldNumber(entriesWith(FIELD_ID, values), FIELD_ID)).toBe(expected)})test('empty fieldId → null', () => {diff --git a/apps/studio/lib/configcat-attributes.test.ts b/apps/studio/lib/configcat-attributes.test.tsindex 9cda82a72bc..ff7785a73d0 100644--- a/apps/studio/lib/configcat-attributes.test.ts+++ b/apps/studio/lib/configcat-attributes.test.ts@@ -11,19 +11,7 @@ describe('toUnixSecondsString', () => {expect(toUnixSecondsString('2024-01-01T00:00:00Z')).toBe('1704067200')})- it('returns undefined for undefined', () => {- expect(toUnixSecondsString(undefined)).toBeUndefined()- })-- it('returns undefined for null', () => {- expect(toUnixSecondsString(null)).toBeUndefined()- })-- it('returns undefined for an empty string', () => {- expect(toUnixSecondsString('')).toBeUndefined()- })-- it('returns undefined for an unparseable string', () => {- expect(toUnixSecondsString('not-a-date')).toBeUndefined()+ it.each([undefined, null, '', 'not-a-date'])('returns undefined for %o', (value) => {+ expect(toUnixSecondsString(value)).toBeUndefined()})})diff --git a/apps/studio/lib/constants/timezones.test.ts b/apps/studio/lib/constants/timezones.test.tsindex 4db50bf0706..5f55bbe5fb3 100644--- a/apps/studio/lib/constants/timezones.test.ts+++ b/apps/studio/lib/constants/timezones.test.ts@@ -50,18 +50,26 @@ describe('catalog integrity', () => {const winter = new Date('2026-01-15T12:00:00Z')const summer = new Date('2026-07-15T12:00:00Z')- const cases = TIMEZONES_BY_IANA.flatMap((entry) =>- entry.utc.map((iana) => [entry.text, iana, entry] as const)- )+ const getLabelOffsetHours = (label: string) => {+ const match = label.match(/^\(UTC(?:([+-])(\d\d):(\d\d))?\)/)+ if (!match) return undefined+ return match[1] ? (match[1] === '-' ? -1 : 1) * (Number(match[2]) + Number(match[3]) / 60) : 0+ }- it.each(cases)('%s: %s has the offset in its label in winter or summer', (_text, iana, entry) => {- const match = entry.text.match(/^\(UTC(?:([+-])(\d\d):(\d\d))?\)/)- expect(match).not.toBeNull()- const labelOffset = match?.[1]- ? (match[1] === '-' ? -1 : 1) * (Number(match[2]) + Number(match[3]) / 60)- : 0+ it('every IANA zone has the offset in its label in winter or summer', () => {+ const mismatches = TIMEZONES_BY_IANA.flatMap((entry) =>+ entry.utc+ .filter((iana) => {+ const labelOffset = getLabelOffsetHours(entry.text)+ return (+ labelOffset === undefined ||+ ![getOffsetHours(iana, winter), getOffsetHours(iana, summer)].includes(labelOffset)+ )+ })+ .map((iana) => `${entry.text}: ${iana}`)+ )- expect([getOffsetHours(iana, winter), getOffsetHours(iana, summer)]).toContain(labelOffset)+ expect(mismatches).toEqual([])})})@@ -98,13 +106,6 @@ const getTimezone = (zone: string) => {}describe('getTimezoneLabel', () => {- it.each([- ['2026-01-09T03:12:00Z', '(UTC+01:00) Brussels, Copenhagen, Madrid, Paris'],- ['2026-10-09T03:12:00Z', '(UTC+02:00) Brussels, Copenhagen, Madrid, Paris'],- ])('shows Madrid offset at %s', (date, label) => {- expect(getTimezoneLabel(getTimezone('Europe/Madrid'), dayjs(date))).toBe(label)- })-it.each([['2026-03-29T00:59:59Z', '(UTC+01:00)'],['2026-03-29T01:00:00Z', '(UTC+02:00)'],diff --git a/apps/studio/lib/error-reporting.test.ts b/apps/studio/lib/error-reporting.test.tsindex 5f6f4ef44c3..cf31f6d6cca 100644--- a/apps/studio/lib/error-reporting.test.ts+++ b/apps/studio/lib/error-reporting.test.ts@@ -12,174 +12,61 @@ vi.mock('@sentry/nextjs', () => ({}),}))-describe('error-reporting', () => {- describe('captureCriticalError', () => {- it('should not capture error if message is empty', () => {- const error = { message: '' }- captureCriticalError(error, 'test context')-- expect(Sentry.captureException).not.toHaveBeenCalled()- })-- it('should capture regular Error objects', () => {- const error = new Error('Something went wrong')- captureCriticalError(error, 'test action')-- expect(Sentry.captureException).toHaveBeenCalledWith(- expect.objectContaining({ message: 'Something went wrong', name: 'CriticalError' })- )- })-- it('should not capture whitelisted error messages', () => {- const error = new Error('email must be an email')- captureCriticalError(error, 'validation')-- expect(Sentry.captureException).not.toHaveBeenCalled()- })-- it('should not capture errors with partial whitelisted message', () => {- const error = new Error('User error: A user with this email already exists in the system')- captureCriticalError(error, 'sign up')-- expect(Sentry.captureException).not.toHaveBeenCalled()- })-- it('should capture errors that are not whitelisted', () => {- const error = new Error('Database connection failed')- captureCriticalError(error, 'database')-- expect(Sentry.captureException).toHaveBeenCalledWith(- expect.objectContaining({ message: 'Database connection failed', name: 'CriticalError' })- )- })-- it('should capture 5XX ResponseError', () => {- const error = new ResponseError(- 'Internal server error',- 500,- undefined,- undefined,- '/api/test'- )- captureCriticalError(error, 'api call')-- expect(Sentry.captureException).toHaveBeenCalledWith(- expect.objectContaining({- message: 'requestPathname /api/test w/ message: Internal server error',- name: 'CriticalError',- })- )- })-- it('should not capture 4XX ResponseError', () => {- const error = new ResponseError('Not found', 404, undefined, undefined, '/api/test')- captureCriticalError(error, 'api call')-- expect(Sentry.captureException).not.toHaveBeenCalled()- })-- it('should capture ResponseError with 5XX status code', () => {- const error = new ResponseError('Gateway timeout', 504, undefined, undefined, '/api/gateway')- captureCriticalError(error, 'gateway request')-- expect(Sentry.captureException).toHaveBeenCalledWith(- expect.objectContaining({- message: 'requestPathname /api/gateway w/ message: Gateway timeout',- name: 'CriticalError',- })- )- })-- it('should capture ResponseError without code or requestPathname', () => {- const error = new ResponseError('Unknown error')- captureCriticalError(error, 'unknown')-- expect(Sentry.captureException).toHaveBeenCalledWith(- expect.objectContaining({- message: 'Response Error (no code or requestPathname) w/ message: Unknown error',- name: 'CriticalError',- })- )- })-- it('should capture unknown error objects with message property', () => {- const error = { message: 'Custom error object' }- captureCriticalError(error, 'custom')-- expect(Sentry.captureException).toHaveBeenCalledWith(- expect.objectContaining({ message: 'Custom error object', name: 'CriticalError' })- )- })-- it('should not capture unknown error without message', () => {- const error = { foo: 'bar' }- captureCriticalError(error as any, 'no message')-- expect(Sentry.captureException).not.toHaveBeenCalled()- })-- it('should not capture whitelisted password validation error', () => {- const error = new Error(- 'Password is known to be weak and easy to guess, please choose a different one'- )- captureCriticalError(error, 'password update')-- expect(Sentry.captureException).not.toHaveBeenCalled()- })-- it('should not capture whitelisted TOTP error', () => {- const error = new Error('Invalid TOTP code entered')- captureCriticalError(error, 'mfa verification')-- expect(Sentry.captureException).not.toHaveBeenCalled()- })-- it('should not capture whitelisted project name error', () => {- const error = new Error('name should not contain a . string')- captureCriticalError(error, 'create project')-- expect(Sentry.captureException).not.toHaveBeenCalled()- })-- it('should capture non-whitelisted errors even if similar to whitelisted ones', () => {- const error = new Error('email format is invalid')- captureCriticalError(error, 'validation')-- expect(Sentry.captureException).toHaveBeenCalledWith(- expect.objectContaining({ message: 'email format is invalid', name: 'CriticalError' })- )- })-- it('should handle Error objects with empty message', () => {- const error = new Error('')- captureCriticalError(error, 'empty error')-- expect(Sentry.captureException).not.toHaveBeenCalled()- })-- it('should handle ResponseError at boundary of 4XX/5XX (499)', () => {- const error = new ResponseError(- 'Client closed request',- 499,- undefined,- undefined,- '/api/test'- )- captureCriticalError(error, 'request')-- expect(Sentry.captureException).not.toHaveBeenCalled()- })-- it('should handle ResponseError at boundary of 4XX/5XX (500)', () => {- const error = new ResponseError('Internal error', 500, undefined, undefined, '/api/test')- captureCriticalError(error, 'request')+describe('captureCriticalError', () => {+ it.each<[string, Parameters<typeof captureCriticalError>[0]]>([+ ['an object with an empty message', { message: '' }],+ ['an Error with an empty message', new Error('')],+ ['an object without a message', { foo: 'bar' } as unknown as { message: string }],+ ['a whitelisted message', new Error('email must be an email')],+ [+ 'a message containing a whitelisted message',+ new Error('User error: A user with this email already exists in the system'),+ ],+ [+ 'a whitelisted password error',+ new Error('Password is known to be weak and easy to guess, please choose a different one'),+ ],+ ['a whitelisted TOTP error', new Error('Invalid TOTP code entered')],+ ['a whitelisted project name error', new Error('name should not contain a . string')],+ ['a 4XX ResponseError', new ResponseError('Not found', 404, undefined, undefined, '/api/test')],+ [+ 'a ResponseError at the 4XX boundary (499)',+ new ResponseError('Client closed request', 499, undefined, undefined, '/api/test'),+ ],+ ])('does not capture %s', (_, error) => {+ captureCriticalError(error, 'context')++ expect(Sentry.captureException).not.toHaveBeenCalled()+ })- expect(Sentry.captureException).toHaveBeenCalledWith(- expect.objectContaining({- message: 'requestPathname /api/test w/ message: Internal error',- name: 'CriticalError',- })- )- })+ it.each<[string, Parameters<typeof captureCriticalError>[0], string]>([+ ['a regular Error', new Error('Database connection failed'), 'Database connection failed'],+ [+ 'a message similar to, but not matching, a whitelisted one',+ new Error('email format is invalid'),+ 'email format is invalid',+ ],+ ['an unknown object with a message', { message: 'Custom error object' }, 'Custom error object'],+ [+ 'a ResponseError at the 5XX boundary (500)',+ new ResponseError('Internal server error', 500, undefined, undefined, '/api/test'),+ 'requestPathname /api/test w/ message: Internal server error',+ ],+ [+ 'a 5XX ResponseError',+ new ResponseError('Gateway timeout', 504, undefined, undefined, '/api/gateway'),+ 'requestPathname /api/gateway w/ message: Gateway timeout',+ ],+ [+ 'a ResponseError without code or requestPathname',+ new ResponseError('Unknown error'),+ 'Response Error (no code or requestPathname) w/ message: Unknown error',+ ],+ ])('captures %s', (_, error, message) => {+ captureCriticalError(error, 'context')++ expect(Sentry.captureException).toHaveBeenCalledWith(+ expect.objectContaining({ message, name: 'CriticalError' })+ )})})diff --git a/apps/studio/lib/external-identity-providers.test.ts b/apps/studio/lib/external-identity-providers.test.tsindex 2b11db6101a..84ae4a8dafa 100644--- a/apps/studio/lib/external-identity-providers.test.ts+++ b/apps/studio/lib/external-identity-providers.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { afterEach, describe, expect, test, vi } from 'vitest'import {diff --git a/apps/studio/lib/formatSql.test.ts b/apps/studio/lib/formatSql.test.tsindex 67f5662072e..aa457fed9e9 100644--- a/apps/studio/lib/formatSql.test.ts+++ b/apps/studio/lib/formatSql.test.ts@@ -17,7 +17,7 @@ fromexpect(result).toBe('123')})- it('should return the original argument if it is not valid, not throw', () => {+ it('should return templated SQL unchanged rather than throw', () => {const result = formatSql('select {col1}, {col2} from {tableName};')expect(result).toBe('select {col1}, {col2} from {tableName};')})diff --git a/apps/studio/lib/github.test.ts b/apps/studio/lib/github.test.tsindex 4d0e9a4c4e2..f48413095cc 100644--- a/apps/studio/lib/github.test.ts+++ b/apps/studio/lib/github.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { describe, expect, it, vi } from 'vitest'import { getGitHubProfileImgUrl, openInstallGitHubIntegrationWindow } from './github'diff --git a/apps/studio/lib/gotrue.test.ts b/apps/studio/lib/gotrue.test.tsindex 298a9a84221..7c35a5ba32e 100644--- a/apps/studio/lib/gotrue.test.ts+++ b/apps/studio/lib/gotrue.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { describe, expect, it } from 'vitest'import {diff --git a/apps/studio/lib/grants.test.ts b/apps/studio/lib/grants.test.tsindex e1692306fd2..491bdef2dda 100644--- a/apps/studio/lib/grants.test.ts+++ b/apps/studio/lib/grants.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { QueryClient } from '@tanstack/react-query'import { waitFor } from '@testing-library/react'import { platformComponents as components } from 'api-types'diff --git a/apps/studio/lib/helpers.test.ts b/apps/studio/lib/helpers.test.tsindex c800524d7c2..abe3cffafe7 100644--- a/apps/studio/lib/helpers.test.ts+++ b/apps/studio/lib/helpers.test.ts@@ -1,6 +1,5 @@import { toast } from 'sonner'import { copyToClipboard } from 'ui'-import { v4 as _uuidV4 } from 'uuid'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {@@ -30,25 +29,12 @@ import {timeout,tryParseInt,tryParseJson,- uuidv4,} from './helpers'vi.mock('sonner', () => ({toast: { error: vi.fn(), success: vi.fn() },}))-vi.mock('uuid', () => ({- v4: vi.fn(() => 'mocked-uuid'),-}))--describe('uuidv4', () => {- it('calls uuid.v4 and returns the result', () => {- const result = uuidv4()- expect(_uuidV4).toHaveBeenCalled()- expect(result).toBe('mocked-uuid')- })-})-describe('tryParseJson', () => {it('should return the parsed JSON', () => {const result = tryParseJson('{"test": "test"}')@@ -173,7 +159,7 @@ describe('propsAreEqual', () => {})it('should return false if the props are not equal', () => {- propsAreEqual({ a: 1, b: 2 }, { a: 1, b: 3 })+ expect(propsAreEqual({ a: 1, b: 2 }, { a: 1, b: 3 })).toBe(false)})})@@ -391,104 +377,45 @@ describe('isValidHttpUrl', () => {})describe('extractUrls', () => {- it('should extract basic http URLs', () => {- const result = extractUrls('Visit http://example.com for more info')- expect(result).toEqual(['http://example.com'])- })-- it('should extract basic https URLs', () => {- const result = extractUrls('Check out https://supabase.com')- expect(result).toEqual(['https://supabase.com'])- })-- it('should extract URLs with ports', () => {- const result = extractUrls('Connect to http://localhost:3000')- expect(result).toEqual(['http://localhost:3000'])- })-- it('should extract URLs with paths', () => {- const result = extractUrls('Go to https://example.com/path/to/page')- expect(result).toEqual(['https://example.com/path/to/page'])- })-- it('should extract URLs with query parameters', () => {- const result = extractUrls('Visit https://example.com/search?q=test&page=1')- expect(result).toEqual(['https://example.com/search?q=test&page=1'])- })-- it('should extract URLs with fragments', () => {- const result = extractUrls('See https://example.com/page#section')- expect(result).toEqual(['https://example.com/page#section'])- })-- it('should extract URLs with complex paths, query params, and fragments', () => {- const result = extractUrls('Check https://example.com/api/v1/users?id=123&name=test#details')- expect(result).toEqual(['https://example.com/api/v1/users?id=123&name=test#details'])- })-- it('should extract multiple URLs from text', () => {- const result = extractUrls('Visit http://example.com and https://supabase.com for more info')- expect(result).toEqual(['http://example.com', 'https://supabase.com'])- })-- it('should remove trailing punctuation from URLs', () => {- const result = extractUrls('Visit https://example.com.')- expect(result).toEqual(['https://example.com'])- })-- it('should remove multiple trailing punctuation marks', () => {- const result = extractUrls('Check https://example.com!!!')- expect(result).toEqual(['https://example.com'])- })-- it('should remove trailing punctuation including parentheses', () => {- const result = extractUrls('See (https://example.com)')- expect(result).toEqual(['https://example.com'])- })-- it('should handle URLs with trailing commas and periods', () => {- const result = extractUrls('Visit https://example.com, and https://supabase.com.')- expect(result).toEqual(['https://example.com', 'https://supabase.com'])- })-- it('should handle URLs with subpath and markdown bolding', () => {- const result = extractUrls('Check out **https://example.com/subpath** for details')- expect(result).toEqual(['https://example.com/subpath'])- })-- it('should return empty array when no URLs are found', () => {- const result = extractUrls('This is just plain text with no URLs')- expect(result).toEqual([])- })-- it('should return empty array for empty string', () => {- const result = extractUrls('')- expect(result).toEqual([])- })-- it('should handle URLs in parentheses', () => {- const result = extractUrls('Check out (https://example.com) for details')- expect(result).toEqual(['https://example.com'])- })-- it('should be case insensitive for protocol', () => {- const result = extractUrls('Visit HTTP://EXAMPLE.COM and HTTPS://SUPABASE.COM')- expect(result).toEqual(['HTTP://EXAMPLE.COM', 'HTTPS://SUPABASE.COM'])- })-- it('should handle URLs with special characters in path', () => {- const result = extractUrls('Visit https://example.com/path_with_underscores/file-name.txt')- expect(result).toEqual(['https://example.com/path_with_underscores/file-name.txt'])- })-- it('should handle URLs with encoded characters', () => {- const result = extractUrls('Visit https://example.com/search?q=hello%20world')- expect(result).toEqual(['https://example.com/search?q=hello%20world'])- })-- it('should handle URLs with subdomains', () => {- const result = extractUrls('Visit https://www.example.com and https://api.example.com')- expect(result).toEqual(['https://www.example.com', 'https://api.example.com'])+ it.each([+ ['http URLs', 'Visit http://example.com for more info', ['http://example.com']],+ ['URLs with ports', 'Connect to http://localhost:3000', ['http://localhost:3000']],+ [+ 'URLs with paths, query params, and fragments',+ 'Check https://example.com/api/v1/users?id=123&name=test#details',+ ['https://example.com/api/v1/users?id=123&name=test#details'],+ ],+ [+ 'URLs with special and encoded characters',+ 'Visit https://example.com/path_with_underscores/file-name.txt?q=hello%20world',+ ['https://example.com/path_with_underscores/file-name.txt?q=hello%20world'],+ ],+ [+ 'multiple URLs with subdomains',+ 'Visit http://www.example.com and https://api.supabase.com for more info',+ ['http://www.example.com', 'https://api.supabase.com'],+ ],+ ['URLs without trailing punctuation', 'Check https://example.com!!!', ['https://example.com']],+ [+ 'URLs with trailing commas and periods',+ 'Visit https://example.com, and https://supabase.com.',+ ['https://example.com', 'https://supabase.com'],+ ],+ ['URLs in parentheses', 'Check out (https://example.com) for details', ['https://example.com']],+ [+ 'URLs wrapped in markdown bold',+ 'Check out **https://example.com/subpath** for details',+ ['https://example.com/subpath'],+ ],+ [+ 'URLs with an uppercase protocol',+ 'Visit HTTP://EXAMPLE.COM and HTTPS://SUPABASE.COM',+ ['HTTP://EXAMPLE.COM', 'HTTPS://SUPABASE.COM'],+ ],+ ['nothing from plain text', 'This is just plain text with no URLs', []],+ ['nothing from an empty string', '', []],+ ])('should extract %s', (_, text, expected) => {+ expect(extractUrls(text)).toEqual(expected)})describe('with excludeCodeBlocks option', () => {diff --git a/apps/studio/lib/internal-url.test.ts b/apps/studio/lib/internal-url.test.tsindex 19f74243487..881c370988f 100644--- a/apps/studio/lib/internal-url.test.ts+++ b/apps/studio/lib/internal-url.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { afterEach, describe, expect, it, vi } from 'vitest'import { splitInternalUrl } from './internal-url'diff --git a/apps/studio/lib/isNonNullable.test.ts b/apps/studio/lib/isNonNullable.test.tsindex 77a61dae561..6c49d0d7937 100644--- a/apps/studio/lib/isNonNullable.test.ts+++ b/apps/studio/lib/isNonNullable.test.ts@@ -16,7 +16,6 @@ describe(`isNonNullable`, () => {[``, true],[NaN, true],[0, true],- [0, true],[false, true],// Type coercion[[], true],diff --git a/apps/studio/lib/local-storage.test.ts b/apps/studio/lib/local-storage.test.tsindex 0a0bb58bcad..748a8b37fce 100644--- a/apps/studio/lib/local-storage.test.ts+++ b/apps/studio/lib/local-storage.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { clearLocalStorage, LOCAL_STORAGE_KEYS } from 'common'import { describe, expect, it } from 'vitest'diff --git a/apps/studio/lib/migration-utils.test.ts b/apps/studio/lib/migration-utils.test.tsindex a23a71913d2..c575d7de1b9 100644--- a/apps/studio/lib/migration-utils.test.ts+++ b/apps/studio/lib/migration-utils.test.ts@@ -20,41 +20,12 @@ describe('parseMigrationVersion', () => {expect(result?.second()).toBe(0)})- it('should return undefined for invalid version format like "001"', () => {- const result = parseMigrationVersion('001')-- expect(result).toBeUndefined()- })-- it('should return undefined for invalid version format like "002"', () => {- const result = parseMigrationVersion('002')-- expect(result).toBeUndefined()- })-- it('should return undefined for invalid version format like "003"', () => {- const result = parseMigrationVersion('003')-- expect(result).toBeUndefined()- })-- it('should return undefined for empty string', () => {- const result = parseMigrationVersion('')-- expect(result).toBeUndefined()- })-- it('should return undefined for random string', () => {- const result = parseMigrationVersion('not-a-date')-- expect(result).toBeUndefined()- })-- it('should return undefined for partial date format', () => {- const result = parseMigrationVersion('20231128')-- expect(result).toBeUndefined()- })+ it.each(['001', '002', '', 'not-a-date', '20231128'])(+ 'should return undefined for invalid version %o',+ (version) => {+ expect(parseMigrationVersion(version)).toBeUndefined()+ }+ )it('should handle edge case date values that dayjs can parse', () => {// dayjs is lenient and will wrap invalid values to valid dates@@ -66,14 +37,6 @@ describe('parseMigrationVersion', () => {expect(result?.isValid()).toBe(true)})- it('should allow chaining dayjs methods when valid', () => {- const result = parseMigrationVersion('20231128095400')-- expect(result?.fromNow()).toBeDefined()- expect(result?.toISOString()).toBeDefined()- expect(result?.format('DD MMM YYYY')).toBe('28 Nov 2023')- })-it('should parse version digits as UTC so the UTC time is preserved exactly', () => {// Migration versions are stored as UTC in the DB. Parsing without UTC mode// would shift the time by the viewer's local offset, showing wrong UTC values.diff --git a/apps/studio/lib/navigation.test.ts b/apps/studio/lib/navigation.test.tsindex 80817f6c70e..b6c791a17d2 100644--- a/apps/studio/lib/navigation.test.ts+++ b/apps/studio/lib/navigation.test.ts@@ -1,230 +1,82 @@+// @vitest-environment jsdomimport { beforeEach, describe, expect, it, vi } from 'vitest'import { createNavigationHandler } from './navigation'+type NavigationEvent = Parameters<ReturnType<typeof createNavigationHandler>>[0]+type Outcome = 'push' | 'new-tab' | 'none'+describe('createNavigationHandler', () => {- let mockRouter: any- let mockWindowOpen: any+ const URL = '/project/123/settings'+ const router = { push: vi.fn() }+ const windowOpen = vi.fn()beforeEach(() => {- // Mock router with push method- mockRouter = {- push: vi.fn(),- }-- // Mock window.open- mockWindowOpen = vi.fn()- global.window.open = mockWindowOpen+ router.push.mockReset()+ windowOpen.mockReset()+ global.window.open = windowOpen})- describe('keyboard navigation', () => {- it('should call router.push when Enter key is pressed without modifiers', () => {- const handler = createNavigationHandler('/test-url', mockRouter)- const event = {- key: 'Enter',- metaKey: false,- ctrlKey: false,- preventDefault: vi.fn(),- } as unknown as React.KeyboardEvent-- handler(event)-- expect(event.preventDefault).toHaveBeenCalled()- expect(mockRouter.push).toHaveBeenCalledWith('/test-url')- expect(mockWindowOpen).not.toHaveBeenCalled()- })-- it('should call router.push when Space key is pressed without modifiers', () => {- const handler = createNavigationHandler('/test-url', mockRouter)- const event = {- key: ' ',- metaKey: false,- ctrlKey: false,- preventDefault: vi.fn(),- } as unknown as React.KeyboardEvent-- handler(event)-- expect(event.preventDefault).toHaveBeenCalled()- expect(mockRouter.push).toHaveBeenCalledWith('/test-url')- expect(mockWindowOpen).not.toHaveBeenCalled()- })-- it('should open new tab when Enter key is pressed with metaKey', () => {- const handler = createNavigationHandler('/test-url', mockRouter)- const event = {- key: 'Enter',- metaKey: true,- ctrlKey: false,- preventDefault: vi.fn(),- } as unknown as React.KeyboardEvent-- handler(event)-- expect(event.preventDefault).toHaveBeenCalled()- expect(mockWindowOpen).toHaveBeenCalledWith('/test-url', '_blank')- expect(mockRouter.push).not.toHaveBeenCalled()- })-- it('should open new tab when Enter key is pressed with ctrlKey', () => {- const handler = createNavigationHandler('/test-url', mockRouter)- const event = {- key: 'Enter',- metaKey: false,- ctrlKey: true,- preventDefault: vi.fn(),- } as unknown as React.KeyboardEvent-- handler(event)-- expect(event.preventDefault).toHaveBeenCalled()- expect(mockWindowOpen).toHaveBeenCalledWith('/test-url', '_blank')- expect(mockRouter.push).not.toHaveBeenCalled()- })-- it('should open new tab when Space key is pressed with metaKey', () => {- const handler = createNavigationHandler('/test-url', mockRouter)- const event = {- key: ' ',- metaKey: true,- ctrlKey: false,- preventDefault: vi.fn(),- } as unknown as React.KeyboardEvent-- handler(event)-- expect(event.preventDefault).toHaveBeenCalled()- expect(mockWindowOpen).toHaveBeenCalledWith('/test-url', '_blank')- expect(mockRouter.push).not.toHaveBeenCalled()- })-- it('should do nothing when other keys are pressed', () => {- const handler = createNavigationHandler('/test-url', mockRouter)- const event = {- key: 'a',- metaKey: false,- ctrlKey: false,- preventDefault: vi.fn(),- } as unknown as React.KeyboardEvent-- handler(event)-- expect(event.preventDefault).not.toHaveBeenCalled()- expect(mockRouter.push).not.toHaveBeenCalled()- expect(mockWindowOpen).not.toHaveBeenCalled()- })+ const run = (event: Record<string, unknown>) => {+ const preventDefault = vi.fn()+ const handler = createNavigationHandler(+ URL,+ router as unknown as Parameters<typeof createNavigationHandler>[1]+ )+ handler({+ metaKey: false,+ ctrlKey: false,+ preventDefault,+ ...event,+ } as unknown as NavigationEvent)+ return { preventDefault }+ }++ const expectOutcome = (outcome: Outcome) => {+ if (outcome === 'push') {+ expect(router.push).toHaveBeenCalledWith(URL)+ } else {+ expect(router.push).not.toHaveBeenCalled()+ }+ if (outcome === 'new-tab') {+ expect(windowOpen).toHaveBeenCalledWith(URL, '_blank')+ } else {+ expect(windowOpen).not.toHaveBeenCalled()+ }+ }++ it.each<[string, Record<string, unknown>, Outcome]>([+ ['Enter', { key: 'Enter' }, 'push'],+ ['Space', { key: ' ' }, 'push'],+ ['Cmd + Enter', { key: 'Enter', metaKey: true }, 'new-tab'],+ ['Ctrl + Enter', { key: 'Enter', ctrlKey: true }, 'new-tab'],+ ['Cmd + Space', { key: ' ', metaKey: true }, 'new-tab'],+ ])('handles %s by preventing default and navigating', (_, event, outcome) => {+ const { preventDefault } = run(event)++ expect(preventDefault).toHaveBeenCalled()+ expectOutcome(outcome)})- describe('mouse navigation', () => {- it('should call router.push on regular left click', () => {- const handler = createNavigationHandler('/test-url', mockRouter)- const event = {- button: 0,- metaKey: false,- ctrlKey: false,- preventDefault: vi.fn(),- } as unknown as React.MouseEvent-- handler(event)-- expect(mockRouter.push).toHaveBeenCalledWith('/test-url')- expect(mockWindowOpen).not.toHaveBeenCalled()- })-- it('should open new tab on middle mouse button click', () => {- const handler = createNavigationHandler('/test-url', mockRouter)- const event = {- button: 1, // Middle button- metaKey: false,- ctrlKey: false,- preventDefault: vi.fn(),- } as unknown as React.MouseEvent-- handler(event)-- expect(event.preventDefault).toHaveBeenCalled()- expect(mockWindowOpen).toHaveBeenCalledWith('/test-url', '_blank')- expect(mockRouter.push).not.toHaveBeenCalled()- })-- it('should open new tab on Cmd + left click', () => {- const handler = createNavigationHandler('/test-url', mockRouter)- const event = {- button: 0,- metaKey: true,- ctrlKey: false,- preventDefault: vi.fn(),- } as unknown as React.MouseEvent-- handler(event)-- expect(event.preventDefault).toHaveBeenCalled()- expect(mockWindowOpen).toHaveBeenCalledWith('/test-url', '_blank')- expect(mockRouter.push).not.toHaveBeenCalled()- })+ it('ignores other keys', () => {+ const { preventDefault } = run({ key: 'a' })- it('should open new tab on Ctrl + left click', () => {- const handler = createNavigationHandler('/test-url', mockRouter)- const event = {- button: 0,- metaKey: false,- ctrlKey: true,- preventDefault: vi.fn(),- } as unknown as React.MouseEvent-- handler(event)-- expect(event.preventDefault).toHaveBeenCalled()- expect(mockWindowOpen).toHaveBeenCalledWith('/test-url', '_blank')- expect(mockRouter.push).not.toHaveBeenCalled()- })-- it('should handle right click without navigation', () => {- const handler = createNavigationHandler('/test-url', mockRouter)- const event = {- button: 2, // Right button- metaKey: false,- ctrlKey: false,- preventDefault: vi.fn(),- } as unknown as React.MouseEvent-- handler(event)-- // Right click opens the context menu, so it must not navigate.- expect(mockRouter.push).not.toHaveBeenCalled()- expect(mockWindowOpen).not.toHaveBeenCalled()- })+ expect(preventDefault).not.toHaveBeenCalled()+ expectOutcome('none')})- describe('URL handling', () => {- it('should handle URLs with BASE_PATH correctly', () => {- const handler = createNavigationHandler('/project/123/settings', mockRouter)- const event = {- button: 1, // Middle button to open in new tab- metaKey: false,- ctrlKey: false,- preventDefault: vi.fn(),- } as unknown as React.MouseEvent-- handler(event)-- // Should prepend BASE_PATH when opening new tab- expect(mockWindowOpen).toHaveBeenCalledWith('/project/123/settings', '_blank')- })-- it('should pass URL directly to router.push without BASE_PATH', () => {- const handler = createNavigationHandler('/project/123/settings', mockRouter)- const event = {- button: 0,- metaKey: false,- ctrlKey: false,- preventDefault: vi.fn(),- } as unknown as React.MouseEvent-- handler(event)-- // router.push should receive URL without BASE_PATH- expect(mockRouter.push).toHaveBeenCalledWith('/project/123/settings')- })+ it.each<[string, Record<string, unknown>, Outcome]>([+ ['a regular left click', { button: 0 }, 'push'],+ ['a middle click', { button: 1 }, 'new-tab'],+ ['Cmd + left click', { button: 0, metaKey: true }, 'new-tab'],+ ['Ctrl + left click', { button: 0, ctrlKey: true }, 'new-tab'],+ // Right click opens the context menu, so it must not navigate.+ ['a right click', { button: 2 }, 'none'],+ ])('handles %s', (_, event, outcome) => {+ const { preventDefault } = run(event)++ expectOutcome(outcome)+ // New-tab clicks must not also trigger the browser's default navigation+ if (outcome === 'new-tab') expect(preventDefault).toHaveBeenCalled()})})diff --git a/apps/studio/lib/project-transition-state.test.ts b/apps/studio/lib/project-transition-state.test.tsindex 9603bfc05c8..7a1df5b9d52 100644--- a/apps/studio/lib/project-transition-state.test.ts+++ b/apps/studio/lib/project-transition-state.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { beforeEach, describe, expect, it } from 'vitest'import {diff --git a/apps/studio/lib/semver.test.ts b/apps/studio/lib/semver.test.tsindex 026c6032987..46e19858e1f 100644--- a/apps/studio/lib/semver.test.ts+++ b/apps/studio/lib/semver.test.ts@@ -79,11 +79,6 @@ describe('compareSemver', () => {expect(compareSemver('invalid', '1.2.3')).toBeNull()})- it('should prioritize major version differences', () => {- expect(compareSemver('2.0.0', '1.99.99')).toBe(1)- expect(compareSemver('1.99.99', '2.0.0')).toBe(-1)- })-it('should prioritize minor version differences when major is equal', () => {expect(compareSemver('1.3.0', '1.2.99')).toBe(1)expect(compareSemver('1.2.99', '1.3.0')).toBe(-1)diff --git a/apps/studio/lib/sentry-client-options.test.ts b/apps/studio/lib/sentry-client-options.test.tsindex 9d7cd231996..969d3af80a6 100644--- a/apps/studio/lib/sentry-client-options.test.ts+++ b/apps/studio/lib/sentry-client-options.test.ts@@ -11,45 +11,6 @@ import {describe('Sentry beforeSend filtering functions', () => {describe('isBrowserWalletExtensionError', () => {- it('returns true for Gate.io wallet extension error (gt-window-provider.js)', () => {- const event: SentryEvent = {- exception: {- values: [- {- type: 'TypeError',- value: 'en.shouldSetTallyForCurrentProvider is not a function',- stacktrace: {- frames: [- { filename: 'app:///_next/static/chunks/main.js' } as StackFrame,- { filename: 'app:///gt-window-provider.js' } as StackFrame,- ],- },- },- ],- },- }-- expect(isBrowserWalletExtensionError(event)).toBe(true)- })-- it('returns true for Gate.io BTC wallet extension error (gt-window-provider-btc.js)', () => {- const event: SentryEvent = {- exception: {- values: [- {- type: 'TypeError',- value: 'f.shouldSetTallyForCurrentProvider is not a function',- stacktrace: {- frames: [{ filename: 'app:///gt-window-provider-btc.js' } as StackFrame],- },- },- ],- },- }-- expect(isBrowserWalletExtensionError(event)).toBe(true)- })-it('returns true for wallet-provider in abs_path', () => {const event: SentryEvent = {exception: {@@ -121,32 +82,15 @@ describe('Sentry beforeSend filtering functions', () => {})describe('isUserAbortedOperation', () => {- it('returns true for "operation was aborted" error', () => {- const error = new Error('The operation was aborted.')- const event: SentryEvent = {}-- expect(isUserAbortedOperation(error, event)).toBe(true)- })-- it('returns true for "signal is aborted" error', () => {- const error = new Error('signal is aborted without reason')- const event: SentryEvent = {}-- expect(isUserAbortedOperation(error, event)).toBe(true)- })-- it('returns true for "manually canceled" error', () => {- const error = new Error('operation is manually canceled')- const event: SentryEvent = {}-- expect(isUserAbortedOperation(error, event)).toBe(true)- })-- it('returns true for "AbortError" message', () => {- const error = new Error('AbortError: The operation was aborted')- const event: SentryEvent = {}-- expect(isUserAbortedOperation(error, event)).toBe(true)+ it.each([+ // SUPABASE-APP-BG6+ 'The operation was aborted.',+ // SUPABASE-APP-BG7+ 'signal is aborted without reason',+ 'operation is manually canceled',+ 'AbortError: The operation was aborted',+ ])('returns true for an error with message %o', (message) => {+ expect(isUserAbortedOperation(new Error(message), {})).toBe(true)})it('returns true when message is in event.message (no error object)', () => {@@ -358,26 +302,6 @@ describe('Sentry beforeSend filtering functions', () => {expect(isBrowserWalletExtensionError(event)).toBe(true)})- it('correctly identifies SUPABASE-APP-BG6 pattern (user aborted)', () => {- // Based on actual Sentry issue SUPABASE-APP-BG6- const error = new Error('The operation was aborted.')- const event: SentryEvent = {- message: '[CRITICAL][sign in via EP] Failed: The operation was aborted.',- }-- expect(isUserAbortedOperation(error, event)).toBe(true)- })-- it('correctly identifies SUPABASE-APP-BG7 pattern (signal aborted)', () => {- // Based on actual Sentry issue SUPABASE-APP-BG7- const error = new Error('signal is aborted without reason')- const event: SentryEvent = {- message: '[CRITICAL][sign in via EP] Failed: signal is aborted without reason',- }-- expect(isUserAbortedOperation(error, event)).toBe(true)- })-it('correctly identifies SUPABASE-APP-ACC pattern (challenge expired)', () => {// Based on actual Sentry issue SUPABASE-APP-ACCconst error = new Error('Non-Error promise rejection captured with value: challenge-expired')diff --git a/apps/studio/lib/session-replay.test.ts b/apps/studio/lib/session-replay.test.tsindex ee4c3083285..035214e991b 100644--- a/apps/studio/lib/session-replay.test.ts+++ b/apps/studio/lib/session-replay.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { buildSessionRecordingConfig, type CapturedNetworkRequest } from 'common'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -450,12 +451,6 @@ describe('maskReplayAttribute', () => {expect(maskReplayAttribute('_cssText', checkbox)).toBe(checkbox)})- it('still masks url() in an inline style attribute', () => {- expect(maskReplayAttribute('style', 'background-image: url("https://x.test/secret.png")')).toBe(- 'background-image: url(*)'- )- })-it('keeps the SVG namespace exemption to id only', () => {const svgAnchor = document.createElementNS('http://www.w3.org/2000/svg', 'a')expect(maskReplayAttribute('href', 'https://x.test/secret', svgAnchor)).toBe('*')@@ -500,31 +495,23 @@ describe('maskReplayNetworkRequest', () => {})describe('SESSION_REPLAY_CONFIG', () => {- it('masks all text and inputs', () => {- expect(SESSION_REPLAY_CONFIG.maskTextSelector).toBe('*')- expect(SESSION_REPLAY_CONFIG.maskAllInputs).toBe(true)- expect(SESSION_REPLAY_CONFIG.maskTextFn).toBe(maskReplayText)- })-- it('never records request or response payloads', () => {- expect(SESSION_REPLAY_CONFIG.recordHeaders).toBe(false)- expect(SESSION_REPLAY_CONFIG.recordBody).toBe(false)- })-- it('never records canvas, which text masking cannot reach', () => {- expect(SESSION_REPLAY_CONFIG.captureCanvas).toEqual({ recordCanvas: false })- })-- it('strips sensitive URL parts via maskReplayNetworkRequest', () => {- expect(SESSION_REPLAY_CONFIG.maskCapturedNetworkRequestFn).toBe(maskReplayNetworkRequest)- })-- it('masks attributes, which maskTextFn cannot reach', () => {- expect(SESSION_REPLAY_CONFIG.maskAttributeFn).toBe(maskReplayAttribute)- })-- it('pins maskAllElementAttributes off, since true would discard maskAttributeFn', () => {- expect(SESSION_REPLAY_CONFIG.maskAllElementAttributes).toBe(false)+ it('pins the privacy-relevant recording options', () => {+ expect(SESSION_REPLAY_CONFIG).toMatchObject({+ // Mask all text and inputs+ maskTextSelector: '*',+ maskAllInputs: true,+ maskTextFn: maskReplayText,+ // Attributes are masked separately, since maskTextFn cannot reach them. `true` for+ // maskAllElementAttributes would discard maskAttributeFn.+ maskAttributeFn: maskReplayAttribute,+ maskAllElementAttributes: false,+ // Never record request or response payloads; strip sensitive URL parts+ recordHeaders: false,+ recordBody: false,+ maskCapturedNetworkRequestFn: maskReplayNetworkRequest,+ // Never record canvas, which text masking cannot reach+ captureCanvas: { recordCanvas: false },+ })})})@@ -536,13 +523,6 @@ describe('buildSessionRecordingConfig', () => {expect(config).not.toHaveProperty('session_recording')})- it('disables recording when the policy is undefined', () => {- const config = buildSessionRecordingConfig(undefined)-- expect(config.disable_session_recording).toBe(true)- expect(config).not.toHaveProperty('session_recording')- })-it('enables recording and forwards the policy when given one', () => {const config = buildSessionRecordingConfig(SESSION_REPLAY_CONFIG)diff --git a/apps/studio/lib/sql-event-parser.test.ts b/apps/studio/lib/sql-event-parser.test.tsindex 7cb18459faa..cbd24388974 100644--- a/apps/studio/lib/sql-event-parser.test.ts+++ b/apps/studio/lib/sql-event-parser.test.ts@@ -4,326 +4,72 @@ import { describe, expect, it } from 'vitest'import { sqlEventParser } from './sql-event-parser'describe('SQL Event Parser', () => {- describe('CREATE TABLE detection', () => {- it('detects basic CREATE TABLE', () => {- const results = sqlEventParser.getTableEvents('CREATE TABLE users (id INT PRIMARY KEY)')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: undefined,- tableName: 'users',- })- })-- it('detects CREATE TABLE with schema', () => {- const results = sqlEventParser.getTableEvents('CREATE TABLE public.users (id INT)')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: 'public',- tableName: 'users',- })- })-- it('detects CREATE TABLE IF NOT EXISTS', () => {- const results = sqlEventParser.getTableEvents('CREATE TABLE IF NOT EXISTS users (id INT)')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: undefined,- tableName: 'users',- })- })-- it('handles quoted identifiers', () => {- const results = sqlEventParser.getTableEvents('CREATE TABLE "public"."user_table" (id INT)')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: 'public',- tableName: 'user_table',- })- })-- it('returns empty array for non-matching SQL', () => {- const results = sqlEventParser.getTableEvents('SELECT * FROM users')- expect(results).toHaveLength(0)- })-- it('detects CREATE TEMPORARY TABLE', () => {- const results = sqlEventParser.getTableEvents('CREATE TEMPORARY TABLE temp_users (id INT)')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: undefined,- tableName: 'temp_users',- })- })-- it('detects CREATE TEMP TABLE', () => {- const results = sqlEventParser.getTableEvents('CREATE TEMP TABLE temp_users (id INT)')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: undefined,- tableName: 'temp_users',- })- })-- it('detects CREATE UNLOGGED TABLE', () => {- const results = sqlEventParser.getTableEvents('CREATE UNLOGGED TABLE fast_table (id INT)')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: undefined,- tableName: 'fast_table',- })- })-- it('detects CREATE TEMP TABLE IF NOT EXISTS', () => {- const results = sqlEventParser.getTableEvents(- 'CREATE TEMP TABLE IF NOT EXISTS temp_users (id INT)'- )- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: undefined,- tableName: 'temp_users',- })- })- })-- describe('INSERT detection', () => {- it('detects basic INSERT INTO', () => {- const results = sqlEventParser.getTableEvents("INSERT INTO users (name) VALUES ('John')")- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableDataAdded,- schema: undefined,- tableName: 'users',- })- })-- it('detects INSERT with schema', () => {- const results = sqlEventParser.getTableEvents(- "INSERT INTO public.users (name) VALUES ('John')"- )- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableDataAdded,- schema: 'public',- tableName: 'users',- })- })-- it('handles quoted identifiers', () => {- const results = sqlEventParser.getTableEvents('INSERT INTO "auth"."users" (id) VALUES (1)')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableDataAdded,- schema: 'auth',- tableName: 'users',- })- })-- it('returns empty array for non-matching SQL', () => {- const results = sqlEventParser.getTableEvents('UPDATE users SET name = "John"')- expect(results).toHaveLength(0)- })- })-- describe('COPY detection', () => {- it('detects basic COPY FROM', () => {- const results = sqlEventParser.getTableEvents("COPY users FROM '/tmp/users.csv'")- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableDataAdded,- schema: undefined,- tableName: 'users',- })- })-- it('detects COPY with schema', () => {- const results = sqlEventParser.getTableEvents(- "COPY public.users FROM '/tmp/users.csv' WITH CSV HEADER"- )- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableDataAdded,- schema: 'public',- tableName: 'users',- })- })-- it('handles quoted identifiers', () => {- const results = sqlEventParser.getTableEvents('COPY "auth"."users" FROM STDIN')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableDataAdded,- schema: 'auth',- tableName: 'users',- })- })-- it('returns empty array for COPY TO', () => {- const results = sqlEventParser.getTableEvents("COPY users TO '/tmp/users.csv'")- expect(results).toHaveLength(0)- })-- it('returns empty array for non-matching SQL', () => {- const results = sqlEventParser.getTableEvents('SELECT * FROM users')- expect(results).toHaveLength(0)- })+ const { TableCreated, TableDataAdded, TableRLSEnabled } = TABLE_EVENT_ACTIONS++ it.each([+ // CREATE TABLE+ ['CREATE TABLE users (id INT PRIMARY KEY)', TableCreated, undefined, 'users'],+ ['CREATE TABLE public.users (id INT)', TableCreated, 'public', 'users'],+ ['CREATE TABLE IF NOT EXISTS users (id INT)', TableCreated, undefined, 'users'],+ ['CREATE TABLE "public"."user_table" (id INT)', TableCreated, 'public', 'user_table'],+ ['CREATE TEMPORARY TABLE temp_users (id INT)', TableCreated, undefined, 'temp_users'],+ ['CREATE TEMP TABLE temp_users (id INT)', TableCreated, undefined, 'temp_users'],+ ['CREATE UNLOGGED TABLE fast_table (id INT)', TableCreated, undefined, 'fast_table'],+ ['CREATE TEMP TABLE IF NOT EXISTS temp_users (id INT)', TableCreated, undefined, 'temp_users'],+ ['CREATE TABLE table123 (id INT)', TableCreated, undefined, 'table123'],+ // INSERT+ ["INSERT INTO users (name) VALUES ('John')", TableDataAdded, undefined, 'users'],+ ["INSERT INTO public.users (name) VALUES ('John')", TableDataAdded, 'public', 'users'],+ ['INSERT INTO "auth"."users" (id) VALUES (1)', TableDataAdded, 'auth', 'users'],+ // COPY ... FROM+ ["COPY users FROM '/tmp/users.csv'", TableDataAdded, undefined, 'users'],+ ["COPY public.users FROM '/tmp/users.csv' WITH CSV HEADER", TableDataAdded, 'public', 'users'],+ ['COPY "auth"."users" FROM STDIN', TableDataAdded, 'auth', 'users'],+ // SELECT INTO / CREATE TABLE AS+ ['SELECT * INTO new_users FROM users', TableCreated, undefined, 'new_users'],+ ['SELECT id, name INTO public.new_users FROM users', TableCreated, 'public', 'new_users'],+ ['SELECT * INTO "backup"."users_2024" FROM users', TableCreated, 'backup', 'users_2024'],+ ['CREATE TABLE new_users AS SELECT * FROM users', TableCreated, undefined, 'new_users'],+ [+ 'CREATE TABLE IF NOT EXISTS new_users AS SELECT * FROM users WHERE active = true',+ TableCreated,+ undefined,+ 'new_users',+ ],+ // RLS+ ['ALTER TABLE users ENABLE ROW LEVEL SECURITY', TableRLSEnabled, undefined, 'users'],+ ['ALTER TABLE users ENABLE RLS', TableRLSEnabled, undefined, 'users'],+ ['ALTER TABLE public.users ENABLE ROW LEVEL SECURITY', TableRLSEnabled, 'public', 'users'],+ [+ 'ALTER TABLE users ADD COLUMN test INT, ENABLE ROW LEVEL SECURITY',+ TableRLSEnabled,+ undefined,+ 'users',+ ],+ [+ 'ALTER TABLE IF EXISTS public."Conversations" ENABLE ROW LEVEL SECURITY',+ TableRLSEnabled,+ 'public',+ 'Conversations',+ ],+ ['ALTER TABLE ONLY public.users ENABLE ROW LEVEL SECURITY', TableRLSEnabled, 'public', 'users'],+ [+ 'ALTER TABLE IF EXISTS ONLY public.users ENABLE ROW LEVEL SECURITY',+ TableRLSEnabled,+ 'public',+ 'users',+ ],+ ])('detects %s', (sql, type, schema, tableName) => {+ expect(sqlEventParser.getTableEvents(sql)).toEqual([{ type, schema, tableName }])})- describe('SELECT INTO detection', () => {- it('detects SELECT INTO', () => {- const results = sqlEventParser.getTableEvents('SELECT * INTO new_users FROM users')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: undefined,- tableName: 'new_users',- })- })-- it('detects SELECT INTO with schema', () => {- const results = sqlEventParser.getTableEvents(- 'SELECT id, name INTO public.new_users FROM users'- )- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: 'public',- tableName: 'new_users',- })- })-- it('detects CREATE TABLE AS SELECT', () => {- const results = sqlEventParser.getTableEvents('CREATE TABLE new_users AS SELECT * FROM users')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: undefined,- tableName: 'new_users',- })- })-- it('detects CREATE TABLE IF NOT EXISTS AS SELECT', () => {- const results = sqlEventParser.getTableEvents(- 'CREATE TABLE IF NOT EXISTS new_users AS SELECT * FROM users WHERE active = true'- )- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: undefined,- tableName: 'new_users',- })- })-- it('handles quoted identifiers', () => {- const results = sqlEventParser.getTableEvents(- 'SELECT * INTO "backup"."users_2024" FROM users'- )- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: 'backup',- tableName: 'users_2024',- })- })-- it('returns empty array for regular SELECT', () => {- const results = sqlEventParser.getTableEvents('SELECT * FROM users')- expect(results).toHaveLength(0)- })- })-- describe('RLS detection', () => {- it('detects ALTER TABLE ENABLE ROW LEVEL SECURITY', () => {- const results = sqlEventParser.getTableEvents('ALTER TABLE users ENABLE ROW LEVEL SECURITY')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableRLSEnabled,- schema: undefined,- tableName: 'users',- })- })-- it('detects short form ENABLE RLS', () => {- const results = sqlEventParser.getTableEvents('ALTER TABLE users ENABLE RLS')- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableRLSEnabled,- schema: undefined,- tableName: 'users',- })- })-- it('detects with schema', () => {- const results = sqlEventParser.getTableEvents(- 'ALTER TABLE public.users ENABLE ROW LEVEL SECURITY'- )- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableRLSEnabled,- schema: 'public',- tableName: 'users',- })- })-- it('handles other ALTER TABLE statements in between', () => {- const results = sqlEventParser.getTableEvents(- 'ALTER TABLE users ADD COLUMN test INT, ENABLE ROW LEVEL SECURITY'- )- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableRLSEnabled,- schema: undefined,- tableName: 'users',- })- })-- it('returns empty array for disabling RLS', () => {- const results = sqlEventParser.getTableEvents('ALTER TABLE users DISABLE ROW LEVEL SECURITY')- expect(results).toHaveLength(0)- })-- it('detects ALTER TABLE IF EXISTS ENABLE ROW LEVEL SECURITY', () => {- const results = sqlEventParser.getTableEvents(- 'ALTER TABLE IF EXISTS public."Conversations" ENABLE ROW LEVEL SECURITY'- )- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableRLSEnabled,- schema: 'public',- tableName: 'Conversations',- })- })-- it('detects ALTER TABLE ONLY ENABLE ROW LEVEL SECURITY', () => {- const results = sqlEventParser.getTableEvents(- 'ALTER TABLE ONLY public.users ENABLE ROW LEVEL SECURITY'- )- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableRLSEnabled,- schema: 'public',- tableName: 'users',- })- })-- it('detects ALTER TABLE IF EXISTS ONLY ENABLE ROW LEVEL SECURITY', () => {- const results = sqlEventParser.getTableEvents(- 'ALTER TABLE IF EXISTS ONLY public.users ENABLE ROW LEVEL SECURITY'- )- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableRLSEnabled,- schema: 'public',- tableName: 'users',- })- })+ it.each([+ 'SELECT * FROM users',+ 'UPDATE users SET name = "John"',+ "COPY users TO '/tmp/users.csv'",+ 'ALTER TABLE users DISABLE ROW LEVEL SECURITY',+ ])('returns no events for %s', (sql) => {+ expect(sqlEventParser.getTableEvents(sql)).toEqual([])})describe('ReDoS protection', () => {@@ -408,28 +154,6 @@ describe('SQL Event Parser', () => {expect(results).toHaveLength(0)})- it('handles identifiers with numbers', () => {- const sql = 'CREATE TABLE table123 (id INT)'- const results = sqlEventParser.getTableEvents(sql)- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: undefined,- tableName: 'table123',- })- })-- it('handles identifiers with underscores', () => {- const sql = 'CREATE TABLE user_accounts (id INT)'- const results = sqlEventParser.getTableEvents(sql)- expect(results).toHaveLength(1)- expect(results[0]).toEqual({- type: TABLE_EVENT_ACTIONS.TableCreated,- schema: undefined,- tableName: 'user_accounts',- })- })-it('handles escaped quotes in identifiers', () => {const sql = 'CREATE TABLE "user""table" (id INT)'const results = sqlEventParser.getTableEvents(sql)diff --git a/apps/studio/lib/void.test.ts b/apps/studio/lib/void.test.tsdeleted file mode 100644index 2ad837d9ed8..00000000000--- a/apps/studio/lib/void.test.ts+++ /dev/null@@ -1,31 +0,0 @@-import { describe, expect, it } from 'vitest'--import { EMPTY_ARR, EMPTY_OBJ, noop } from './void'--describe('void utilities', () => {- describe('noop', () => {- it('should return undefined', () => {- expect(noop()).toBeUndefined()- })- })-- describe('EMPTY_OBJ', () => {- it('should always return the same reference', () => {- expect(EMPTY_OBJ).toBe(EMPTY_OBJ)- })-- it('should be an empty object', () => {- expect(Object.keys(EMPTY_OBJ)).toHaveLength(0)- })- })-- describe('EMPTY_ARR', () => {- it('should always return the same reference', () => {- expect(EMPTY_ARR).toBe(EMPTY_ARR)- })-- it('should be an empty array', () => {- expect(EMPTY_ARR).toHaveLength(0)- })- })-})diff --git a/apps/studio/scripts/__tests__/server-source-maps.test.ts b/apps/studio/scripts/__tests__/server-source-maps.test.tsindex 956d7c30afc..9baebc309c2 100644--- a/apps/studio/scripts/__tests__/server-source-maps.test.ts+++ b/apps/studio/scripts/__tests__/server-source-maps.test.ts@@ -189,35 +189,31 @@ describe('server source maps', () => {await expect(plugin.load.call({} as never, codeFile)).rejects.toMatchObject({ code: 'EISDIR' })})+ // Vercel output paths are covered by the build cases below; here only token/skip change the config.it.each([- [false, false, true],- [false, true, true],- [true, false, false],- [true, true, false],- [false, false, false],- [true, false, true],- ])(- 'enables both server stages with token=%s, Vercel=%s, skip=%s',- async (hasToken, isVercel, shouldSkipUpload) => {- const config = await resolveStudioConfig(hasToken, isVercel, shouldSkipUpload)- expect(config.environments.ssr.build.sourcemap).toBe(true)- expect(config.environments.nitro.build.sourcemap).toBe(true)- expect(config.environments.client.build.sourcemap).toBe(- hasToken && !shouldSkipUpload ? 'hidden' : false- )- expect(captured.nitro?.experimental?.sourcemapMinify).toBe(false)- expect(captured.sentry?.sourcemaps?.filesToDeleteAfterUpload).toEqual([- path.join(studioRoot, '.output/public/**/*.map'),- path.join(studioRoot, '.vercel/output/static/**/*.map'),- ...(hasToken && !shouldSkipUpload- ? [- path.join(studioRoot, '.output/server/**/*.map'),- path.join(studioRoot, '.vercel/output/functions/**/*.map'),- ]- : []),- ])- }- )+ [false, true],+ [true, false],+ [false, false],+ [true, true],+ ])('enables both server stages with token=%s, skip=%s', async (hasToken, shouldSkipUpload) => {+ const config = await resolveStudioConfig(hasToken, false, shouldSkipUpload)+ expect(config.environments.ssr.build.sourcemap).toBe(true)+ expect(config.environments.nitro.build.sourcemap).toBe(true)+ expect(config.environments.client.build.sourcemap).toBe(+ hasToken && !shouldSkipUpload ? 'hidden' : false+ )+ expect(captured.nitro?.experimental?.sourcemapMinify).toBe(false)+ expect(captured.sentry?.sourcemaps?.filesToDeleteAfterUpload).toEqual([+ path.join(studioRoot, '.output/public/**/*.map'),+ path.join(studioRoot, '.vercel/output/static/**/*.map'),+ ...(hasToken && !shouldSkipUpload+ ? [+ path.join(studioRoot, '.output/server/**/*.map'),+ path.join(studioRoot, '.vercel/output/functions/**/*.map'),+ ]+ : []),+ ])+ })it.each([[false, false, false],diff --git a/apps/studio/sentry.tanstack.test.ts b/apps/studio/sentry.tanstack.test.tsindex c8d8e3c38f6..ac244caf772 100644--- a/apps/studio/sentry.tanstack.test.ts+++ b/apps/studio/sentry.tanstack.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport type { AnyRouter } from '@tanstack/react-router'import { afterEach, describe, expect, it, vi } from 'vitest'diff --git a/apps/studio/state/ai-assistant-state.notebook-cache-invalidation.test.ts b/apps/studio/state/ai-assistant-state.notebook-cache-invalidation.test.tsindex 8126f6bf928..2f35605c4c3 100644--- a/apps/studio/state/ai-assistant-state.notebook-cache-invalidation.test.ts+++ b/apps/studio/state/ai-assistant-state.notebook-cache-invalidation.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport type { UIMessageChunk } from 'ai'import { convertArrayToReadableStream } from 'ai/test'import { afterEach, describe, expect, it, vi } from 'vitest'diff --git a/apps/studio/state/explorer-query.test.ts b/apps/studio/state/explorer-query.test.tsindex fed32b9a8a1..fd9495eea47 100644--- a/apps/studio/state/explorer-query.test.ts+++ b/apps/studio/state/explorer-query.test.ts@@ -318,47 +318,26 @@ describe('explorer query drafts', () => {}})- it('normalizes a fractional persisted row limit to the default', () => {- const storage = createMemoryStorage()- storage.setItem(- LOCAL_STORAGE_KEYS.EXPLORER_QUERY_DRAFTS('project-a'),- JSON.stringify({- 'query-1': { name: 'Query', sql: 'select 1', updatedAt: 1, rowLimit: 100.5 },- })- )-- const state = createExplorerQueryState(storage)- expect(state.restoreDraft({ id: 'query-1', projectRef: 'project-a' })).toBe(true)- expect(state.drafts['query-1']).toMatchObject({ rowLimit: 100 })- })-- it('normalizes an out-of-range persisted row limit to the default', () => {- const storage = createMemoryStorage()- storage.setItem(- LOCAL_STORAGE_KEYS.EXPLORER_QUERY_DRAFTS('project-a'),- JSON.stringify({- 'query-1': { name: 'Query', sql: 'select 1', updatedAt: 1, rowLimit: 999999 },- })- )-- const state = createExplorerQueryState(storage)- expect(state.restoreDraft({ id: 'query-1', projectRef: 'project-a' })).toBe(true)- expect(state.drafts['query-1']).toMatchObject({ rowLimit: 100 })- })-- it('normalizes a non-numeric persisted row limit to the default without dropping the draft', () => {- const storage = createMemoryStorage()- storage.setItem(- LOCAL_STORAGE_KEYS.EXPLORER_QUERY_DRAFTS('project-a'),- JSON.stringify({- 'query-1': { name: 'Query', sql: 'select 1', updatedAt: 1, rowLimit: 'unlimited' },- })- )+ it.each([+ ['a fractional', 100.5],+ ['an out-of-range', 999999],+ ['a non-numeric', 'unlimited'],+ ])(+ 'normalizes %s persisted row limit to the default without dropping the draft',+ (_, rowLimit) => {+ const storage = createMemoryStorage()+ storage.setItem(+ LOCAL_STORAGE_KEYS.EXPLORER_QUERY_DRAFTS('project-a'),+ JSON.stringify({+ 'query-1': { name: 'Query', sql: 'select 1', updatedAt: 1, rowLimit },+ })+ )- const state = createExplorerQueryState(storage)- expect(state.restoreDraft({ id: 'query-1', projectRef: 'project-a' })).toBe(true)- expect(state.drafts['query-1']).toMatchObject({ rowLimit: 100, uncheckedSql: 'select 1' })- })+ const state = createExplorerQueryState(storage)+ expect(state.restoreDraft({ id: 'query-1', projectRef: 'project-a' })).toBe(true)+ expect(state.drafts['query-1']).toMatchObject({ rowLimit: 100, uncheckedSql: 'select 1' })+ }+ )it('persists and restores a per-draft impersonated role independently of other drafts', () => {const storage = createMemoryStorage()diff --git a/apps/studio/state/notebooks/notebooks-state.test.ts b/apps/studio/state/notebooks/notebooks-state.test.tsindex 68c4f2f23d6..eda2b6e61e2 100644--- a/apps/studio/state/notebooks/notebooks-state.test.ts+++ b/apps/studio/state/notebooks/notebooks-state.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { beforeEach, describe, expect, it } from 'vitest'import { persistNotebookDraft, readNotebookDraft } from './notebook-drafts'diff --git a/apps/studio/state/shortcuts/formatShortcut.test.ts b/apps/studio/state/shortcuts/formatShortcut.test.tsindex 3dc1047db67..474cd2a4c68 100644--- a/apps/studio/state/shortcuts/formatShortcut.test.ts+++ b/apps/studio/state/shortcuts/formatShortcut.test.ts@@ -3,97 +3,37 @@ import { describe, expect, it } from 'vitest'import { hotkeyToKeys } from './formatShortcut'describe('hotkeyToKeys', () => {- describe('single-step hotkeys', () => {- it('returns a single letter key unchanged', () => {- expect(hotkeyToKeys('K')).toEqual(['K'])- })-- it('preserves named keys', () => {- expect(hotkeyToKeys('Enter')).toEqual(['Enter'])- expect(hotkeyToKeys('Escape')).toEqual(['Escape'])- expect(hotkeyToKeys('Tab')).toEqual(['Tab'])- expect(hotkeyToKeys('ArrowUp')).toEqual(['ArrowUp'])- expect(hotkeyToKeys('ArrowDown')).toEqual(['ArrowDown'])- expect(hotkeyToKeys('ArrowLeft')).toEqual(['ArrowLeft'])- expect(hotkeyToKeys('ArrowRight')).toEqual(['ArrowRight'])- })-- it('preserves punctuation keys', () => {- expect(hotkeyToKeys(',')).toEqual([','])- expect(hotkeyToKeys('.')).toEqual(['.'])- expect(hotkeyToKeys('/')).toEqual(['/'])- })- })-- describe('Mod mapping', () => {- it('converts standalone Mod to Meta', () => {- expect(hotkeyToKeys('Mod')).toEqual(['Meta'])- })-- it('converts Mod to Meta when combined with a single key', () => {- expect(hotkeyToKeys('Mod+K')).toEqual(['Meta', 'K'])- })-- it('is case sensitive — only exact "Mod" is converted', () => {- expect(hotkeyToKeys('mod+K')).toEqual(['mod', 'K'])- expect(hotkeyToKeys('MOD+K')).toEqual(['MOD', 'K'])- })-- it('does not rewrite keys that merely contain "Mod" as a substring', () => {- expect(hotkeyToKeys('Model')).toEqual(['Model'])- expect(hotkeyToKeys('Mod+Model')).toEqual(['Meta', 'Model'])- })- })-- describe('modifier combos', () => {- it('handles Mod+Shift combos', () => {- expect(hotkeyToKeys('Mod+Shift+M')).toEqual(['Meta', 'Shift', 'M'])- expect(hotkeyToKeys('Mod+Shift+J')).toEqual(['Meta', 'Shift', 'J'])- expect(hotkeyToKeys('Mod+Shift+C')).toEqual(['Meta', 'Shift', 'C'])- })-- it('preserves modifier order', () => {- expect(hotkeyToKeys('Shift+Mod+K')).toEqual(['Shift', 'Meta', 'K'])- expect(hotkeyToKeys('Alt+Mod+K')).toEqual(['Alt', 'Meta', 'K'])- })-- it('leaves Ctrl, Alt, Shift, Meta literals untouched', () => {- expect(hotkeyToKeys('Ctrl+K')).toEqual(['Ctrl', 'K'])- expect(hotkeyToKeys('Alt+K')).toEqual(['Alt', 'K'])- expect(hotkeyToKeys('Shift+K')).toEqual(['Shift', 'K'])- expect(hotkeyToKeys('Meta+K')).toEqual(['Meta', 'K'])- })-- it('handles three-modifier combos', () => {- expect(hotkeyToKeys('Mod+Alt+Shift+K')).toEqual(['Meta', 'Alt', 'Shift', 'K'])- })- })-- describe('named-key combos from the registry', () => {- it('handles Mod+ArrowUp/Down/Left/Right', () => {- expect(hotkeyToKeys('Mod+ArrowUp')).toEqual(['Meta', 'ArrowUp'])- expect(hotkeyToKeys('Mod+ArrowDown')).toEqual(['Meta', 'ArrowDown'])- expect(hotkeyToKeys('Mod+ArrowLeft')).toEqual(['Meta', 'ArrowLeft'])- expect(hotkeyToKeys('Mod+ArrowRight')).toEqual(['Meta', 'ArrowRight'])- })-- it('handles Mod+Enter and Mod+Escape', () => {- expect(hotkeyToKeys('Mod+Enter')).toEqual(['Meta', 'Enter'])- expect(hotkeyToKeys('Mod+Escape')).toEqual(['Meta', 'Escape'])- })-- it('handles Mod+. (operation queue toggle / logs reset)', () => {- expect(hotkeyToKeys('Mod+.')).toEqual(['Meta', '.'])- })- })-- describe('edge cases', () => {- it('returns a single-element array for empty input', () => {- expect(hotkeyToKeys('')).toEqual([''])- })-- it('preserves empty segments from trailing plus', () => {- expect(hotkeyToKeys('Mod+')).toEqual(['Meta', ''])- })+ it.each([+ // Single keys (letters, named, punctuation) are preserved+ ['K', ['K']],+ ['Enter', ['Enter']],+ ['ArrowUp', ['ArrowUp']],+ [',', [',']],+ ['/', ['/']],+ // Mod maps to Meta, alone or in combos, without reordering modifiers+ ['Mod', ['Meta']],+ ['Mod+K', ['Meta', 'K']],+ ['Mod+Shift+M', ['Meta', 'Shift', 'M']],+ ['Shift+Mod+K', ['Shift', 'Meta', 'K']],+ ['Alt+Mod+K', ['Alt', 'Meta', 'K']],+ ['Mod+Alt+Shift+K', ['Meta', 'Alt', 'Shift', 'K']],+ ['Mod+ArrowDown', ['Meta', 'ArrowDown']],+ ['Mod+Enter', ['Meta', 'Enter']],+ ['Mod+.', ['Meta', '.']],+ // Other modifier literals are untouched+ ['Ctrl+K', ['Ctrl', 'K']],+ ['Alt+K', ['Alt', 'K']],+ ['Shift+K', ['Shift', 'K']],+ ['Meta+K', ['Meta', 'K']],+ // Only exact, case-sensitive "Mod" segments are converted+ ['mod+K', ['mod', 'K']],+ ['MOD+K', ['MOD', 'K']],+ ['Model', ['Model']],+ ['Mod+Model', ['Meta', 'Model']],+ // Edge cases keep empty segments+ ['', ['']],+ ['Mod+', ['Meta', '']],+ ])('maps %j to %j', (hotkey, expected) => {+ expect(hotkeyToKeys(hotkey)).toEqual(expected)})})diff --git a/apps/studio/state/shortcuts/matchEvent.test.ts b/apps/studio/state/shortcuts/matchEvent.test.tsindex 942eb33d435..15549fc9e16 100644--- a/apps/studio/state/shortcuts/matchEvent.test.ts+++ b/apps/studio/state/shortcuts/matchEvent.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { getSequenceManager } from '@tanstack/react-hotkeys'import { describe, expect, it, vi } from 'vitest'diff --git a/apps/studio/state/shortcuts/registry/org-shortcuts.test.ts b/apps/studio/state/shortcuts/registry/org-shortcuts.test.tsindex 5bda3061fc5..0f899cc55cd 100644--- a/apps/studio/state/shortcuts/registry/org-shortcuts.test.ts+++ b/apps/studio/state/shortcuts/registry/org-shortcuts.test.ts@@ -28,50 +28,6 @@ describe('Org settings nav shortcuts', () => {})})-describe('NAV_ORG_SETTINGS remap', () => {- it('uses G , (matching project settings chord)', () => {- const def = SHORTCUT_DEFINITIONS[SHORTCUT_IDS.NAV_ORG_SETTINGS]- expect(def.sequence).toEqual(['G', ','])- })-})--describe('Org action shortcuts', () => {- it('ORG_OAUTH_APPS_PUBLISH is registered', () => {- expect(SHORTCUT_DEFINITIONS[SHORTCUT_IDS.ORG_OAUTH_APPS_PUBLISH]).toBeDefined()- expect(SHORTCUT_DEFINITIONS[SHORTCUT_IDS.ORG_OAUTH_APPS_PUBLISH].sequence).toEqual(['Shift+N'])- })-- it('ORG_OAUTH_APPS_SUBMIT uses Mod+Enter and is hidden from settings', () => {- const def = SHORTCUT_DEFINITIONS[SHORTCUT_IDS.ORG_OAUTH_APPS_SUBMIT]- expect(def.sequence).toEqual(['Mod+Enter'])- expect(def.showInSettings).toBe(false)- })-- it('ORG_TEAM_INVITE is registered', () => {- expect(SHORTCUT_DEFINITIONS[SHORTCUT_IDS.ORG_TEAM_INVITE].sequence).toEqual(['Shift+N'])- })-- it('ORG_TEAM_INVITE_SUBMIT uses Mod+Enter and is hidden from settings', () => {- const def = SHORTCUT_DEFINITIONS[SHORTCUT_IDS.ORG_TEAM_INVITE_SUBMIT]- expect(def.sequence).toEqual(['Mod+Enter'])- expect(def.showInSettings).toBe(false)- })-- it('ORG_INTEGRATIONS_ADD_CONNECTION is registered', () => {- expect(SHORTCUT_DEFINITIONS[SHORTCUT_IDS.ORG_INTEGRATIONS_ADD_CONNECTION].sequence).toEqual([- 'Shift+N',- ])- })-- it('ORG_PROJECTS_NEW is registered', () => {- expect(SHORTCUT_DEFINITIONS[SHORTCUT_IDS.ORG_PROJECTS_NEW].sequence).toEqual(['Shift+N'])- })-- it('ORG_PROJECTS_SEARCH is registered', () => {- expect(SHORTCUT_DEFINITIONS[SHORTCUT_IDS.ORG_PROJECTS_SEARCH].sequence).toEqual(['Shift+F'])- })-})-describe('Reference group ordering', () => {it('NAVIGATION_ORG_SETTINGS appears after NAVIGATION_GLOBAL', () => {const globalIdx = SHORTCUT_REFERENCE_GROUP_ORDER.indexOf(diff --git a/apps/studio/state/shortcuts/useShortcut.test.tsx b/apps/studio/state/shortcuts/useShortcut.test.tsxindex 5233e3d0c83..6e836eb44a7 100644--- a/apps/studio/state/shortcuts/useShortcut.test.tsx+++ b/apps/studio/state/shortcuts/useShortcut.test.tsx@@ -70,14 +70,6 @@ describe('useShortcut', () => {renderHook(() => useShortcut(SHORTCUT_IDS.NAV_HOME, vi.fn()))expect(mockUseHotkeySequence.mock.calls[0][0]).toEqual(['G', 'H'])})-- it('wires the callback by reference — useHotkeySequence receives the same function', () => {- const cb = vi.fn()- renderHook(() => useShortcut(SHORTCUT_IDS.ACTION_BAR_SAVE, cb))- const passedCallback = mockUseHotkeySequence.mock.calls[0][1]- passedCallback()- expect(cb).toHaveBeenCalledTimes(1)- })})describe('enabled resolution', () => {@@ -97,18 +89,6 @@ describe('useShortcut', () => {expect(getLastHotkeyOptions().enabled).toBe(false)})- it('global enabled AND caller enabled = true', () => {- mockUseIsShortcutEnabled.mockReturnValue(true)- renderHook(() => useShortcut(SHORTCUT_IDS.COMMAND_MENU_OPEN, vi.fn(), { enabled: true }))- expect(getLastHotkeyOptions().enabled).toBe(true)- })-- it('global enabled AND caller undefined = true', () => {- mockUseIsShortcutEnabled.mockReturnValue(true)- renderHook(() => useShortcut(SHORTCUT_IDS.COMMAND_MENU_OPEN, vi.fn()))- expect(getLastHotkeyOptions().enabled).toBe(true)- })-it('subscribes to the correct shortcut id for global preference', () => {renderHook(() => useShortcut(SHORTCUT_IDS.NAV_TABLE_EDITOR, vi.fn()))expect(mockUseIsShortcutEnabled).toHaveBeenCalledWith(SHORTCUT_IDS.NAV_TABLE_EDITOR)diff --git a/apps/studio/state/sql-editor/sql-editor-diff-request.test.ts b/apps/studio/state/sql-editor/sql-editor-diff-request.test.tsindex eef93ebc072..976183d6e04 100644--- a/apps/studio/state/sql-editor/sql-editor-diff-request.test.ts+++ b/apps/studio/state/sql-editor/sql-editor-diff-request.test.ts@@ -9,19 +9,6 @@ beforeEach(() => {})describe('sqlEditorDiffRequestState', () => {- it('is empty by default', () => {- expect(sqlEditorDiffRequestState.pending).toBeUndefined()- })-- it('requestDiff queues a pending request', () => {- sqlEditorDiffRequestState.requestDiff('select 1', DiffType.Addition)-- expect(sqlEditorDiffRequestState.pending).toEqual({- sql: 'select 1',- diffType: DiffType.Addition,- })- })-it('consumeDiffRequest returns the pending request and clears it', () => {sqlEditorDiffRequestState.requestDiff('select 1', DiffType.Modification)diff --git a/apps/studio/state/sql-editor/sql-editor-lifecycle.test.ts b/apps/studio/state/sql-editor/sql-editor-lifecycle.test.tsindex 6e6def1faf8..f9552ab9b55 100644--- a/apps/studio/state/sql-editor/sql-editor-lifecycle.test.ts+++ b/apps/studio/state/sql-editor/sql-editor-lifecycle.test.ts@@ -127,35 +127,6 @@ describe('statusOnEdit', () => {})})-describe('lifecycle round trips', () => {- it('new snippet: first save succeeds then a re-save succeeds', () => {- let status: SnippetStatus = 'new'- status = statusOnSaveStart(status)- expect(status).toBe('new_saving')- status = statusOnSaveSuccess()- expect(status).toBe('saved')- // re-save- status = statusOnSaveStart(status)- expect(status).toBe('saving')- status = statusOnSaveSuccess()- expect(status).toBe('saved')- })-- it('new snippet: first save fails, retry succeeds (stays never-persisted until success)', () => {- let status: SnippetStatus = 'new'- status = statusOnSaveStart(status)- status = statusOnSaveError(status)- expect(status).toBe('new_save_failed')- expect(wasNeverPersisted(status)).toBe(true)- // retry- status = statusOnSaveStart(status)- expect(status).toBe('new_saving')- status = statusOnSaveSuccess()- expect(status).toBe('saved')- expect(wasNeverPersisted(status)).toBe(false)- })-})-const NEW_FOLDER: Array<FolderStatus> = ['new_editing', 'new_saving']const PERSISTED_FOLDER: Array<FolderStatus> = ['editing', 'saving', 'idle']diff --git a/apps/studio/state/sql-editor/sql-editor-rules.test.ts b/apps/studio/state/sql-editor/sql-editor-rules.test.tsindex a46f443f61d..314f0d9f489 100644--- a/apps/studio/state/sql-editor/sql-editor-rules.test.ts+++ b/apps/studio/state/sql-editor/sql-editor-rules.test.ts@@ -121,11 +121,6 @@ describe('validateMoveToFolder', () => {})describe('buildUpsertPayload', () => {- it('emits the snippet type — sql for a database snippet', () => {- const payload = buildUpsertPayload(makeSnippet(), 'snippet-1')- expect(payload.type).toBe('sql')- })-it('emits the snippet type — log_sql for a logs snippet (not silently rewritten to sql)', () => {const payload = buildUpsertPayload(makeLogSnippet(), 'log-snippet-1')expect(payload.type).toBe('log_sql')@@ -146,34 +141,21 @@ describe('buildUpsertPayload', () => {expect(payload.favorite).toBe(false)})- it('applies Untitled default when name is undefined', () => {- const snippet = makeSnippet({ name: undefined })- const payload = buildUpsertPayload(snippet, 'snippet-1')- expect(payload.name).toBe('Untitled')- })-- it('applies empty-string default when description is undefined', () => {- const snippet = makeSnippet({ description: undefined })- const payload = buildUpsertPayload(snippet, 'snippet-1')- expect(payload.description).toBe('')- })-- it('applies user default when visibility is undefined', () => {- const snippet = makeSnippet({ visibility: undefined })- const payload = buildUpsertPayload(snippet, 'snippet-1')- expect(payload.visibility).toBe('user')- })-- it('applies 0 default when project_id is undefined', () => {- const snippet = makeSnippet({ project_id: undefined })- const payload = buildUpsertPayload(snippet, 'snippet-1')- expect(payload.project_id).toBe(0)- })-- it('applies false default when favorite is undefined', () => {- const snippet = makeSnippet({ favorite: undefined })- const payload = buildUpsertPayload(snippet, 'snippet-1')- expect(payload.favorite).toBe(false)+ it('applies defaults for missing optional fields', () => {+ const snippet = makeSnippet({+ name: undefined,+ description: undefined,+ visibility: undefined,+ project_id: undefined,+ favorite: undefined,+ })+ expect(buildUpsertPayload(snippet, 'snippet-1')).toMatchObject({+ name: 'Untitled',+ description: '',+ visibility: 'user',+ project_id: 0,+ favorite: false,+ })})it('sets content.content_id to the supplied id', () => {@@ -205,14 +187,4 @@ describe('isLoadedSnippet', () => {const snippet = { ...makeSnippet(), content: undefined }expect(isLoadedSnippet(snippet)).toBe(false)})-- it('narrows the snippet so buildUpsertPayload accepts it', () => {- const snippet: SnippetWithContent = makeSnippet()- if (isLoadedSnippet(snippet)) {- const payload = buildUpsertPayload(snippet, 'snippet-1')- expect(payload.id).toBe('snippet-1')- } else {- throw new Error('expected snippet to be loaded')- }- })})diff --git a/apps/studio/state/storage-explorer.test.ts b/apps/studio/state/storage-explorer.test.tsindex 2c19ee41192..9259610f951 100644--- a/apps/studio/state/storage-explorer.test.ts+++ b/apps/studio/state/storage-explorer.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { HttpResponse } from 'msw'import { beforeEach, describe, expect, it } from 'vitest'diff --git a/apps/studio/state/tabs.test.ts b/apps/studio/state/tabs.test.tsindex 0957e11474c..903b564d3f7 100644--- a/apps/studio/state/tabs.test.ts+++ b/apps/studio/state/tabs.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport type { NextRouter } from 'next/router'import { beforeEach, describe, expect, it, vi } from 'vitest'diff --git a/apps/studio/tests/components/ApiAuthorization.test.tsx b/apps/studio/tests/components/ApiAuthorization.test.tsxindex 708ceb30bd9..25c44a1fd79 100644--- a/apps/studio/tests/components/ApiAuthorization.test.tsx+++ b/apps/studio/tests/components/ApiAuthorization.test.tsx@@ -228,32 +228,22 @@ describe('ApiAuthorizationScreen', () => {path: '/platform/oauth/authorizations/:id',response: () => new Promise<never>(() => {}),})- const { container } = renderScreen()- expect(screen.getByText('Loading...')).toBeInTheDocument()- expect(container.querySelectorAll('.shimmering-loader').length).toBeGreaterThan(0)- })-- test('renders error screen when authorization query fails', async () => {- mockOrgsEndpoint()- addAPIMock({- method: 'get',- path: '/platform/oauth/authorizations/:id',- response: () => HttpResponse.json<APIErrorBody>({ message: 'Not found' }, { status: 404 }),- })renderScreen()- await screen.findByText('Unable to load authorization')+ expect(screen.getByText('Loading...')).toBeInTheDocument()})- test('renders error screen when authorization query returns no requester', async () => {- mockOrgsEndpoint()- addAPIMock({- method: 'get',- path: '/platform/oauth/authorizations/:id',- response: () =>+ test.each([+ ['fails', () => HttpResponse.json<APIErrorBody>({ message: 'Not found' }, { status: 404 })],+ [+ 'returns no requester',+ () =>HttpResponse.json<GetOAuthAuthorizationResponse>(null as unknown as GetOAuthAuthorizationResponse),- })+ ],+ ])('renders error screen when authorization query %s', async (_, response) => {+ mockOrgsEndpoint()+ addAPIMock({ method: 'get', path: '/platform/oauth/authorizations/:id', response })renderScreen()await screen.findByText('Unable to load authorization')})@@ -317,7 +307,7 @@ describe('ApiAuthorizationScreen', () => {).not.toBeInTheDocument()})- test('shows empty state when user has no organizations', async () => {+ test('shows empty state linking back to this authorize request when user has no organizations', async () => {mockBothEndpoints(createMockAuthResponse(), [])renderScreen()await screen.findByText('No organizations found')@@ -325,13 +315,7 @@ describe('ApiAuthorizationScreen', () => {expect(screen.queryByRole('button', { name: /Authorize Test App/ })).not.toBeInTheDocument()- })-- test('empty state links back to this authorize request via returnTo', async () => {- mockBothEndpoints(createMockAuthResponse(), [])- renderScreen()- const link = await screen.findByRole('link', { name: 'Create an organization' })- expect(link).toHaveAttribute(+ expect(screen.getByRole('link', { name: 'Create an organization' })).toHaveAttribute('href',`/new?returnTo=${encodeURIComponent('/authorize?auth_id=test-auth-id')}`)@@ -432,13 +416,6 @@ describe('ApiAuthorizationScreen', () => {expect(screen.queryByRole('button', { name: 'Cancel' })).not.toBeInTheDocument()expect(screen.queryByRole('button', { name: /Authorize Claude/ })).not.toBeInTheDocument()})-- test('does not show expiration warning when request has not expired', async () => {- mockBothEndpoints()- renderScreen()- await screen.findByText('Authorize API access for Test App')- expect(screen.queryByText('Authorization request expired')).not.toBeInTheDocument()- })})describe('approve action', () => {diff --git a/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts b/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.tsindex af8472a32b4..736ddda5906 100644--- a/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts+++ b/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts@@ -37,19 +37,9 @@ const logC = makeLog({})describe('timestamp conversion (microseconds → milliseconds)', () => {- test('dividing by 1000 produces a valid date', () => {- expect(dayjs(TS_A / TIMESTAMP_MICROS_PER_MS).isValid()).toBe(true)- })-- test('produces the correct year', () => {+ test('dividing by TIMESTAMP_MICROS_PER_MS produces the correct date', () => {expect(dayjs(TS_A / TIMESTAMP_MICROS_PER_MS).year()).toBe(2026)})-- test('dayjs.unix on a microsecond value produces an invalid date', () => {- // Guard: confirms the bug we fixed — dayjs.unix() treats the value as seconds,- // overflowing JS Date's max and producing "Invalid Date"- expect(dayjs.unix(TS_A).isValid()).toBe(false)- })})describe('filterByFilterGroup', () => {diff --git a/apps/studio/tests/components/AuditLogs/OrgAuditLogs.utils.test.ts b/apps/studio/tests/components/AuditLogs/OrgAuditLogs.utils.test.tsindex 86b1a30f501..fe9c6d88b6e 100644--- a/apps/studio/tests/components/AuditLogs/OrgAuditLogs.utils.test.ts+++ b/apps/studio/tests/components/AuditLogs/OrgAuditLogs.utils.test.ts@@ -30,47 +30,33 @@ describe('formatSelectedDateRange', () => {expect(to.hour()).toBe(NOW.hour())})- test('single date matching today: from is set to 00:00:00', () => {+ test('single date matching today: from starts at 00:00:00 and to keeps current time', () => {fakeNow()const today = NOW.format('YYYY-MM-DD')const result = formatSelectedDateRange({ from: today, to: today })const from = dayjs(result.from)+ const to = dayjs(result.to)expect(from.hour()).toBe(0)expect(from.minute()).toBe(0)expect(from.second()).toBe(0)- })-- test('single date matching today: to keeps current time', () => {- fakeNow()- const today = NOW.format('YYYY-MM-DD')- const result = formatSelectedDateRange({ from: today, to: today })- const to = dayjs(result.to)expect(to.hour()).toBe(NOW.hour())expect(to.minute()).toBe(NOW.minute())})- test('single date in the past: to is set to 23:59:59', () => {+ test('single date in the past: from keeps current time and to ends at 23:59:59', () => {fakeNow()const result = formatSelectedDateRange({from: '2024-06-01',to: '2024-06-01',})+ const from = dayjs(result.from)const to = dayjs(result.to)+ expect(from.hour()).toBe(NOW.hour())expect(to.hour()).toBe(23)expect(to.minute()).toBe(59)expect(to.second()).toBe(59)})- test('single date in the past: from keeps current time', () => {- fakeNow()- const result = formatSelectedDateRange({- from: '2024-06-01',- to: '2024-06-01',- })- const from = dayjs(result.from)- expect(from.hour()).toBe(NOW.hour())- })-test('output is in UTC ISO format', () => {fakeNow()const result = formatSelectedDateRange({diff --git a/apps/studio/tests/components/Auth/Auth.constants.test.ts b/apps/studio/tests/components/Auth/Auth.constants.test.tsindex 1beb569ed1d..5acc501494f 100644--- a/apps/studio/tests/components/Auth/Auth.constants.test.ts+++ b/apps/studio/tests/components/Auth/Auth.constants.test.ts@@ -34,23 +34,14 @@ describe('Auth.constants: urlRegex', () => {it('should not match invalid URLs', () => {const invalidUrls = ['supabase', 'mailto:[email protected]', 'hello world.com', '[email protected]']- const failingInvalidUrls = invalidUrls.filter((url) => urlRegex().test(url))- if (failingInvalidUrls.length > 0) {- console.log('Failing invalid URLs:', failingInvalidUrls)- }-invalidUrls.forEach((url) => {expect(urlRegex().test(url)).toBe(false)})})- it('should not match simple domain URLs when excludeSimpleDomains is true', () => {+ it('only matches simple domain URLs when excludeSimpleDomains is false', () => {const simpleDomainUrl = 'smtp-pulse.com'expect(urlRegex({ excludeSimpleDomains: true }).test(simpleDomainUrl)).toBe(false)- })-- it('should match simple domain URLs when excludeSimpleDomains is false', () => {- const simpleDomainUrl = 'smtp-pulse.com'expect(urlRegex({ excludeSimpleDomains: false }).test(simpleDomainUrl)).toBe(true)})diff --git a/apps/studio/tests/components/Database/Roles.test.tsx b/apps/studio/tests/components/Database/Roles.test.tsxindex 2428bacaeec..e11ba49b8e1 100644--- a/apps/studio/tests/components/Database/Roles.test.tsx+++ b/apps/studio/tests/components/Database/Roles.test.tsx@@ -90,16 +90,21 @@ describe('RoleRow', () => {expect(deleteItem).toBeAriaDisabled()fireEvent.click(deleteItem)expect(onSelectDelete).not.toHaveBeenCalled()-- await userEvent.hover(deleteItem)- expect(- await screen.findByRole('tooltip', {- name: `The ${name} role is a system role and cannot be deleted`,- })- ).toBeInTheDocument()})+ test('explains why Delete is disabled for a system role', async () => {+ customRender(<RoleRow role={createRole(1, 'postgres')} onSelectDelete={vi.fn()} />)++ await userEvent.click(screen.getByRole('button', { name: 'postgres actions' }))+ await userEvent.hover(await screen.findByRole('menuitem', { name: 'Delete' }))+ expect(+ await screen.findByRole('tooltip', {+ name: 'The postgres role is a system role and cannot be deleted',+ })+ ).toBeInTheDocument()+ })+test('keeps the postgres permission editor available', async () => {customRender(<RoleRow role={createRole(1, 'postgres')} onSelectDelete={vi.fn()} />)diff --git a/apps/studio/tests/components/Editor/SpreadsheetImport.utils.test.ts b/apps/studio/tests/components/Editor/SpreadsheetImport.utils.test.tsindex 5b124150f48..4216e7a6b2f 100644--- a/apps/studio/tests/components/Editor/SpreadsheetImport.utils.test.ts+++ b/apps/studio/tests/components/Editor/SpreadsheetImport.utils.test.ts@@ -89,13 +89,6 @@ describe('SpreadsheetImport.utils: parseSpreadsheetText', () => {expect((rows[1] as SampleRow).age).toBeNull()})- test('should not affect non-empty values when treatEmptyAsNull is true', async () => {- const csv = `name,age\nJohn,25\nJane,`- const { rows } = await parseSpreadsheetText({ text: csv, emptyStringAsNullHeaders: undefined })- expect((rows[0] as SampleRow).name).toBe('John')- expect((rows[0] as SampleRow).age).toBe('25')- })-test('should handle multiple empty cells across columns when treatEmptyAsNull is true', async () => {const csv = `name,age,city\nJohn,,\nJane,30,`const { rows } = await parseSpreadsheetText({ text: csv, emptyStringAsNullHeaders: undefined })diff --git a/apps/studio/tests/components/Functions/EdgeFunctionDetails.utils.test.ts b/apps/studio/tests/components/Functions/EdgeFunctionDetails.utils.test.tsindex af31ed7d99c..29c153ac16c 100644--- a/apps/studio/tests/components/Functions/EdgeFunctionDetails.utils.test.ts+++ b/apps/studio/tests/components/Functions/EdgeFunctionDetails.utils.test.ts@@ -4,19 +4,13 @@ import { getEdgeFunctionErrorDocs } from '@/components/interfaces/Functions/Edgeimport { DOCS_URL } from '@/lib/constants'describe('getEdgeFunctionErrorDocs', () => {- it('builds a documentation link from the error code header', () => {- expect(- getEdgeFunctionErrorDocs({ 'sb-error-code': 'UNAUTHORIZED_INVALID_JWT_FORMAT' })- ).toEqual({- code: 'UNAUTHORIZED_INVALID_JWT_FORMAT',- href: `${DOCS_URL}/guides/functions/error-codes#unauthorizedinvalidjwtformat`,- })- })-- it('uses the same anchor format as documentation headings', () => {- expect(getEdgeFunctionErrorDocs({ 'sb-error-code': 'WORKER_RESOURCE_LIMIT' })).toEqual({- code: 'WORKER_RESOURCE_LIMIT',- href: `${DOCS_URL}/guides/functions/error-codes#workerresourcelimit`,+ it.each([+ ['UNAUTHORIZED_INVALID_JWT_FORMAT', 'unauthorizedinvalidjwtformat'],+ ['WORKER_RESOURCE_LIMIT', 'workerresourcelimit'],+ ])('builds a documentation link for %s using the docs heading anchor format', (code, anchor) => {+ expect(getEdgeFunctionErrorDocs({ 'sb-error-code': code })).toEqual({+ code,+ href: `${DOCS_URL}/guides/functions/error-codes#${anchor}`,})})diff --git a/apps/studio/tests/components/Functions/EdgeFunctionTesterSheet.utils.test.ts b/apps/studio/tests/components/Functions/EdgeFunctionTesterSheet.utils.test.tsindex f2a33e59ffa..b188519227d 100644--- a/apps/studio/tests/components/Functions/EdgeFunctionTesterSheet.utils.test.ts+++ b/apps/studio/tests/components/Functions/EdgeFunctionTesterSheet.utils.test.ts@@ -33,19 +33,6 @@ describe('buildEdgeFunctionTestHeaders', () => {expect(headers).toEqual({ 'Content-Type': 'application/json' })})- it('keeps a user supplied Authorization header', () => {- const headers = buildEdgeFunctionTestHeaders({- apiKey: PUBLISHABLE_KEY,- customHeaders: [{ key: 'Authorization', value: 'Bearer user-token' }],- })-- expect(headers).toEqual({- 'Content-Type': 'application/json',- apikey: PUBLISHABLE_KEY,- Authorization: 'Bearer user-token',- })- })-it('keeps the apikey alongside several user rows', () => {const headers = buildEdgeFunctionTestHeaders({apiKey: PUBLISHABLE_KEY,diff --git a/apps/studio/tests/components/Grid/Grid.utils.test.ts b/apps/studio/tests/components/Grid/Grid.utils.test.tsindex 8722cebe1f0..691fd6dead7 100644--- a/apps/studio/tests/components/Grid/Grid.utils.test.ts+++ b/apps/studio/tests/components/Grid/Grid.utils.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { copyToClipboard } from 'ui'import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'diff --git a/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.network.test.tsx b/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.network.test.tsxdeleted file mode 100644index debe2b3aa77..00000000000--- a/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.network.test.tsx+++ /dev/null@@ -1,364 +0,0 @@-import { fireEvent, screen, waitFor, within } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { platformComponents as components, operations } from 'api-types'-import { mockIntersectionObserver } from 'jsdom-testing-mocks'-import { HttpResponse } from 'msw'-import { describe, expect, test, vi } from 'vitest'--import { InviteMemberButton } from '@/components/interfaces/Organization/TeamSettings/InviteMemberButton'-import { FGA_PERMISSIONS } from '@/hooks/misc/useCheckPermissionsV2'-import type { ProfileContextType } from '@/lib/profile'-import { createMockOrganizationResponse } from '@/tests/helpers'-import { customRender } from '@/tests/lib/custom-render'-import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'--type OrganizationResponse = components['schemas']['OrganizationResponse_Output']-type Member = components['schemas']['Member_Output']-type InvitationResponse = components['schemas']['InvitationResponse_Output']-type OrganizationRoleResponse = components['schemas']['OrganizationRoleResponse_Output']-type ListEntitlementsResponse = components['schemas']['ListEntitlementsResponse_Output']-type OrganizationProjectsResponse = components['schemas']['OrganizationProjectsResponse_Output']-type OrgProject = OrganizationProjectsResponse['projects'][number]-type CreateInvitationResponse =- operations['InvitationsController_createInvitation']['responses']['201']['content']['application/json']-type PermissionsV2Response = components['schemas']['UserPermissionsResponse_Output']--// The project multi-select's infinite-scroll sentinel uses IntersectionObserver, which jsdom lacks-mockIntersectionObserver()--const ORG_SLUG = 'test-org'--const ROLE_IDS = { owner: 1, administrator: 2, developer: 3, readOnly: 4 } as const--vi.mock('common', async (importOriginal) => {- const actual = (await importOriginal()) as typeof import('common')- return {- ...actual,- useParams: () => ({ slug: ORG_SLUG }),- useIsLoggedIn: () => true,- }-})--vi.mock('@/lib/constants', async (importOriginal) => {- const actual = await importOriginal<Record<string, unknown>>()- return { ...actual, IS_PLATFORM: true }-})--const PROFILE_CONTEXT: ProfileContextType = {- profile: {- id: 1,- auth0_id: 'auth0|test',- gotrue_id: 'gotrue-test',- username: 'testuser',- primary_email: '[email protected]',- first_name: null,- last_name: null,- mobile: null,- is_alpha_user: false,- is_sso_user: false,- disabled_features: [],- free_project_limit: null,- },- error: null,- isLoading: false,- isError: false,- isSuccess: true,-}--const buildRole = (id: number, name: string): OrganizationRoleResponse['org_scoped_roles'][0] => ({- id,- name,- base_role_id: id,- description: null,- projects: [],-})--const buildMember = (overrides: Partial<Member>): Member => ({- gotrue_id: 'gotrue-test',- avatar_url: null,- is_sso_user: false,- metadata: {},- mfa_enabled: false,- primary_email: '[email protected]',- role_ids: [ROLE_IDS.developer],- username: 'testuser',- ...overrides,-})--const PERMISSIONS_RESPONSE: PermissionsV2Response = {- organizations: [- {- slug: ORG_SLUG,- role: 'owner',- permissions: [FGA_PERMISSIONS.ORGANIZATION.MEMBERS_WRITE],- projects: [],- },- ],-}--const PROJECTS: OrgProject[] = [- {- cloud_provider: 'AWS',- databases: [],- inserted_at: '2026-01-01T00:00:00.000Z',- integration_source: null,- is_branch: false,- ref: 'project-alpha',- name: 'Alpha',- region: 'us-east-1',- status: 'ACTIVE_HEALTHY',- },- {- cloud_provider: 'AWS',- databases: [],- inserted_at: '2026-01-01T00:00:00.000Z',- integration_source: null,- is_branch: false,- ref: 'project-beta',- name: 'Beta',- region: 'us-east-1',- status: 'ACTIVE_HEALTHY',- },-]--function setupMocks(- members: Member[] = [buildMember({})],- { projectScoped = false }: { projectScoped?: boolean } = {}-) {- const invitePayloads: unknown[] = []-- addAPIMock({- method: 'get',- path: '/platform/organizations',- response: () =>- HttpResponse.json<OrganizationResponse[]>([- createMockOrganizationResponse({ id: 1, slug: ORG_SLUG, name: 'Test Org' }),- ]),- })-- addAPIMock({- method: 'get',- path: '/platform/profile/permissions/v2',- response: () => HttpResponse.json<PermissionsV2Response>(PERMISSIONS_RESPONSE),- })-- addAPIMock({- method: 'get',- path: '/platform/organizations/:slug/members',- response: () => HttpResponse.json<Member[]>(members),- })-- addAPIMock({- method: 'get',- path: '/platform/organizations/:slug/members/invitations',- response: () => HttpResponse.json<InvitationResponse>({ invitations: [] }),- })-- addAPIMock({- method: 'get',- path: '/platform/organizations/:slug/roles',- response: () =>- HttpResponse.json<OrganizationRoleResponse>({- org_scoped_roles: [- buildRole(ROLE_IDS.owner, 'Owner'),- buildRole(ROLE_IDS.administrator, 'Administrator'),- buildRole(ROLE_IDS.developer, 'Developer'),- buildRole(ROLE_IDS.readOnly, 'Read-only'),- ],- // Unused by this component's org-scoped flow, but required by the schema- project_scoped_roles: [],- }),- })-- // 404 with this message is how the query layer detects "no SSO provider" and- // resolves the config to null (see getOrgSSOConfig).- addAPIMock({- method: 'get',- path: '/platform/organizations/:slug/sso',- response: () =>- HttpResponse.json<APIErrorBody>(- { message: 'Failed to find an existing SSO Provider' },- { status: 404 }- ),- })-- // Empty entitlements => project-level permissions are off, so the panel- // renders the org-scoped role flow (no "all projects" toggle or selector). When- // projectScoped is true, both appear.- addAPIMock({- method: 'get',- path: '/platform/organizations/:slug/entitlements',- response: () =>- HttpResponse.json<ListEntitlementsResponse>({- entitlements: projectScoped- ? [- {- config: { enabled: true },- feature: { key: 'project_scoped_roles', type: 'boolean' },- hasAccess: true,- type: 'boolean',- },- ]- : [],- }),- })-- addAPIMock({- method: 'get',- path: '/platform/organizations/:slug/projects',- response: () =>- HttpResponse.json<OrganizationProjectsResponse>({- pagination: { count: PROJECTS.length, limit: 96, offset: 0 },- projects: PROJECTS,- }),- })-- addAPIMock({- method: 'post',- path: '/platform/organizations/:slug/members/invitations',- response: async ({ request }) => {- invitePayloads.push(await request.json())- return HttpResponse.json<CreateInvitationResponse>({- succeeded: ['[email protected]'],- failed: [],- })- },- })-- return { invitePayloads }-}--async function openDialog() {- await waitFor(() => expect(screen.getByRole('button', { name: /invite members/i })).toBeEnabled())- await userEvent.click(screen.getByRole('button', { name: /invite members/i }))- return screen.findByRole('dialog')-}--describe('InviteMemberButton (network)', () => {- test('renders each role with its permission description and a roles docs link', async () => {- setupMocks()- customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })- await openDialog()-- // Every role is rendered as a selectable card- expect(await screen.findByText('Administrator')).toBeInTheDocument()- expect(screen.getByText('Owner')).toBeInTheDocument()- expect(screen.getByText('Developer')).toBeInTheDocument()- expect(screen.getByText('Read-only')).toBeInTheDocument()-- // The key safety message from the ticket: Administrator can delete projects- expect(screen.getByText('deleting projects')).toBeInTheDocument()-- // Roles documentation is one click away (the ticket's other complaint)- const docsLink = screen.getByRole('link', { name: /roles and permissions/i })- expect(docsLink).toHaveAttribute(- 'href',- expect.stringContaining('/guides/platform/access-control')- )- })-- test('sends emails and the default Developer role_id in the request body', async () => {- const { invitePayloads } = setupMocks()- customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })- await openDialog()- await screen.findByText('Developer')-- fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {- target: { value: '[email protected]' },- })- fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))-- await waitFor(() => expect(invitePayloads).toHaveLength(1))- expect(invitePayloads[0]).toEqual({- emails: ['[email protected]'],- role_id: ROLE_IDS.developer,- })- })-- test('sends the selected role_id when a different role is chosen', async () => {- const { invitePayloads } = setupMocks()- customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })- await openDialog()-- // Select the Administrator card via the new RadioGroupStacked- await userEvent.click(await screen.findByText('Administrator'))-- fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {- target: { value: '[email protected]' },- })- fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))-- const confirmation = await screen.findByRole('dialog', { name: 'Invite as Administrator?' })- expect(invitePayloads).toHaveLength(0)- fireEvent.click(within(confirmation).getByRole('button', { name: /send invitation/i }))-- await waitFor(() => expect(invitePayloads).toHaveLength(1))- expect(invitePayloads[0]).toEqual({- emails: ['[email protected]'],- role_id: ROLE_IDS.administrator,- })- })-- test('lowercases and de-duplicates emails before sending', async () => {- const { invitePayloads } = setupMocks()- customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })- await openDialog()- await screen.findByText('Developer')-- fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {- })- fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))-- await waitFor(() => expect(invitePayloads).toHaveLength(1))- expect(invitePayloads[0]).toEqual({- emails: ['[email protected]', '[email protected]'],- role_id: ROLE_IDS.developer,- })- })-- describe('project-scoped access', () => {- test('requires at least one project when "Grant this role on all projects" is off', async () => {- const { invitePayloads } = setupMocks(undefined, { projectScoped: true })- customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })- await openDialog()-- const toggle = await screen.findByRole('switch')- expect(toggle).toBeChecked()- await userEvent.click(toggle)- expect(toggle).not.toBeChecked()-- fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {- target: { value: '[email protected]' },- })- fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))-- expect(await screen.findByText('Select at least one project')).toBeInTheDocument()- expect(invitePayloads).toHaveLength(0)- })-- test('sends the selected projects as role_scoped_projects when multiple are chosen', async () => {- const { invitePayloads } = setupMocks(undefined, { projectScoped: true })- customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })- await openDialog()-- await userEvent.click(await screen.findByRole('switch'))-- await userEvent.click(screen.getByRole('combobox'))- await userEvent.click(await screen.findByRole('option', { name: /Alpha/ }))- await userEvent.click(await screen.findByRole('option', { name: /Beta/ }))-- fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {- target: { value: '[email protected]' },- })- fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))-- await waitFor(() => expect(invitePayloads).toHaveLength(1))- expect(invitePayloads[0]).toEqual({- emails: ['[email protected]'],- role_id: ROLE_IDS.developer,- role_scoped_projects: ['project-alpha', 'project-beta'],- })- })- })-})diff --git a/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.test.tsx b/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.test.tsxindex 85b0c9c61f8..332537cb83a 100644--- a/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.test.tsx+++ b/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.test.tsx@@ -1,10 +1,35 @@import { fireEvent, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { platformComponents as components, operations } from 'api-types'+import { mockIntersectionObserver } from 'jsdom-testing-mocks'+import { HttpResponse } from 'msw'import { toast } from 'sonner'-import { beforeEach, describe, expect, it, vi } from 'vitest'+import { describe, expect, test, vi } from 'vitest'import { InviteMemberButton } from '@/components/interfaces/Organization/TeamSettings/InviteMemberButton'+import { FGA_PERMISSIONS } from '@/hooks/misc/useCheckPermissionsV2'+import type { ProfileContextType } from '@/lib/profile'+import { createMockOrganizationResponse } from '@/tests/helpers'import { customRender } from '@/tests/lib/custom-render'+import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'++type OrganizationResponse = components['schemas']['OrganizationResponse_Output']+type Member = components['schemas']['Member_Output']+type InvitationResponse = components['schemas']['InvitationResponse_Output']+type OrganizationRoleResponse = components['schemas']['OrganizationRoleResponse_Output']+type ListEntitlementsResponse = components['schemas']['ListEntitlementsResponse_Output']+type OrganizationProjectsResponse = components['schemas']['OrganizationProjectsResponse_Output']+type OrgProject = OrganizationProjectsResponse['projects'][number]+type CreateInvitationResponse =+ operations['InvitationsController_createInvitation']['responses']['201']['content']['application/json']+type PermissionsV2Response = components['schemas']['UserPermissionsResponse_Output']++// The project multi-select's infinite-scroll sentinel uses IntersectionObserver, which jsdom lacks+mockIntersectionObserver()++const ORG_SLUG = 'test-org'++const ROLE_IDS = { owner: 1, administrator: 2, developer: 3, readOnly: 4 } as constvi.mock('sonner', () => ({toast: { success: vi.fn(), error: vi.fn() },@@ -12,132 +37,241 @@ vi.mock('sonner', () => ({vi.mock('common', async (importOriginal) => {const actual = (await importOriginal()) as typeof import('common')- return { ...actual, useParams: () => ({ slug: 'test-org' }) }+ return {+ ...actual,+ useParams: () => ({ slug: ORG_SLUG }),+ useIsLoggedIn: () => true,+ }})-vi.mock('@/lib/profile', () => ({- useProfile: () => ({ profile: { id: 1, gotrue_id: 'user-1' } }),-}))--vi.mock('@/hooks/misc/useSelectedOrganization', () => ({- useSelectedOrganizationQuery: () => ({- data: { id: 1, slug: 'test-org', name: 'Test Org' },- }),-}))+vi.mock('@/lib/constants', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>()+ return { ...actual, IS_PLATFORM: true }+})-vi.mock('@/data/permissions/permissions-query-v2', () => ({- usePermissionsQueryV2: () => ({- data: {- organizations: [{ slug: 'test-org', role: 'owner', permissions: [], projects: [] }],- },- }),-}))+const PROFILE_CONTEXT: ProfileContextType = {+ profile: {+ id: 1,+ auth0_id: 'auth0|test',+ gotrue_id: 'gotrue-test',+ username: 'testuser',+ primary_email: '[email protected]',+ first_name: null,+ last_name: null,+ mobile: null,+ is_alpha_user: false,+ is_sso_user: false,+ disabled_features: [],+ free_project_limit: null,+ },+ error: null,+ isLoading: false,+ isError: false,+ isSuccess: true,+}-vi.mock('@/hooks/misc/useIsFeatureEnabled', () => ({- useIsFeatureEnabled: mockIsFeatureEnabled,-}))+const buildRole = (id: number, name: string): OrganizationRoleResponse['org_scoped_roles'][0] => ({+ id,+ name,+ base_role_id: id,+ description: null,+ projects: [],+})-vi.mock('@/data/organizations/organization-members-query', () => ({- useOrganizationMembersQuery: () => ({- data: [- {- gotrue_id: 'user-1',- primary_email: '[email protected]',- role_ids: [1],- },- {- gotrue_id: 'existing-user',- primary_email: '[email protected]',- role_ids: [1],- },- ],- }),-}))+const buildMember = (overrides: Partial<Member>): Member => ({+ gotrue_id: 'gotrue-test',+ avatar_url: null,+ is_sso_user: false,+ metadata: {},+ mfa_enabled: false,+ primary_email: '[email protected]',+ role_ids: [ROLE_IDS.developer],+ username: 'testuser',+ ...overrides,+})-const mockRoles = {- org_scoped_roles: [- { id: 4, name: 'Owner', description: null },- { id: 3, name: 'Administrator', description: null },- { id: 1, name: 'Developer', description: null },- { id: 2, name: 'Read-only', description: null },+const PERMISSIONS_RESPONSE: PermissionsV2Response = {+ organizations: [+ {+ slug: ORG_SLUG,+ role: 'owner',+ permissions: [FGA_PERMISSIONS.ORGANIZATION.MEMBERS_WRITE],+ projects: [],+ },],}-vi.mock('@/data/organization-members/organization-roles-query', () => ({- useOrganizationRolesV2Query: () => ({ data: mockRoles, isSuccess: true }),-}))-vi.mock('@/data/sso/sso-config-query', () => ({- useOrgSSOConfigQuery: () => ({ data: null }),-}))+const PROJECTS: OrgProject[] = [+ {+ cloud_provider: 'AWS',+ databases: [],+ inserted_at: '2026-01-01T00:00:00.000Z',+ integration_source: null,+ is_branch: false,+ ref: 'project-alpha',+ name: 'Alpha',+ region: 'us-east-1',+ status: 'ACTIVE_HEALTHY',+ },+ {+ cloud_provider: 'AWS',+ databases: [],+ inserted_at: '2026-01-01T00:00:00.000Z',+ integration_source: null,+ is_branch: false,+ ref: 'project-beta',+ name: 'Beta',+ region: 'us-east-1',+ status: 'ACTIVE_HEALTHY',+ },+]++const EXISTING_MEMBER = buildMember({+ gotrue_id: 'existing-user',+ primary_email: '[email protected]',+})-vi.mock('@/data/subscriptions/org-subscription-query', () => ({- useHasAccessToProjectLevelPermissions: () => false,-}))+function setupMocks({+ members = [buildMember({}), EXISTING_MEMBER],+ projectScoped = false,+ inviteResponse = { succeeded: ['[email protected]'], failed: [] },+}: {+ members?: Member[]+ projectScoped?: boolean+ inviteResponse?: CreateInvitationResponse+} = {}) {+ const invitePayloads: unknown[] = []++ addAPIMock({+ method: 'get',+ path: '/platform/organizations',+ response: () =>+ HttpResponse.json<OrganizationResponse[]>([+ createMockOrganizationResponse({ id: 1, slug: ORG_SLUG, name: 'Test Org' }),+ ]),+ })-vi.mock('@/hooks/misc/useCheckEntitlements', () => ({- useCheckEntitlements: () => ({ hasAccess: false }),-}))+ addAPIMock({+ method: 'get',+ path: '/platform/profile/permissions/v2',+ response: () => HttpResponse.json<PermissionsV2Response>(PERMISSIONS_RESPONSE),+ })-const { mockGetAssignableRoleIds, mockIsFeatureEnabled } = vi.hoisted(() => ({- mockGetAssignableRoleIds: vi.fn(),- mockIsFeatureEnabled: vi.fn(),-}))+ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/members',+ response: () => HttpResponse.json<Member[]>(members),+ })-vi.mock('@/components/interfaces/Organization/TeamSettings/TeamSettings.utils', () => ({- getOrgRole: () => 'owner',- getAssignableRoleIds: mockGetAssignableRoleIds,-}))+ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/members/invitations',+ response: () => HttpResponse.json<InvitationResponse>({ invitations: [] }),+ })-const mockInvite = vi.fn().mockResolvedValue({ succeeded: [], failed: [] })-vi.mock('@/data/organization-members/organization-invitation-create-mutation', () => ({- useOrganizationCreateInvitationMutation: () => ({- mutateAsync: mockInvite,- isPending: false,- }),-}))+ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/roles',+ response: () =>+ HttpResponse.json<OrganizationRoleResponse>({+ org_scoped_roles: [+ buildRole(ROLE_IDS.owner, 'Owner'),+ buildRole(ROLE_IDS.administrator, 'Administrator'),+ buildRole(ROLE_IDS.developer, 'Developer'),+ buildRole(ROLE_IDS.readOnly, 'Read-only'),+ ],+ // Unused by this component's org-scoped flow, but required by the schema+ project_scoped_roles: [],+ }),+ })++ // 404 with this message is how the query layer detects "no SSO provider" and+ // resolves the config to null (see getOrgSSOConfig).+ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/sso',+ response: () =>+ HttpResponse.json<APIErrorBody>(+ { message: 'Failed to find an existing SSO Provider' },+ { status: 404 }+ ),+ })++ // Empty entitlements => project-level permissions are off, so the panel+ // renders the org-scoped role flow (no "all projects" toggle or selector). When+ // projectScoped is true, both appear.+ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/entitlements',+ response: () =>+ HttpResponse.json<ListEntitlementsResponse>({+ entitlements: projectScoped+ ? [+ {+ config: { enabled: true },+ feature: { key: 'project_scoped_roles', type: 'boolean' },+ hasAccess: true,+ type: 'boolean',+ },+ ]+ : [],+ }),+ })++ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/projects',+ response: () =>+ HttpResponse.json<OrganizationProjectsResponse>({+ pagination: { count: PROJECTS.length, limit: 96, offset: 0 },+ projects: PROJECTS,+ }),+ })-vi.mock('@/hooks/ui/useConfirmOnClose', () => ({- useConfirmOnClose: ({ onClose }: { checkIsDirty: () => boolean; onClose: () => void }) => ({- confirmOnClose: onClose,- handleOpenChange: (open: boolean) => {- if (!open) onClose()+ addAPIMock({+ method: 'post',+ path: '/platform/organizations/:slug/members/invitations',+ response: async ({ request }) => {+ invitePayloads.push(await request.json())+ return HttpResponse.json<CreateInvitationResponse>(inviteResponse)},- modalProps: { visible: false, onClose, onCancel: vi.fn() },- }),-}))+ })-// Helpers-const getRoleDescription = (text: string) =>- screen.getByText((_, element) => element?.tagName === 'P' && element.textContent === text)+ return { invitePayloads }+}async function openDialog() {+ await waitFor(() => expect(screen.getByRole('button', { name: /invite members/i })).toBeEnabled())await userEvent.click(screen.getByRole('button', { name: /invite members/i }))return screen.findByRole('dialog')}-async function submitForm(emailValue: string) {+const INVITE_BUTTON = { name: /invite members/i }++async function fillAndSubmit(emailValue: string) {await openDialog()+ await screen.findByText('Developer')fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {target: { value: emailValue },})fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))}-// Testsdescribe('InviteMemberButton', () => {- beforeEach(() => {- mockInvite.mockResolvedValue({ succeeded: [], failed: [] })- mockGetAssignableRoleIds.mockReturnValue([1, 2, 3, 4])- mockIsFeatureEnabled.mockReturnValue({ organizationMembersCreate: true })- })-- it('disables the button when member creation is turned off despite sufficient permissions', async () => {- mockIsFeatureEnabled.mockReturnValue({ organizationMembersCreate: false })- customRender(<InviteMemberButton />)+ test('disables the button with a reason when member creation is turned off', async () => {+ setupMocks()+ customRender(<InviteMemberButton />, {+ profileContext: {+ ...PROFILE_CONTEXT,+ profile: {+ ...PROFILE_CONTEXT.profile!,+ disabled_features: ['organization_members:create'],+ },+ },+ })- const button = screen.getByRole('button', { name: /invite members/i })+ const button = screen.getByRole('button', INVITE_BUTTON)expect(button).toHaveAttribute('aria-disabled', 'true')-await userEvent.click(button)expect(screen.queryByRole('dialog')).not.toBeInTheDocument()@@ -146,191 +280,177 @@ describe('InviteMemberButton', () => {expect(screen.queryAllByText(/shift|⇧/i)).toHaveLength(0)})- describe('when the user cannot invite members', () => {- beforeEach(() => {- mockGetAssignableRoleIds.mockReturnValue([])- })-- it('shows only the permission warning, not the shortcut tooltip', async () => {- customRender(<InviteMemberButton />)- const button = screen.getByRole('button', { name: /invite members/i })- expect(button).toHaveAttribute('aria-disabled', 'true')-- await userEvent.hover(button)-- expect(- await screen.findAllByText(- 'You need additional permissions to invite members to this organization'- )- ).not.toHaveLength(0)- expect(screen.queryAllByText(/shift|⇧/i)).toHaveLength(0)- })- })-- it('renders an enabled Invite members button', () => {- customRender(<InviteMemberButton />)- expect(screen.getByRole('button', { name: /invite members/i })).toBeEnabled()- })+ test('disables the button with a permission warning when the user has no org role', async () => {+ setupMocks({ members: [buildMember({ role_ids: [] })] })+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })- it('opens the invite dialog when the button is clicked', async () => {- customRender(<InviteMemberButton />)- await openDialog()- expect(screen.getByRole('dialog')).toBeInTheDocument()- expect(screen.getByText('Invite team members')).toBeInTheDocument()+ const button = screen.getByRole('button', INVITE_BUTTON)+ await userEvent.hover(button)+ expect(+ await screen.findAllByText(+ 'You need additional permissions to invite members to this organization'+ )+ ).not.toHaveLength(0)+ expect(screen.queryAllByText(/shift|⇧/i)).toHaveLength(0)+ // Still disabled once members have loaded, not just while loading+ expect(button).toHaveAttribute('aria-disabled', 'true')})- it('renders a stacked radio option with permission guidance for each role', async () => {- customRender(<InviteMemberButton />)+ test('renders each role with its permission description and a roles docs link', async () => {+ setupMocks()+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })await openDialog()+ // Every role is rendered as a selectable card+ expect(await screen.findByText('Administrator')).toBeInTheDocument()+ expect(screen.getByText('Owner')).toBeInTheDocument()+ expect(screen.getByText('Developer')).toBeInTheDocument()+ expect(screen.getByText('Read-only')).toBeInTheDocument()expect(screen.getAllByRole('radio')).toHaveLength(4)- expect(screen.getByRole('link', { name: 'roles and permissions' })).toHaveAttribute(++ // The key safety message from the ticket: Administrator can delete projects+ expect(screen.getByText('deleting projects')).toBeInTheDocument()++ // Roles documentation is one click away (the ticket's other complaint)+ const docsLink = screen.getByRole('link', { name: /roles and permissions/i })+ expect(docsLink).toHaveAttribute('href',- 'https://supabase.com/docs/guides/platform/access-control'+ expect.stringContaining('/guides/platform/access-control'))- expect(- getRoleDescription(- 'Full access, including removing you or any other owner, deleting the organization, and transferring or deleting projects.'- )- ).toBeInTheDocument()- expect(- getRoleDescription(- 'Manage members, billing, and project settings, including removing members and deleting projects. Cannot manage organization settings or owners.'- )- ).toBeInTheDocument()- expect(- screen.getByText(- 'Manage project content, including deleting data, users, files, and Edge Functions. Cannot change settings or delete projects.'- )- ).toBeInTheDocument()- expect(- screen.getByText(- 'View resources without modifying or deleting them. SQL Editor access is limited to SELECT queries.'- )- ).toBeInTheDocument()})- it('asks for confirmation before inviting as Owner', async () => {- customRender(<InviteMemberButton />)+ test('sends emails and the default Developer role_id in the request body', async () => {+ const { invitePayloads } = setupMocks()+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })await openDialog()- await userEvent.click(screen.getByRole('radio', { name: 'Owner' }))+ await screen.findByText('Developer')+fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {target: { value: '[email protected]' },})fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))- const confirmation = await screen.findByRole('dialog', { name: 'Invite as Owner?' })- expect(mockInvite).not.toHaveBeenCalled()-- fireEvent.click(within(confirmation).getByRole('button', { name: /send invitation/i }))- await waitFor(() => {- expect(mockInvite).toHaveBeenCalledWith(- expect.objectContaining({ emails: ['[email protected]'], roleId: 4 })- )+ await waitFor(() => expect(invitePayloads).toHaveLength(1))+ expect(invitePayloads[0]).toEqual({+ emails: ['[email protected]'],+ role_id: ROLE_IDS.developer,})})- it('calls the mutation with a single email in an array', async () => {- customRender(<InviteMemberButton />)- await submitForm('[email protected]')+ test.each([+ ['Owner', ROLE_IDS.owner],+ ['Administrator', ROLE_IDS.administrator],+ ])(+ 'asks for confirmation before inviting as %s, then sends its role_id',+ async (roleName, roleId) => {+ const { invitePayloads } = setupMocks()+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await openDialog()++ await userEvent.click(await screen.findByRole('radio', { name: roleName }))+ fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {+ target: { value: '[email protected]' },+ })+ fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))++ const confirmation = await screen.findByRole('dialog', { name: `Invite as ${roleName}?` })+ expect(invitePayloads).toHaveLength(0)+ fireEvent.click(within(confirmation).getByRole('button', { name: /send invitation/i }))++ await waitFor(() => expect(invitePayloads).toHaveLength(1))+ expect(invitePayloads[0]).toEqual({ emails: ['[email protected]'], role_id: roleId })+ }+ )++ test('lowercases and de-duplicates emails before sending', async () => {+ const { invitePayloads } = setupMocks()+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await openDialog()+ await screen.findByText('Developer')- await waitFor(() => {- expect(mockInvite).toHaveBeenCalledWith(- expect.objectContaining({ emails: ['[email protected]'] })- )+ fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {})- })-- it('calls the mutation with multiple emails parsed from a comma-separated input', async () => {- customRender(<InviteMemberButton />)+ fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))- await waitFor(() => {- expect(mockInvite).toHaveBeenCalledWith(- expect.objectContaining({- })- )+ await waitFor(() => expect(invitePayloads).toHaveLength(1))+ expect(invitePayloads[0]).toEqual({+ emails: ['[email protected]', '[email protected]'],+ role_id: ROLE_IDS.developer,})})- it('lowercases emails before sending', async () => {- customRender(<InviteMemberButton />)- await submitForm('[email protected]')-- await waitFor(() => {- expect(mockInvite).toHaveBeenCalledWith(- expect.objectContaining({ emails: ['[email protected]'] })- )- })- })-- it('shows a validation error for an invalid email', async () => {- customRender(<InviteMemberButton />)- await openDialog()- fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {- target: { value: 'not-an-email' },- })- fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))+ test('shows a validation error for an invalid email', async () => {+ const { invitePayloads } = setupMocks()+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await fillAndSubmit('not-an-email')expect(await screen.findByText(/invalid email address: "not-an-email"/i)).toBeInTheDocument()- expect(mockInvite).not.toHaveBeenCalled()+ expect(invitePayloads).toHaveLength(0)})- it('shows an error toast and skips the mutation for an already-existing member', async () => {- customRender(<InviteMemberButton />)- await submitForm('[email protected]')+ test('skips the request when every email is already a member', async () => {+ const { invitePayloads } = setupMocks()+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await fillAndSubmit('[email protected]')await waitFor(() => {expect(toast.error).toHaveBeenCalledWith('[email protected] is already in this organization')})- expect(mockInvite).not.toHaveBeenCalled()+ expect(invitePayloads).toHaveLength(0)})- it('still invites new emails in a batch that also contains an existing member', async () => {- customRender(<InviteMemberButton />)- await submitForm('[email protected], [email protected]')+ test('still invites new emails in a batch that also contains an existing member', async () => {+ const { invitePayloads } = setupMocks()+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await fillAndSubmit('[email protected], [email protected]')- await waitFor(() => {- expect(toast.error).toHaveBeenCalled()- expect(mockInvite).toHaveBeenCalledWith(- expect.objectContaining({ emails: ['[email protected]'] })- )- })+ await waitFor(() => expect(invitePayloads).toHaveLength(1))+ expect(invitePayloads[0]).toEqual({ emails: ['[email protected]'], role_id: ROLE_IDS.developer })+ expect(toast.error).toHaveBeenCalledWith('[email protected] is already in this organization')})- it('shows a success toast for a single email in succeeded', async () => {- mockInvite.mockResolvedValueOnce({ succeeded: ['[email protected]'], failed: [] })- customRender(<InviteMemberButton />)- await submitForm('[email protected]')+ test('shows a plural success toast when multiple invitations succeed', async () => {+ setupMocks({+ inviteResponse: { succeeded: ['[email protected]', '[email protected]'], failed: [] },+ })+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await fillAndSubmit('[email protected], [email protected]')await waitFor(() => {- expect(toast.success).toHaveBeenCalledWith('Successfully sent invitation to new member')+ expect(toast.success).toHaveBeenCalledWith('Successfully sent invitations to 2 new members')})})- it('shows a plural success toast when multiple emails succeeded', async () => {- mockInvite.mockResolvedValueOnce({- succeeded: ['[email protected]', '[email protected]'],- failed: [],+ test('shows a success toast and a per-email error toast for a partial batch result', async () => {+ setupMocks({+ inviteResponse: {+ succeeded: ['[email protected]'],+ failed: [{ email: '[email protected]', error: 'Domain not allowed' }],+ },})- customRender(<InviteMemberButton />)- await submitForm('[email protected], [email protected]')+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await fillAndSubmit('[email protected], [email protected]')await waitFor(() => {- expect(toast.success).toHaveBeenCalledWith('Successfully sent invitations to 2 new members')+ expect(toast.success).toHaveBeenCalledWith('Successfully sent invitation to new member')+ expect(toast.error).toHaveBeenCalledWith(+ 'Failed to invite [email protected]: Domain not allowed'+ )})})- it('shows an error toast with the server error for each failed email', async () => {- mockInvite.mockResolvedValueOnce({- succeeded: [],- failed: [{ email: '[email protected]', error: 'Domain not allowed' }],+ test('shows only error toasts when every invitation fails', async () => {+ setupMocks({+ inviteResponse: {+ succeeded: [],+ failed: [{ email: '[email protected]', error: 'Domain not allowed' }],+ },})- customRender(<InviteMemberButton />)- await submitForm('[email protected]')+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await fillAndSubmit('[email protected]')await waitFor(() => {expect(toast.error).toHaveBeenCalledWith(@@ -340,19 +460,48 @@ describe('InviteMemberButton', () => {expect(toast.success).not.toHaveBeenCalled()})- it('shows both success and error toasts for a partial batch result', async () => {- mockInvite.mockResolvedValueOnce({- succeeded: ['[email protected]'],- failed: [{ email: '[email protected]', error: 'Domain not allowed' }],+ describe('project-scoped access', () => {+ test('requires at least one project when "Grant this role on all projects" is off', async () => {+ const { invitePayloads } = setupMocks({ projectScoped: true })+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await openDialog()++ const toggle = await screen.findByRole('switch')+ expect(toggle).toBeChecked()+ await userEvent.click(toggle)+ expect(toggle).not.toBeChecked()++ fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {+ target: { value: '[email protected]' },+ })+ fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))++ expect(await screen.findByText('Select at least one project')).toBeInTheDocument()+ expect(invitePayloads).toHaveLength(0)})- customRender(<InviteMemberButton />)- await submitForm('[email protected], [email protected]')- await waitFor(() => {- expect(toast.success).toHaveBeenCalledWith('Successfully sent invitation to new member')- expect(toast.error).toHaveBeenCalledWith(- 'Failed to invite [email protected]: Domain not allowed'- )+ test('sends the selected projects as role_scoped_projects when multiple are chosen', async () => {+ const { invitePayloads } = setupMocks({ projectScoped: true })+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await openDialog()++ await userEvent.click(await screen.findByRole('switch'))++ await userEvent.click(screen.getByRole('combobox'))+ await userEvent.click(await screen.findByRole('option', { name: /Alpha/ }))+ await userEvent.click(await screen.findByRole('option', { name: /Beta/ }))++ fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {+ target: { value: '[email protected]' },+ })+ fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))++ await waitFor(() => expect(invitePayloads).toHaveLength(1))+ expect(invitePayloads[0]).toEqual({+ emails: ['[email protected]'],+ role_id: ROLE_IDS.developer,+ role_scoped_projects: ['project-alpha', 'project-beta'],+ })})})})diff --git a/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.utils.test.ts b/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.utils.test.tsindex 9c8e4cff4bf..a9ffd5a32fe 100644--- a/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.utils.test.ts+++ b/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.utils.test.ts@@ -41,16 +41,8 @@ describe('parseEmails', () => {})- test('returns an empty array for an empty string', () => {- expect(parseEmails('')).toStrictEqual([])- })-- test('returns an empty array for a whitespace-only string', () => {- expect(parseEmails(' ')).toStrictEqual([])- })-- test('returns an empty array for commas only', () => {- expect(parseEmails(',,,,')).toStrictEqual([])+ test.each(['', ' ', ',,,,'])('returns an empty array for %j', (value) => {+ expect(parseEmails(value)).toStrictEqual([])})test('parses space-separated emails', () => {@@ -123,17 +115,6 @@ describe('categorizeInviteEmails', () => {})})- test('places all emails in toInvite when none match existing members', () => {- const members = [makeMember({ primary_email: '[email protected]' })]- expect(- ).toStrictEqual({- alreadyInvited: [],- alreadyMembers: [],- })- })-test('returns all-empty for an empty email list', () => {expect(categorizeInviteEmails([], [makeMember()])).toStrictEqual({alreadyInvited: [],@@ -163,10 +144,6 @@ describe('buildProjectPayload', () => {)})- test('returns a projects array when applyToOrg is false and one project is selected', () => {- expect(buildProjectPayload(false, ['ref_abc'])).toStrictEqual({ projects: ['ref_abc'] })- })-test('returns all selected projects when applyToOrg is false and multiple are selected', () => {expect(buildProjectPayload(false, ['ref_abc', 'ref_def', 'ref_ghi'])).toStrictEqual({projects: ['ref_abc', 'ref_def', 'ref_ghi'],diff --git a/apps/studio/tests/components/Organization/TeamSettings/UpdateRolesPanel.network.test.tsx b/apps/studio/tests/components/Organization/TeamSettings/UpdateRolesPanel.network.test.tsxindex 66ab5edcd4a..e9d68fffd05 100644--- a/apps/studio/tests/components/Organization/TeamSettings/UpdateRolesPanel.network.test.tsx+++ b/apps/studio/tests/components/Organization/TeamSettings/UpdateRolesPanel.network.test.tsx@@ -1,4 +1,4 @@-import { screen, waitFor } from '@testing-library/react'+import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { platformComponents as components } from 'api-types'import { mockAnimationsApi } from 'jsdom-testing-mocks'@@ -171,21 +171,10 @@ describe('UpdateRolesPanel (network)', () => {expect(screen.getByRole('option', { name: /Developer/ })).toBeInTheDocument()expect(screen.getByRole('option', { name: /Read-only/ })).toBeInTheDocument()- // The key safety message from the ticket: Administrator can delete projects+ // Every role has a permission description; the key safety message from the+ // ticket is that Administrator can delete projectsexpect(screen.getByText('deleting projects')).toBeInTheDocument()- })-- test('renders a role description for every known role', async () => {- setupMocks()- customRender(<UpdateRolesPanel visible member={MEMBER} onClose={vi.fn()} />, {- profileContext: PROFILE_CONTEXT,- })-- await userEvent.click(await screen.findByRole('combobox'))-- await waitFor(() => {- expect(screen.getByText(/deleting the organization/i)).toBeInTheDocument()- })+ expect(screen.getByText(/deleting the organization/i)).toBeInTheDocument()expect(screen.getByText(/Manage members, billing/i)).toBeInTheDocument()expect(screen.getByText(/Manage project content/i)).toBeInTheDocument()expect(screen.getByText(/limited to SELECT queries/i)).toBeInTheDocument()diff --git a/apps/studio/tests/components/SQLEditor/RoleImpersonationSelector.test.tsx b/apps/studio/tests/components/SQLEditor/RoleImpersonationSelector.test.tsxindex 022a3a73b97..aa682d4bbb2 100644--- a/apps/studio/tests/components/SQLEditor/RoleImpersonationSelector.test.tsx+++ b/apps/studio/tests/components/SQLEditor/RoleImpersonationSelector.test.tsx@@ -38,10 +38,6 @@ describe('RoleImpersonationSelectorInterface', () => {const { rerender } = customRender(<RoleImpersonationSelectorInterface state={state} />)expect(screen.queryByText('Role')).not.toBeInTheDocument()- for (const option of screen.getAllByRole('radio')) {- expect(option).toHaveClass('w-full')- expect(option.querySelector('svg')).toBeInTheDocument()- }expect(screen.getByRole('radio', { name: 'PostgresSuperuser' })).toBeChecked()expect(screen.getByText('Bypasses RLS and can return all rows.')).toBeVisible()expect(screen.getByTestId('user-settings')).toBeDisabled()diff --git a/apps/studio/tests/components/Settings/Infrastructure/ReadReplicasSection.test.tsx b/apps/studio/tests/components/Settings/Infrastructure/ReadReplicasSection.test.tsxindex 0f8fd8ac5b6..90a5ed8c0b5 100644--- a/apps/studio/tests/components/Settings/Infrastructure/ReadReplicasSection.test.tsx+++ b/apps/studio/tests/components/Settings/Infrastructure/ReadReplicasSection.test.tsx@@ -65,7 +65,6 @@ describe('ReadReplicasSection', () => {})test('renders the read replicas section with add CTA and empty state', async () => {- mockUseIsFeatureEnabled.mockReturnValue({ infrastructureReadReplicas: true })addReplicaListMocks()customRender(<ReadReplicasSection onRecommendCompute={vi.fn()} />)diff --git a/apps/studio/tests/components/interfaces/App/IndirectTaxDeclarationModal.test.tsx b/apps/studio/tests/components/interfaces/App/IndirectTaxDeclarationModal.test.tsxindex 3b221b9719b..a2d741a6314 100644--- a/apps/studio/tests/components/interfaces/App/IndirectTaxDeclarationModal.test.tsx+++ b/apps/studio/tests/components/interfaces/App/IndirectTaxDeclarationModal.test.tsx@@ -1,5 +1,7 @@+import { QueryClient } from '@tanstack/react-query'import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { platformComponents as components } from 'api-types'import { HttpResponse } from 'msw'import { toast } from 'sonner'import { describe, expect, test, vi } from 'vitest'@@ -11,6 +13,9 @@ import { customRender } from '@/tests/lib/custom-render'import { addAPIMock } from '@/tests/lib/msw'import { createMockProfileContext } from '@/tests/lib/profile-helpers'+type OrganizationResponse = components['schemas']['OrganizationResponse_Output']+type PermissionsV2Response = components['schemas']['UserPermissionsResponse_Output']+const ORG_SLUG = 'test-org'const PROFILE_CONTEXT = createMockProfileContext()@@ -42,34 +47,55 @@ function setupMocks({canUpdateBilling?: booleanrequiresDeclaration?: boolean} = {}) {+ const served = { organizations: false, permissions: false }+addAPIMock({method: 'get',path: '/platform/organizations',- response: [- createMockOrganizationResponse({- slug: ORG_SLUG,- name: 'Test Org',- requires_indirect_tax_declaration: requiresDeclaration,- }),- ],+ response: () => {+ served.organizations = true+ return HttpResponse.json<OrganizationResponse[]>([+ createMockOrganizationResponse({+ slug: ORG_SLUG,+ name: 'Test Org',+ requires_indirect_tax_declaration: requiresDeclaration,+ }),+ ])+ },})addAPIMock({method: 'get',path: '/platform/profile/permissions/v2',- response: {- organizations: [- {- slug: ORG_SLUG,- role: 'administrator',- permissions: canUpdateBilling ? [FGA_PERMISSIONS.ORGANIZATION.BILLING_WRITE] : [],- projects: [],- },- ],+ response: () => {+ served.permissions = true+ return HttpResponse.json<PermissionsV2Response>({+ organizations: [+ {+ slug: ORG_SLUG,+ role: 'administrator',+ permissions: canUpdateBilling ? [FGA_PERMISSIONS.ORGANIZATION.BILLING_WRITE] : [],+ projects: [],+ },+ ],+ })},})++ return served+}++// Asserting that the modal is absent is only meaningful once the org and permission data it+// depends on has loaded; before that it is absent regardless.+async function waitForDataToLoad(served: ReturnType<typeof setupMocks>, queryClient: QueryClient) {+ await waitFor(() => {+ expect(served).toEqual({ organizations: true, permissions: true })+ expect(queryClient.isFetching()).toBe(0)+ })}+const createQueryClient = () => new QueryClient({ defaultOptions: { queries: { retry: false } } })+describe('IndirectTaxDeclarationModal', () => {test('is non-dismissible and requires an explicit response', async () => {setupMocks()@@ -163,12 +189,12 @@ describe('IndirectTaxDeclarationModal', () => {})test('does not show for members without billing write permission', async () => {- setupMocks({ canUpdateBilling: false })- customRender(<IndirectTaxDeclarationModal />, { profileContext: PROFILE_CONTEXT })+ const served = setupMocks({ canUpdateBilling: false })+ const queryClient = createQueryClient()+ customRender(<IndirectTaxDeclarationModal />, { profileContext: PROFILE_CONTEXT, queryClient })- await waitFor(() => {- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()- })+ await waitForDataToLoad(served, queryClient)+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()})test('shows a dismissible confirmation when linked after a previous submission', async () => {@@ -189,11 +215,11 @@ describe('IndirectTaxDeclarationModal', () => {})test('does not show the submitted confirmation without the URL parameter', async () => {- setupMocks({ requiresDeclaration: false })- customRender(<IndirectTaxDeclarationModal />, { profileContext: PROFILE_CONTEXT })+ const served = setupMocks({ requiresDeclaration: false })+ const queryClient = createQueryClient()+ customRender(<IndirectTaxDeclarationModal />, { profileContext: PROFILE_CONTEXT, queryClient })- await waitFor(() => {- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()- })+ await waitForDataToLoad(served, queryClient)+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()})})diff --git a/apps/studio/tests/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.test.tsx b/apps/studio/tests/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.test.tsxindex ea786aad869..fd1e80a6990 100644--- a/apps/studio/tests/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.test.tsx+++ b/apps/studio/tests/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/AdvancedSettings.test.tsx@@ -45,24 +45,24 @@ const TestForm = () => {}describe('AdvancedSettings', () => {- it.each(numericFields)(- 'allows $label to be cleared and replaced',- async ({ label, initialValue }) => {- const user = userEvent.setup()- customRender(<TestForm />)+ // One render for all fields: each field is independent, and re-rendering per field only adds setup cost+ it('allows every numeric field to be cleared and replaced', async () => {+ const user = userEvent.setup()+ customRender(<TestForm />)- await user.click(screen.getByRole('button', { name: /Advanced settings/ }))+ await user.click(screen.getByRole('button', { name: /Advanced settings/ }))+ for (const { label, initialValue } of numericFields) {const input = screen.getByRole('spinbutton', { name: label })- expect(input).toHaveValue(initialValue)+ expect(input, label).toHaveValue(initialValue)await user.clear(input)- expect(input).toHaveValue(null)+ expect(input, label).toHaveValue(null)await user.type(input, '5')- expect(input).toHaveValue(5)+ expect(input, label).toHaveValue(5)}- )+ })it('uses the existing error while an empty required number is being edited', async () => {const user = userEvent.setup()diff --git a/apps/studio/tests/components/ui/Charts/Charts.utils.test.ts b/apps/studio/tests/components/ui/Charts/Charts.utils.test.tsindex e3ab934afce..b97f8f48c7f 100644--- a/apps/studio/tests/components/ui/Charts/Charts.utils.test.ts+++ b/apps/studio/tests/components/ui/Charts/Charts.utils.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { renderHook } from '@testing-library/react'import { describe, expect, it, test } from 'vitest'diff --git a/apps/studio/tests/components/ui/QueryBlock/QueryBlock.utils.test.ts b/apps/studio/tests/components/ui/QueryBlock/QueryBlock.utils.test.tsindex a2d5ceb372d..daf8ad41ed0 100644--- a/apps/studio/tests/components/ui/QueryBlock/QueryBlock.utils.test.ts+++ b/apps/studio/tests/components/ui/QueryBlock/QueryBlock.utils.test.ts@@ -26,11 +26,6 @@ describe('checkHasNonPositiveValues', () => {expect(checkHasNonPositiveValues(data, 'value')).toBe(true)})- it('returns true when all values are non-positive', () => {- const data = [{ value: -5 }, { value: 0 }, { value: -1 }]- expect(checkHasNonPositiveValues(data, 'value')).toBe(true)- })-it('checks only the specified key', () => {const data = [{ x: -1, y: 5 },@@ -145,20 +140,6 @@ describe('getCumulativeResults', () => {expect(output[1]).toMatchObject({ x: 'b', y: 3, label: 'bar' })})- it('handles a single row', () => {- const results = { rows: [{ x: 'a', y: 42 }] }- const config = {- type: 'bar' as const,- xKey: 'x',- yKey: 'y',- cumulative: true,- showLabels: false,- showGrid: false,- }- const output = getCumulativeResults(results, config)- expect(output).toEqual([{ x: 'a', y: 42 }])- })-// Postgres returns `bigint`, `numeric`, `money` and `count(*)` columns as// strings, so the running total must sum numerically rather than concatenate.it('sums numeric string yKey values instead of concatenating them', () => {diff --git a/apps/studio/tests/config/msw.test.ts b/apps/studio/tests/config/msw.test.tsindex 5cb569e21dc..d4d0bbed985 100644--- a/apps/studio/tests/config/msw.test.ts+++ b/apps/studio/tests/config/msw.test.ts@@ -11,9 +11,5 @@ test('MSW works as expected', async () => {})test('MSW errors on missing endpoints', async () => {- expect(async () => {- const res = await fetch(`${API_URL}/endpoint-that-doesnt-exist`)- const json = await res.json()- expect(json).toEqual({ message: '🚫 MSW missed' })- })+ await expect(fetch(`${API_URL}/endpoint-that-doesnt-exist`)).rejects.toThrow()})diff --git a/apps/studio/tests/config/router.test.tsx b/apps/studio/tests/config/router.test.tsxindex a6f0b0872a2..a0d874c1efb 100644--- a/apps/studio/tests/config/router.test.tsx+++ b/apps/studio/tests/config/router.test.tsx@@ -1,4 +1,4 @@-import { render, screen, waitFor } from '@testing-library/react'+import { act, render } from '@testing-library/react'import { expect, suite, test } from 'vitest'import { routerMock } from '../lib/route-mock'@@ -8,25 +8,12 @@ suite('Router Mock', () => {test('Router mock works as expected', async () => {const comp = render(<RouterComponent />)expect(comp.container.textContent).toContain('path: /')- expect(routerMock.pathname).toBe('/')- })-- test('Clicking on link changes the path', async () => {- const comp = render(<RouterComponent />)-- const link = screen.getByRole('link')- link.click()+ await act(() => routerMock.push('/test'))+ expect(routerMock.pathname).toBe('/test')+ expect(comp.container.textContent).toContain('path: /test')- waitFor(() => {- expect(routerMock.pathname).toBe('/test')- expect(comp.container.textContent).toContain('path: /test')- })- })-- test('Router mock is reset after each test', async () => {- const comp = render(<RouterComponent />)- expect(comp.container.textContent).toContain('path: /')- expect(routerMock.pathname).toBe('/')+ // The router mock is not reset between tests, so restore it explicitly+ routerMock.setCurrentUrl('/')})})diff --git a/apps/studio/tests/features/explain-visualizer/ExplainVisualizer.parser.test.ts b/apps/studio/tests/features/explain-visualizer/ExplainVisualizer.parser.test.tsindex d2c87e8c845..a2206257d18 100644--- a/apps/studio/tests/features/explain-visualizer/ExplainVisualizer.parser.test.ts+++ b/apps/studio/tests/features/explain-visualizer/ExplainVisualizer.parser.test.ts@@ -570,42 +570,6 @@ describe('parseExplainOutput', () => {// Should not parse invalid value at all (regex won't match)expect(result[0].rowsRemovedByFilter).toBeUndefined()})-- test('parsed numeric fields are finite for valid input', () => {- const input = toQueryPlanRows([- 'Seq Scan on users (cost=0.00..10.50 rows=100 width=36) (actual time=0.015..0.123 rows=85 loops=1)',- " Filter: (status = 'active')",- ' Rows Removed by Filter: 15',- ])-- const result = parseExplainOutput(input)- parseNodeDetails(result[0])-- expect(result).toHaveLength(1)- const node = result[0]-- // Verify all numeric values are finite- if (node.cost) {- expect(Number.isFinite(node.cost.start)).toBe(true)- expect(Number.isFinite(node.cost.end)).toBe(true)- }- if (node.actualTime) {- expect(Number.isFinite(node.actualTime.start)).toBe(true)- expect(Number.isFinite(node.actualTime.end)).toBe(true)- }- if (node.rows !== undefined) {- expect(Number.isFinite(node.rows)).toBe(true)- }- if (node.actualRows !== undefined) {- expect(Number.isFinite(node.actualRows)).toBe(true)- }- if (node.width !== undefined) {- expect(Number.isFinite(node.width)).toBe(true)- }- if (node.rowsRemovedByFilter !== undefined) {- expect(Number.isFinite(node.rowsRemovedByFilter)).toBe(true)- }- })})describe('complex real-world queries', () => {@@ -886,25 +850,7 @@ describe('calculateSummary', () => {})})- test('calculates totalCost from root node cost.end', () => {- const tree: ExplainNode[] = [- {- operation: 'Seq Scan',- details: 'on users',- cost: { start: 0, end: 45.5 },- rows: 100,- width: 36,- level: 0,- children: [],- raw: '',- },- ]-- const result = calculateSummary(tree)- expect(result.totalCost).toBe(45.5)- })-- test('calculates maxCost from maximum cost across all nodes', () => {+ test('takes totalCost from the root node and maxCost from the most expensive node', () => {const tree: ExplainNode[] = [{operation: 'Limit',diff --git a/apps/studio/tests/features/logs/LogTable.test.tsx b/apps/studio/tests/features/logs/LogTable.test.tsxindex 05e0d20b348..e4f78147a96 100644--- a/apps/studio/tests/features/logs/LogTable.test.tsx+++ b/apps/studio/tests/features/logs/LogTable.test.tsx@@ -169,96 +169,23 @@ const LOG_DATA = {},}-test('can display log data', async () => {- render(- <>- <LogTable projectRef="default" data={[LOG_DATA]} />- </>- )-- await screen.findAllByText(LOG_DATA.timestamp)-})--test('Shows total results', async () => {+test('displays log data and the total result count', async () => {render(<LogTable projectRef="default" data={[LOG_DATA]} />)- await screen.getByText(/results \(1\)/i)-})--test('can run if no queryType provided', async () => {- const mockRun = vi.fn()-- render(- <LogTable- projectRef="projectRef"- data={[- {- id: 'some-uuid',- timestamp: 1621323232312,- event_message: 'some event happened',- metadata: {- my_key: 'something_value',- },- },- ]}- onRun={mockRun}- />- )-- const run = await screen.findByText('Run')- await userEvent.click(run)- // expect(mockRun).toBeCalled()-})--test('can run if no queryType provided', async () => {- const mockRun = vi.fn()-- render(- <LogTable- data={[- {- id: 'some-uuid',- timestamp: 1621323232312,- event_message: 'some event happened',- metadata: {- my_key: 'something_value',- },- },- ]}- projectRef="abcd"- onRun={mockRun}- />- )-- const run = await screen.findByText('Run')- await userEvent.click(run)- // expect(mockRun).toBeCalled()+ await screen.findAllByText(LOG_DATA.timestamp)+ expect(screen.getByText(/results \(1\)/i)).toBeInTheDocument()})test('dedupes log lines with exact id', async () => {- // chronological mode requires 4 columns- render(- <LogTable- projectRef="projectRef"- data={[- {- id: 'some-uuid',- timestamp: 1621323232312,- event_message: 'some event happened',- metadata: {},- },- {- id: 'some-uuid',- timestamp: 1621323232312,- event_message: 'some event happened',- metadata: {},- },- ]}- />- )+ const duplicate = {+ id: 'some-uuid',+ timestamp: 1621323232312,+ event_message: 'some event happened',+ metadata: {},+ }+ render(<LogTable projectRef="projectRef" data={[duplicate, { ...duplicate }]} />)- // should only have one element, this line will fail if there are >1 element- await screen.findByText('timestamp')+ expect(await screen.findAllByText(/some event happened/)).toHaveLength(1)})test('can display standard preview table columns', async () => {@@ -269,9 +196,9 @@ test('can display standard preview table columns', async () => {data={[{ id: '12345', event_message: 'some event message', timestamp: fakeMicroTimestamp }]}/>)- await waitFor(() => screen.getByText(/some event message/))- await expect(screen.findByText(/12345/)).rejects.toThrow()- await expect(screen.findByText(fakeMicroTimestamp)).rejects.toThrow()+ await screen.findByText(/some event message/)+ expect(screen.queryByText(/12345/)).not.toBeInTheDocument()+ expect(screen.queryByText(fakeMicroTimestamp)).not.toBeInTheDocument()})test("closes the selection if the selected row's data changes", async () => {@@ -292,8 +219,8 @@ test("closes the selection if the selected row's data changes", async () => {data={[{ id: '2', event_message: 'some other message', timestamp: fakeMicroTimestamp }]}/>)- await expect(screen.findByText(/some event message/)).rejects.toThrow()await screen.findByText(/some other message/)+ expect(screen.queryByText(/some event message/)).not.toBeInTheDocument()})enum QueryType {@@ -365,21 +292,14 @@ test.each([])('table col renderer for $queryType', async ({ queryType, data, includes, excludes }) => {render(<LogTable projectRef="ref" queryType={queryType} data={data} />)- await Promise.all([- ...includes.map((text) => screen.findByText(text)),- ...excludes.map((text) => expect(screen.findByText(text)).rejects.toThrow()),- ])+ await Promise.all(includes.map((text) => screen.findByText(text)))+ excludes.forEach((text) => expect(screen.queryByText(text)).not.toBeInTheDocument())})-test('error message handling', async () => {- // Render LogTable with error as a string+test('displays a string error message', () => {render(<LogTable projectRef="ref" error={'some error message'} />)- expect(screen.getByText(`some error message`)).toBeTruthy()-- // Rerender LogTable with error as null- render(<LogTable projectRef="ref" error={null} />)- // Add any additional assertions if LogTable behaves differently when error is null+ expect(screen.getByText('some error message')).toBeInTheDocument()})test('no results message handling', async () => {@@ -447,20 +367,6 @@ const shiftClick = async (user: ReturnType<typeof userEvent.setup>, element: Eleawait user.keyboard('{/Shift}')}-test('shift-click selects the range between the anchor row and the clicked row', async () => {- const user = userEvent.setup()- render(<LogTable projectRef="projectRef" data={MULTI_SELECT_LOGS} />)-- const checkboxes = getRowCheckboxes()- expect(checkboxes).toHaveLength(MULTI_SELECT_LOGS.length)-- await user.click(checkboxes[1])- await shiftClick(user, getRowCheckboxes()[4])-- expectCheckedIndexes([1, 2, 3, 4])- await screen.findByText('4 rows selected')-})-test('shift-click without an anchor toggles only the clicked row', async () => {const user = userEvent.setup()render(<LogTable projectRef="projectRef" data={MULTI_SELECT_LOGS} />)@@ -471,13 +377,15 @@ test('shift-click without an anchor toggles only the clicked row', async () => {await screen.findByText('1 row selected')})-test('shift-click on a selected row deselects back to the anchor, leaving the anchor checked', async () => {+test('shift-click selects the range from the anchor, and shift-clicking a selected row deselects back to the anchor', async () => {const user = userEvent.setup()render(<LogTable projectRef="projectRef" data={MULTI_SELECT_LOGS} />)+ expect(getRowCheckboxes()).toHaveLength(MULTI_SELECT_LOGS.length)await user.click(getRowCheckboxes()[1])await shiftClick(user, getRowCheckboxes()[4])expectCheckedIndexes([1, 2, 3, 4])+ await screen.findByText('4 rows selected')// Row 4 is now the anchor and is never modified, so only it stays checkedawait shiftClick(user, getRowCheckboxes()[1])diff --git a/apps/studio/tests/features/logs/Logs.Datepickers.test.tsx b/apps/studio/tests/features/logs/Logs.Datepickers.test.tsxindex 71ae5d750f0..e39ddeb2c1b 100644--- a/apps/studio/tests/features/logs/Logs.Datepickers.test.tsx+++ b/apps/studio/tests/features/logs/Logs.Datepickers.test.tsx@@ -185,11 +185,6 @@ describe('parseCustomInput', () => {})describe('generateDynamicHelper', () => {- test('generates helper with correct text', () => {- const helper = generateDynamicHelper(5, 'hour')- expect(helper.text).toBe('Last 5 hours')- })-test('uses singular form when value is 1', () => {expect(generateDynamicHelper(1, 'minute').text).toBe('Last 1 minute')expect(generateDynamicHelper(1, 'hour').text).toBe('Last 1 hour')@@ -273,24 +268,6 @@ test('renders warning', async () => {await screen.findByText(RegExp(from.format('DD MMM')))})-test('renders dates in local time', async () => {- const from = dayjs().subtract(1, 'days')- const to = dayjs()- render(- <LogsDatePicker- helpers={PREVIEWER_DATEPICKER_HELPERS}- onSubmit={mockFn}- value={{- from: from.toISOString(),- to: to.toISOString(),- }}- />- )- // renders time locally- await userEvent.click(await screen.findByText(RegExp(from.format('DD MMM'))))- await screen.findByText(RegExp(from.format('DD MMM')))-})-test('renders datepicker selected dates in local time', async () => {const from = dayjs().date(25)const to = dayjs().date(27)@@ -332,28 +309,26 @@ test('datepicker onSubmit will return ISO string of selected dates', async () =>)// open the datepicker- userEvent.click(screen.getByText(/13:00/i))+ await userEvent.click(screen.getByText(/13:00/i))const day15 = dayjs().date(15)const day16 = day15.add(1, 'day')// Find and click on first dateconst day15Element = await screen.findByText(day15.format('D'))- userEvent.dblClick(day15Element)+ await userEvent.dblClick(day15Element)// Find and click on second dateconst day16Element = await screen.findByText(day16.format('D'))- userEvent.click(day16Element)+ await userEvent.click(day16Element)await userEvent.click(await screen.findByText('Apply'))- expect(mockFn).toBeCalled()-- const call = mockFn.mock.calls[0][0]-- expect(call).toMatchObject({- from: dayjs().date(day15.date()).hour(13).minute(0).second(0).millisecond(0).toISOString(),- to: dayjs().date(day16.date()).hour(23).minute(59).second(59).millisecond(0).toISOString(),- })+ expect(mockFn).toHaveBeenCalledWith(+ expect.objectContaining({+ from: dayjs().date(day15.date()).hour(13).minute(0).second(0).millisecond(0).toISOString(),+ to: dayjs().date(day16.date()).hour(23).minute(59).second(59).millisecond(0).toISOString(),+ })+ )})test('disabled helpers are disabled', async () => {@@ -385,7 +360,7 @@ test('disabled helpers are disabled', async () => {)// click the datepicker- userEvent.click(screen.getByText('Last 7 days'))+ await userEvent.click(screen.getByText('Last 7 days'))const disabledHelperContainer = await screen.findByText(/last 30 days/i)@@ -396,31 +371,6 @@ test('disabled helpers are disabled', async () => {expect(disabledButton.getAttribute('aria-disabled')).toBe('true')})-test('passing a value prop shows the correct dates in the label', async () => {- const from = dayjs().subtract(10, 'days')- const to = dayjs()-- render(- <LogsDatePicker- helpers={[]}- value={{ from: from.toISOString(), to: to.toISOString() }}- onSubmit={mockFn}- />- )-- await screen.findByText(- `${from.format('DD MMM')}, ${from.format('HH:mm')} - ${to.format('DD MMM')}, ${to.format('HH:mm')}`- )-- // change the date- userEvent.click(await screen.findByText(RegExp(from.format('DD MMM'))))- userEvent.click(await screen.findByText(RegExp(to.format('DD MMM'))))-- await screen.findByText(- `${from.format('DD MMM')}, ${from.format('HH:mm')} - ${to.format('DD MMM')}, ${to.format('HH:mm')}`- )-})-test('opening with an unparseable date value (legacy epoch-ms its/ite) does not crash', async () => {render(<LogsDatePickerdiff --git a/apps/studio/tests/features/logs/Logs.utils.test.ts b/apps/studio/tests/features/logs/Logs.utils.test.tsindex c94fd16700e..64664dc21d3 100644--- a/apps/studio/tests/features/logs/Logs.utils.test.ts+++ b/apps/studio/tests/features/logs/Logs.utils.test.ts@@ -29,39 +29,6 @@ describe('fillTimeseries', () => {expect(result[60]).toEqual({ timestamp: '2023-01-01T01:00:00.000Z', value: 0 })})- test('should normalize timestamps when data exceeds minPointsToFill', () => {- const data = [- { timestamp: '2023-01-01T00:00:00.000Z', value: 1 },- { timestamp: '2023-01-01T00:01:00.000Z', value: 2 },- { timestamp: '2023-01-01T00:02:00.000Z', value: 3 },- { timestamp: '2023-01-01T00:03:00.000Z', value: 4 },- { timestamp: '2023-01-01T00:04:00.000Z', value: 5 },- { timestamp: '2023-01-01T00:05:00.000Z', value: 6 },- { timestamp: '2023-01-01T00:06:00.000Z', value: 7 },- { timestamp: '2023-01-01T00:07:00.000Z', value: 8 },- { timestamp: '2023-01-01T00:08:00.000Z', value: 9 },- { timestamp: '2023-01-01T00:09:00.000Z', value: 10 },- { timestamp: '2023-01-01T00:10:00.000Z', value: 11 },- { timestamp: '2023-01-01T00:11:00.000Z', value: 12 },- { timestamp: '2023-01-01T00:12:00.000Z', value: 13 },- { timestamp: '2023-01-01T00:13:00.000Z', value: 14 },- { timestamp: '2023-01-01T00:14:00.000Z', value: 15 },- { timestamp: '2023-01-01T00:15:00.000Z', value: 16 },- { timestamp: '2023-01-01T00:16:00.000Z', value: 17 },- { timestamp: '2023-01-01T00:17:00.000Z', value: 18 },- { timestamp: '2023-01-01T00:18:00.000Z', value: 19 },- { timestamp: '2023-01-01T00:19:00.000Z', value: 20 },- { timestamp: '2023-01-01T00:20:00.000Z', value: 21 },- ]- const result = fillTimeseries(data, 'timestamp', 'value', 0, undefined, undefined, 20)-- // Should return normalized data without filling gaps- expect(result).toHaveLength(21)- result.forEach((item) => {- expect(item.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)- })- })-test('should fill gaps in sparse data with 1-minute intervals', () => {const min = '2023-01-01T00:00:00.000Z'const max = '2023-01-01T00:04:00.000Z'@@ -112,10 +79,6 @@ describe('fillTimeseries', () => {// Test 2-minute intervals: 00:00, 00:02, 00:04, 00:05, 00:06, 00:08, 00:10 = 7 pointsconst result2m = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, '2m')- console.log(- '2m intervals:',- result2m.map((r) => r.timestamp)- )expect(result2m).toHaveLength(7)// Test 1-hour intervals: 00:00, 01:00, 02:00 with existing data at 00:05 = 4 points@@ -201,7 +164,7 @@ describe('fillTimeseries', () => {})})- test('should not fill gaps when data is dense enough', () => {+ test('should not fill gaps when data exceeds minPointsToFill', () => {const data = Array.from({ length: 25 }, (_, i) => ({timestamp: dayjs.utc('2023-01-01T00:00:00.000Z').add(i, 'minute').toISOString(),value: i,@@ -209,7 +172,6 @@ describe('fillTimeseries', () => {const result = fillTimeseries(data, 'timestamp', 'value', 0, undefined, undefined, 20)- expect(result).toHaveLength(25)expect(result).toEqual(data)})@@ -260,8 +222,6 @@ describe('fillTimeseries', () => {const result = fillTimeseries(data, 'timestamp', 'value', 0)expect(result[0]).toEqual(data[0])- expect(result[0].extra).toBe('data')- expect(result[0].nested).toEqual({ prop: 'value' })})test('should handle empty value keys array', () => {diff --git a/apps/studio/tests/features/logs/LogsFilterPopover.test.tsx b/apps/studio/tests/features/logs/LogsFilterPopover.test.tsxindex 057ec714abe..ac3564797f5 100644--- a/apps/studio/tests/features/logs/LogsFilterPopover.test.tsx+++ b/apps/studio/tests/features/logs/LogsFilterPopover.test.tsx@@ -1,4 +1,4 @@-import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { fireEvent, render, screen } from '@testing-library/react'import { describe, expect, it, vi } from 'vitest'import LogsFilterPopover from '@/components/interfaces/Settings/Logs/LogsFilterPopover'@@ -28,7 +28,7 @@ describe('LogsFilterPopover', () => {},}- it('renders with initial props and stays closed', () => {+ const renderPopover = () => {const onFiltersChange = vi.fn()render(<LogsFilterPopover@@ -38,72 +38,28 @@ describe('LogsFilterPopover', () => {buttonClassName=""/>)+ return { onFiltersChange }+ }- expect(screen.getByText('Severity')).toBeInTheDocument()- expect(screen.queryByText('Error level logs')).not.toBeInTheDocument()- })-- it('opens when clicked and shows options', async () => {- const onFiltersChange = vi.fn()- render(- <LogsFilterPopover- options={mockOptions}- filters={mockFilters}- onFiltersChange={onFiltersChange}- buttonClassName=""- />- )-- fireEvent.click(screen.getByText('Severity'))-- await waitFor(() => {- expect(screen.getByText('Error level logs')).toBeInTheDocument()- expect(screen.getByText('Warning level logs')).toBeInTheDocument()- })- })+ it('starts closed, then opens to show options reflecting the initial filter values', async () => {+ renderPopover()- it('reflects initial filter values correctly', async () => {- const onFiltersChange = vi.fn()- render(- <LogsFilterPopover- options={mockOptions}- filters={mockFilters}- onFiltersChange={onFiltersChange}- buttonClassName=""- />- )+ expect(screen.queryByText('Error level logs')).not.toBeInTheDocument()fireEvent.click(screen.getByText('Severity'))- await waitFor(() => {- expect(screen.getByText('Error level logs')).toBeInTheDocument()- })-- const errorCheckbox = document.getElementById('severity.error')!- const warningCheckbox = document.getElementById('severity.warn')!-- expect(errorCheckbox).toHaveAttribute('aria-checked', 'true')- expect(warningCheckbox).toHaveAttribute('aria-checked', 'false')+ expect(await screen.findByText('Error level logs')).toBeInTheDocument()+ expect(screen.getByText('Warning level logs')).toBeInTheDocument()+ expect(document.getElementById('severity.error')).toHaveAttribute('aria-checked', 'true')+ expect(document.getElementById('severity.warn')).toHaveAttribute('aria-checked', 'false')})it('calls onFiltersChange when applying filters', async () => {- const onFiltersChange = vi.fn()- render(- <LogsFilterPopover- options={mockOptions}- filters={mockFilters}- onFiltersChange={onFiltersChange}- buttonClassName=""- />- )+ const { onFiltersChange } = renderPopover()fireEvent.click(screen.getByText('Severity'))-- await waitFor(() => {- const warningButton = screen.getByText('Warning')- fireEvent.click(warningButton)- fireEvent.click(screen.getByRole('button', { name: 'Apply' }))- })+ fireEvent.click(await screen.findByText('Warning'))+ fireEvent.click(screen.getByRole('button', { name: 'Apply' }))expect(onFiltersChange).toHaveBeenCalledWith({severity: {@@ -114,49 +70,13 @@ describe('LogsFilterPopover', () => {})it('clears filters when clicking clear button', async () => {- const onFiltersChange = vi.fn()- render(- <LogsFilterPopover- options={mockOptions}- filters={mockFilters}- onFiltersChange={onFiltersChange}- buttonClassName=""- />- )+ const { onFiltersChange } = renderPopover()fireEvent.click(screen.getByText('Severity'))-- await waitFor(() => {- fireEvent.click(screen.getByText('Clear'))- })+ fireEvent.click(await screen.findByText('Clear'))expect(onFiltersChange).toHaveBeenCalledWith({severity: {},})})-- it('closes popover when clicking outside', async () => {- const onFiltersChange = vi.fn()- render(- <LogsFilterPopover- options={mockOptions}- filters={mockFilters}- onFiltersChange={onFiltersChange}- buttonClassName=""- />- )-- fireEvent.click(screen.getByText('Severity'))-- await waitFor(() => {- expect(screen.getByText('Error level logs')).toBeInTheDocument()- })-- // Simulate clicking outside by triggering a change in open state- fireEvent.keyDown(document.body, { key: 'Escape' })-- await waitFor(() => {- expect(screen.queryByText('Error level logs')).not.toBeInTheDocument()- })- })})diff --git a/apps/studio/tests/features/logs/LogsPreviewer.test.tsx b/apps/studio/tests/features/logs/LogsPreviewer.test.tsxindex fec11b873a4..6f05d54135b 100644--- a/apps/studio/tests/features/logs/LogsPreviewer.test.tsx+++ b/apps/studio/tests/features/logs/LogsPreviewer.test.tsx@@ -65,10 +65,6 @@ test('search loads with whatever is on the URL', async () => {await waitFor(() => {expect(screen.getByRole('textbox')).toHaveValue('test-search-box-value')})-- await waitFor(() => {- expect(screen.getByRole('textbox')).not.toHaveValue('WRONGVALUE!🪿')- })})test('useLogsPreview returns data from MSW', async () => {@@ -79,18 +75,13 @@ test('useLogsPreview returns data from MSW', async () => {}))- await waitFor(() => {- expect(result.current.isLoading).toBe(false)- })-await waitFor(() => {expect(result.current.logData.length).toBeGreaterThan(0)})-expect(result.current.logData).toEqual(LOGS_API_MOCKS.result)})-test('LogsPreviewer passes API data to LogTable', async () => {+test('LogsPreviewer passes API data to LogTable and offers loading older logs', async () => {customRender(<LogsPreviewer queryType="api" projectRef="default" tableName={LogsTableName.EDGE} />)@@ -100,6 +91,7 @@ test('LogsPreviewer passes API data to LogTable', async () => {await waitFor(() => {expect(screen.getAllByText(firstLogEventMessage)[0]).toBeInTheDocument()})+ expect(await screen.findByRole('button', { name: /Load older/i })).toBeEnabled()})test('can toggle log event chart', async () => {@@ -120,24 +112,6 @@ test('can toggle log event chart', async () => {})})-test('can click load older', async () => {- customRender(- <LogsPreviewer queryType="api" projectRef="default" tableName={LogsTableName.EDGE} />- )-- const loadOlder = await waitFor(- async () => await screen.findByRole('button', { name: /Load older/i }),- { timeout: 10000 }- )-- const handleClick = vi.fn()- loadOlder.addEventListener('click', handleClick)-- await userEvent.click(loadOlder)-- expect(handleClick).toHaveBeenCalled()-})-test('loads its/ite from the URL into the date picker and opens without crashing', async () => {const its = dayjs('2024-01-15T12:00:00.000Z')const ite = dayjs('2024-01-15T12:02:00.000Z')@@ -155,84 +129,73 @@ test('loads its/ite from the URL into the date picker and opens without crashingdescribe('calculateBarClickTimeRange', () => {const clickedTime = '2024-01-15T12:30:00.000Z'- test('uses 15-second range for time ranges less than 2 minutes', () => {- const rangeStart = '2024-01-15T12:00:00.000Z'- const rangeEnd = '2024-01-15T12:01:30.000Z' // 1.5 minutes-- const result = calculateBarClickTimeRange(rangeStart, rangeEnd, clickedTime)-- expect(result.start).toBe('2024-01-15T12:29:52.500Z') // 7.5 seconds before- expect(result.end).toBe('2024-01-15T12:30:07.500Z') // 7.5 seconds after- })-- test('uses 2-minute range for time ranges between 2 minutes and 1 hour', () => {- const rangeStart = '2024-01-15T12:00:00.000Z'- const rangeEnd = '2024-01-15T12:30:00.000Z' // 30 minutes-- const result = calculateBarClickTimeRange(rangeStart, rangeEnd, clickedTime)-- expect(result.start).toBe('2024-01-15T12:29:00.000Z') // 1 minute before- expect(result.end).toBe('2024-01-15T12:31:00.000Z') // 1 minute after- })-- test('uses 5-minute range for time ranges between 1 and 12 hours', () => {- const rangeStart = '2024-01-15T10:00:00.000Z'- const rangeEnd = '2024-01-15T14:00:00.000Z' // 4 hours-- const result = calculateBarClickTimeRange(rangeStart, rangeEnd, clickedTime)-- expect(result.start).toBe('2024-01-15T12:27:30.000Z') // 2.5 minutes before- expect(result.end).toBe('2024-01-15T12:32:30.000Z') // 2.5 minutes after- })-- test('uses 1-hour range for time ranges 12 hours or more', () => {- const rangeStart = '2024-01-15T00:00:00.000Z'- const rangeEnd = '2024-01-15T24:00:00.000Z' // 24 hours-- const result = calculateBarClickTimeRange(rangeStart, rangeEnd, clickedTime)-- expect(result.start).toBe('2024-01-15T12:00:00.000Z') // 30 minutes before- expect(result.end).toBe('2024-01-15T13:00:00.000Z') // 30 minutes after- })-- test('handles edge case of exactly 2 minutes range', () => {- const rangeStart = '2024-01-15T12:00:00.000Z'- const rangeEnd = '2024-01-15T12:02:00.000Z' // exactly 2 minutes-- const result = calculateBarClickTimeRange(rangeStart, rangeEnd, clickedTime)-- expect(result.start).toBe('2024-01-15T12:29:00.000Z') // 1 minute before- expect(result.end).toBe('2024-01-15T12:31:00.000Z') // 1 minute after- })-- test('handles edge case of exactly 1 hour range', () => {- const rangeStart = '2024-01-15T12:00:00.000Z'- const rangeEnd = '2024-01-15T13:00:00.000Z' // exactly 1 hour-- const result = calculateBarClickTimeRange(rangeStart, rangeEnd, clickedTime)-- expect(result.start).toBe('2024-01-15T12:27:30.000Z') // 2.5 minutes before- expect(result.end).toBe('2024-01-15T12:32:30.000Z') // 2.5 minutes after- })-- test('handles edge case of exactly 12 hours range', () => {- const rangeStart = '2024-01-15T00:00:00.000Z'- const rangeEnd = '2024-01-15T12:00:00.000Z' // exactly 12 hours-- const result = calculateBarClickTimeRange(rangeStart, rangeEnd, clickedTime)-- expect(result.start).toBe('2024-01-15T12:00:00.000Z') // 30 minutes before- expect(result.end).toBe('2024-01-15T13:00:00.000Z') // 30 minutes after+ test.each([+ {+ range: 'under 2 minutes uses a 15-second window',+ rangeStart: '2024-01-15T12:00:00.000Z',+ rangeEnd: '2024-01-15T12:01:30.000Z',+ start: '2024-01-15T12:29:52.500Z',+ end: '2024-01-15T12:30:07.500Z',+ },+ {+ range: 'exactly 2 minutes uses a 2-minute window',+ rangeStart: '2024-01-15T12:00:00.000Z',+ rangeEnd: '2024-01-15T12:02:00.000Z',+ start: '2024-01-15T12:29:00.000Z',+ end: '2024-01-15T12:31:00.000Z',+ },+ {+ range: 'between 2 minutes and 1 hour uses a 2-minute window',+ rangeStart: '2024-01-15T12:00:00.000Z',+ rangeEnd: '2024-01-15T12:30:00.000Z',+ start: '2024-01-15T12:29:00.000Z',+ end: '2024-01-15T12:31:00.000Z',+ },+ {+ range: 'exactly 1 hour uses a 5-minute window',+ rangeStart: '2024-01-15T12:00:00.000Z',+ rangeEnd: '2024-01-15T13:00:00.000Z',+ start: '2024-01-15T12:27:30.000Z',+ end: '2024-01-15T12:32:30.000Z',+ },+ {+ range: 'between 1 and 12 hours uses a 5-minute window',+ rangeStart: '2024-01-15T10:00:00.000Z',+ rangeEnd: '2024-01-15T14:00:00.000Z',+ start: '2024-01-15T12:27:30.000Z',+ end: '2024-01-15T12:32:30.000Z',+ },+ {+ range: 'exactly 12 hours uses a 1-hour window',+ rangeStart: '2024-01-15T00:00:00.000Z',+ rangeEnd: '2024-01-15T12:00:00.000Z',+ start: '2024-01-15T12:00:00.000Z',+ end: '2024-01-15T13:00:00.000Z',+ },+ {+ range: 'over 12 hours uses a 1-hour window',+ rangeStart: '2024-01-15T00:00:00.000Z',+ rangeEnd: '2024-01-15T24:00:00.000Z',+ start: '2024-01-15T12:00:00.000Z',+ end: '2024-01-15T13:00:00.000Z',+ },+ ])('a range $range centred on the clicked time', ({ rangeStart, rangeEnd, start, end }) => {+ expect(calculateBarClickTimeRange(rangeStart, rangeEnd, clickedTime)).toMatchObject({+ start,+ end,+ })})- test('handles different clicked timestamps correctly', () => {- const rangeStart = '2024-01-15T00:00:00.000Z'- const rangeEnd = '2024-01-15T24:00:00.000Z' // 24 hours- const differentClickedTime = '2024-01-15T06:15:30.000Z'-- const result = calculateBarClickTimeRange(rangeStart, rangeEnd, differentClickedTime)+ test('centres the window on whichever timestamp was clicked', () => {+ const result = calculateBarClickTimeRange(+ '2024-01-15T00:00:00.000Z',+ '2024-01-15T24:00:00.000Z',+ '2024-01-15T06:15:30.000Z'+ )- expect(result.start).toBe('2024-01-15T05:45:30.000Z') // 30 minutes before- expect(result.end).toBe('2024-01-15T06:45:30.000Z') // 30 minutes after+ expect(result).toMatchObject({+ start: '2024-01-15T05:45:30.000Z',+ end: '2024-01-15T06:45:30.000Z',+ })})})diff --git a/apps/studio/tests/features/logs/LogsQueryPanel.test.tsx b/apps/studio/tests/features/logs/LogsQueryPanel.test.tsxdeleted file mode 100644index e6d2a6556dd..00000000000--- a/apps/studio/tests/features/logs/LogsQueryPanel.test.tsx+++ /dev/null@@ -1,19 +0,0 @@-import { screen } from '@testing-library/react'-import { expect, test } from 'vitest'--import { LogsQueryPanel } from '@/components/interfaces/Settings/Logs/LogsQueryPanel'-import { render } from '@/tests/helpers'--test('run and clear', async () => {- render(- <LogsQueryPanel- value={{ from: '', to: '', isHelper: false }}- onDateChange={() => {}}- onSelectSource={() => {}}- onSelectTemplate={() => {}}- warnings={[]}- templates={[]}- />- )- await expect(screen.findByPlaceholderText(/Search/)).rejects.toThrow()-})diff --git a/apps/studio/tests/features/logs/logs-query.test.tsx b/apps/studio/tests/features/logs/logs-query.test.tsxdeleted file mode 100644index 5be8f1a0a11..00000000000--- a/apps/studio/tests/features/logs/logs-query.test.tsx+++ /dev/null@@ -1,169 +0,0 @@-import { fireEvent, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import dayjs from 'dayjs'-import { beforeAll, describe, expect, test, vi } from 'vitest'--import { LogsExplorerPage } from '@/pages/project/[ref]/logs/explorer/index'-import { clickDropdown } from '@/tests/helpers'-import { customRender as render } from '@/tests/lib/custom-render'-import { routerMock } from '@/tests/lib/route-mock'--const router = routerMock--beforeAll(() => {- vi.doMock('common', async (importOriginal: () => Promise<any>) => {- const mod = await importOriginal()-- return {- ...mod,- IS_PLATFORM: true,- useIsLoggedIn: vi.fn(),- useParams: vi.fn(() => ({ ref: 'projectRef' })),- }- })- vi.mock('@/lib/gotrue', () => ({- auth: { onAuthStateChange: vi.fn() },- }))-})--test.skip('can display log data', async () => {- const { container } = render(<LogsExplorerPage dehydratedState={{}} />)- let editor = container.querySelector('.monaco-editor')- await waitFor(() => {- editor = container.querySelector('.monaco-editor')- expect(editor).toBeTruthy()- })-- if (!editor) {- throw new Error('editor not found')- }-- await userEvent.type(editor, 'select \ncount(*) as my_count \nfrom edge_logs')- await screen.findByText(/Save query/)- const button = await screen.findByTitle('run-logs-query')- await userEvent.click(button)- const row = await screen.findByText(/timestamp/)- await userEvent.click(row)- await screen.findByText(/metadata/)- await screen.findByText(/request/)-})--test('q= query param will populate the query input', async () => {- router.query = { ...router.query, type: 'api', q: 'some_query' }-- render(<LogsExplorerPage dehydratedState={{}} />)-})--test('ite= and its= query param will populate the datepicker', async () => {- const start = dayjs().subtract(1, 'day')- const end = dayjs()- router.query = {- ...router.query,- type: 'api',- q: 'some_query',- its: start.toISOString(),- ite: end.toISOString(),- }-- render(<LogsExplorerPage dehydratedState={{}} />)-})--test.skip('custom sql querying', async () => {- const { container } = render(<LogsExplorerPage dehydratedState={{}} />)-- let editor = container.querySelector('.monaco-editor')- if (!editor) {- throw new Error('editor not found')- }-- // type new query- await userEvent.type(editor, 'select \ncount(*) as my_count \nfrom edge_logs')-- // run query by button- await userEvent.click(await screen.findByText('Run'))-- // run query by editor- await userEvent.type(editor, '\nlimit 123{ctrl}{enter}')-- await screen.findByText(/my_count/) //column header- const rowValue = await screen.findByText(/12345/) // row value-- // clicking on the row value should not show log selection panel- await userEvent.click(rowValue)- await expect(screen.findByText(/Metadata/)).rejects.toThrow()-- // should not see chronological features- await expect(screen.findByText(/Load older/)).rejects.toThrow()-})--test.skip('bug: can edit query after selecting a log', async () => {- const { container } = render(<LogsExplorerPage dehydratedState={{}} />)- // run default query- await userEvent.click(await screen.findByText('Run'))- const rowValue = await screen.findByText(/12345/) // row value- // open up an show selection panel- await userEvent.click(rowValue)- await screen.findByText('Copy')-- // change the query- let editor = container.querySelector('.monaco-editor')-- if (!editor) {- throw new Error('editor not found')- }-- // type new query- await userEvent.click(editor)- await userEvent.type(editor, ' something')- await userEvent.type(editor, '\nsomething{ctrl}{enter}')- await userEvent.click(await screen.findByText('Run'))-- // closes the selection panel- await expect(screen.findByText('Copy')).rejects.toThrow()-})--test.skip('query warnings', async () => {- router.query = {- ...router.query,- q: 'some_query',- its: dayjs().subtract(10, 'days').toISOString(),- ite: dayjs().toISOString(),- }-- render(<LogsExplorerPage dehydratedState={{}} />)- await screen.findByText('1 warning')-})--test('field reference', async () => {- render(<LogsExplorerPage dehydratedState={{}} />)- await userEvent.click(await screen.findByText('Field Reference'))- await screen.findByText('metadata.request.cf.asOrganization')-})--describe.each(['free', 'pro', 'team', 'enterprise'])('upgrade modal for %s', (key) => {- test.skip('based on query params', async () => {- router.query = {- ...router.query,- q: 'some_query',- its: dayjs().subtract(5, 'month').toISOString(),- ite: dayjs().toISOString(),- }-- render(<LogsExplorerPage dehydratedState={{}} />)- await screen.findByText(/Log retention/) // assert modal title is present- })- test.skip('based on datepicker helpers', async () => {- render(<LogsExplorerPage dehydratedState={{}} />)- clickDropdown(screen.getByText('Last hour'))- await waitFor(async () => {- const option = await screen.findByText('Last 3 days')- fireEvent.click(option)- })- // only Free Plan will show modal- if (key === 'free') {- await screen.findByText('Log retention') // assert modal title is present- } else {- await expect(screen.findByText('Log retention')).rejects.toThrow()- }- })-})diff --git a/apps/studio/tests/features/reports/storage-report.test.tsx b/apps/studio/tests/features/reports/storage-report.test.tsxdeleted file mode 100644index ad77ae4fee7..00000000000--- a/apps/studio/tests/features/reports/storage-report.test.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { screen } from '@testing-library/react'-import { test } from 'vitest'--import { StorageReport } from '@/pages/project/[ref]/observability/storage'-import { render } from '@/tests/helpers'--// [Joshen] Mock data for ApiReport is in __mocks__/hooks/useStorageReport-// I don't think this is an ideal set up as the mock data is not clear in this file itself-// But this is the method that worked for me after hours of wrangling with jest.spyOn and jest.mock-// which for some reason none of them worked when I was trying to mock the data within the file itself-// I'd be keen to see how we can do this better if anyone is more familiar to jest 🙏--test.skip(`Render static elements`, async () => {- render(<StorageReport dehydratedState={{}} />)- await screen.findByText('Request Caching')- await screen.findByText(/Last 24 hours/)-})--test.skip('Render top cache misses', async () => {- render(<StorageReport dehydratedState={{}} />)- await screen.findAllByText('/storage/v1/object/public/videos/marketing/tabTableEditor.mp4')- await screen.findAllByText('2')-})diff --git a/apps/studio/tests/pages/api/mcp/index.test.ts b/apps/studio/tests/pages/api/mcp/index.test.tsindex 1bf7221d07a..656f937722c 100644--- a/apps/studio/tests/pages/api/mcp/index.test.ts+++ b/apps/studio/tests/pages/api/mcp/index.test.ts@@ -32,7 +32,7 @@ describe('/api/mcp', () => {})describe('Method handling', async () => {- it('should handle POST requests', async () => {+ it('should handle POST requests without a features parameter', async () => {const { req, res } = createMocks({method: 'POST',query: {},@@ -42,6 +42,7 @@ describe('/api/mcp', () => {await handler(req, res)expect(res._getStatusCode()).not.toBe(405)+ expect(res._getStatusCode()).not.toBe(400)})it('should return 405 for non-POST methods', async () => {@@ -84,17 +85,5 @@ describe('/api/mcp', () => {expect(res._getStatusCode()).toBe(400)expect(JSON.parse(res._getData())).toHaveProperty('error')})-- it('should work without features parameter', async () => {- const { req, res } = createMocks({- method: 'POST',- query: {},- body: {},- })-- await handler(req, res)-- expect(res._getStatusCode()).not.toBe(400)- })})})diff --git a/apps/studio/tests/pages/api/v1/projects/[ref]/api-keys/[id].test.ts b/apps/studio/tests/pages/api/v1/projects/[ref]/api-keys/[id].test.tsindex b554dd8829e..e3c43683429 100644--- a/apps/studio/tests/pages/api/v1/projects/[ref]/api-keys/[id].test.ts+++ b/apps/studio/tests/pages/api/v1/projects/[ref]/api-keys/[id].test.ts@@ -70,30 +70,15 @@ describe('/api/v1/projects/[ref]/api-keys/[id]', () => {})})- it('masks the secret key when reveal is false', async () => {+ it.each([+ { case: 'reveal is false', query: { reveal: 'false' } },+ { case: 'no reveal query param is set', query: {} },+ ])('masks the secret key when $case', async ({ query }) => {vi.stubEnv('SUPABASE_SECRET_KEY', 'sb_secret_abcdefghijklmnop')const { req, res } = createMocks({method: 'GET',- query: { ref: 'default', id: 'secret', reveal: 'false' },- })- await handler(req, res)-- expect(res._getStatusCode()).toBe(200)- expect(JSON.parse(res._getData())).toMatchObject({- id: 'secret',- type: 'secret',- api_key: 'sb_secret_abcde',- prefix: 'sb_secret_abcde',- })- })-- it('masks the secret key by default when no reveal query param is set', async () => {- vi.stubEnv('SUPABASE_SECRET_KEY', 'sb_secret_abcdefghijklmnop')-- const { req, res } = createMocks({- method: 'GET',- query: { ref: 'default', id: 'secret' },+ query: { ref: 'default', id: 'secret', ...query },})await handler(req, res)diff --git a/apps/studio/tests/pages/aws-marketplace-onboarding.test.tsx b/apps/studio/tests/pages/aws-marketplace-onboarding.test.tsxindex 4bb65bb3209..00592b059a0 100644--- a/apps/studio/tests/pages/aws-marketplace-onboarding.test.tsx+++ b/apps/studio/tests/pages/aws-marketplace-onboarding.test.tsx@@ -220,8 +220,15 @@ describe('AwsMarketplaceOnboardingScreen', () => {renderScreen()- await user.click(await screen.findByRole('button', { name: 'Create organization' }))- await user.type(screen.getByPlaceholderText('Organization name'), 'Mock Marketplace Org')+ // With no existing organizations, only the primary create action is offered+ const createButton = await screen.findByRole('button', { name: 'Create organization' })+ expect(+ screen.queryByRole('button', { name: /Create new organization/ })+ ).not.toBeInTheDocument()++ await user.click(createButton)+ await user.click(screen.getByPlaceholderText('Organization name'))+ await user.paste('Mock Marketplace Org')fireEvent.submit(document.getElementById(CREATE_AWS_MANAGED_ORG_FORM_ID)!)await waitFor(() => {@@ -316,18 +323,4 @@ describe('AwsMarketplaceOnboardingScreen', () => {expect(zeta.compareDocumentPosition(alpha) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()expect(screen.getByRole('button', { name: 'Show 2 more' })).toBeInTheDocument()})-- test('renders a create organization action when there are no existing organizations', async () => {- mockAwsEndpoints({- organizations: [],- onboardingInfo: createOnboardingInfo({ organizations: [] }),- })-- renderScreen()-- expect(await screen.findByRole('button', { name: 'Create organization' })).toBeInTheDocument()- expect(- screen.queryByRole('button', { name: /Create new organization/ })- ).not.toBeInTheDocument()- })})diff --git a/apps/studio/tests/pages/cli-login.test.tsx b/apps/studio/tests/pages/cli-login.test.tsxindex a50b3e80dbb..684e6109cc3 100644--- a/apps/studio/tests/pages/cli-login.test.tsx+++ b/apps/studio/tests/pages/cli-login.test.tsx@@ -129,29 +129,42 @@ describe('CliLoginScreen', () => {expect(screen.queryByText(/Unknown error/)).not.toBeInTheDocument()})- test('POSTs createCliLoginSession exactly once even when parent re-renders', async () => {- createCliLoginSessionMock.mockResolvedValue({ nonce: 'ABCDEFGH12345678' })- const { rerender } = renderScreen()+ test('POSTs once and still navigates after the parent re-renders during an in-flight POST', async () => {+ // Resolve manually so we can inject a re-render while the POST is in flight.+ let resolveSession: (value: { nonce: string }) => void = () => {}+ createCliLoginSessionMock.mockImplementation(+ () =>+ new Promise<{ nonce: string }>((resolve) => {+ resolveSession = resolve+ })+ )+ const { rerender, navigate: initialNavigate } = renderScreen()await waitFor(() => {expect(createCliLoginSessionMock).toHaveBeenCalledTimes(1)})- // Re-render with a brand-new `navigate` prop (mirrors the production- // bug where the parent recreated the closure on every render).- for (let i = 0; i < 5; i++) {- rerender(- <CliLoginScreen- isLoggedIn- routerReady- sessionId="session-test"- publicKey="public-key-test"- tokenName="local-dev"- navigate={vi.fn()}- />- )- }+ // Parent re-renders mid-POST with a brand-new navigate ref. This was the+ // production hang: the cleanup would invalidate the success handler and+ // the ref guard would skip the retry, leaving the screen on the loader.+ const laterNavigate = vi.fn()+ rerender(+ <CliLoginScreen+ isLoggedIn+ routerReady+ sessionId="session-test"+ publicKey="public-key-test"+ tokenName="local-dev"+ navigate={laterNavigate}+ />+ )++ resolveSession({ nonce: 'ABCDEFGH12345678' })+ await waitFor(() => {+ expect(laterNavigate).toHaveBeenCalledWith('/cli/login?device_code=ABCDEFGH')+ })+ expect(initialNavigate).not.toHaveBeenCalled()expect(createCliLoginSessionMock).toHaveBeenCalledTimes(1)})})diff --git a/apps/studio/tests/pages/cli/login.test.tsx b/apps/studio/tests/pages/cli/login.test.tsxdeleted file mode 100644index 0f931d3bb18..00000000000--- a/apps/studio/tests/pages/cli/login.test.tsx+++ /dev/null@@ -1,78 +0,0 @@-import { waitFor } from '@testing-library/dom'-import { expect, test, vi } from 'vitest'--import * as cliLogin from '@/data/cli/login'-import { ProfileContextType } from '@/lib/profile'-import { CliLoginScreen } from '@/pages/cli/login'-import { customRender } from '@/tests/lib/custom-render'--const DEFAULT_PROFILE_CONTEXT: ProfileContextType = {- profile: {- id: 1,- auth0_id: 'auth0|test',- gotrue_id: 'gotrue-test',- username: 'testuser',- primary_email: '[email protected]',- first_name: null,- last_name: null,- mobile: null,- is_alpha_user: false,- is_sso_user: false,- disabled_features: [],- free_project_limit: null,- },- error: null,- isLoading: false,- isError: false,- isSuccess: true,-}--test('still navigates after parent re-renders during an in-flight POST', async () => {- // Resolve manually so we can inject a re-render while the POST is in flight.- let resolveSession: (value: { nonce: string }) => void = () => {}- const createCliLoginSessionMock = vi.spyOn(cliLogin, 'createCliLoginSession').mockImplementation(- () =>- new Promise<{ nonce: string }>((resolve) => {- resolveSession = resolve- })- )- const initialNavigate = vi.fn()- const { rerender } = customRender(- <CliLoginScreen- isLoggedIn- routerReady- sessionId="session-test"- publicKey="public-key-test"- tokenName="local-dev"- navigate={initialNavigate}- />,- { profileContext: DEFAULT_PROFILE_CONTEXT }- )-- await waitFor(() => {- expect(createCliLoginSessionMock).toHaveBeenCalledTimes(1)- })-- // Parent re-renders mid-POST with a brand-new navigate ref. This was the- // production hang: the cleanup would invalidate the success handler and- // the ref guard would skip the retry, leaving the screen on the loader.- const laterNavigate = vi.fn()- rerender(- <CliLoginScreen- isLoggedIn- routerReady- sessionId="session-test"- publicKey="public-key-test"- tokenName="local-dev"- navigate={laterNavigate}- />- )-- resolveSession({ nonce: 'ABCDEFGH12345678' })-- await waitFor(() => {- expect(laterNavigate).toHaveBeenCalledWith('/cli/login?device_code=ABCDEFGH')- })- expect(initialNavigate).not.toHaveBeenCalled()- expect(createCliLoginSessionMock).toHaveBeenCalledTimes(1)-})diff --git a/apps/studio/tests/pages/new/[slug].test.tsx b/apps/studio/tests/pages/new/[slug].test.tsxindex b70d0c03c83..ceeea9b7139 100644--- a/apps/studio/tests/pages/new/[slug].test.tsx+++ b/apps/studio/tests/pages/new/[slug].test.tsx@@ -36,7 +36,10 @@ type GitHubRepositoriesResponse = {mockAnimationsApi()-configure({ asyncUtilTimeout: 5000 })+// defaultHidden skips RTL's per-element accessibility (getComputedStyle) check, which makes+// each *ByRole query on this large form ~3x cheaper. Radix Selects also render hidden native+// <option>s, so option queries are scoped to the open listbox via findOption.+configure({ asyncUtilTimeout: 5000, defaultHidden: true })vi.setConfig({ testTimeout: 30000 })vi.mock('sonner', () => ({@@ -367,15 +370,20 @@ const submitAndReadRegionSelection = async (onRequest: ReturnType<typeof vi.fn>)return onRequest.mock.calls[0][0].region_selection}+const findOption = async (name: string | RegExp) =>+ within(await screen.findByRole('listbox')).findByRole('option', { name })+const selectRegion = async (optionName: string | RegExp) => {await user.click(getSelectTriggerByLabel('Region'))- await user.click(await screen.findByRole('option', { name: optionName }))+ await user.click(await findOption(optionName))}const fillProjectName = async (name: string) => {- const input = await screen.findByPlaceholderText('Project name')- await user.clear(input)- await user.type(input, name)+ // Typing character-by-character re-renders the whole wizard per keystroke; the input+ // behaviour isn't under test, so set the value in one change event.+ fireEvent.change(await screen.findByPlaceholderText('Project name'), {+ target: { value: name },+ })}const generateAndWaitForStrongPassword = async () => {@@ -400,6 +408,8 @@ describe('project creation wizard', () => {await fillProjectName('My New Project')await generateAndWaitForStrongPassword()+ // The recommended region is preselected, so no manual region choice is needed+ expect(getSelectTriggerByLabel('Region')).toHaveTextContent('Americas')fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))@@ -410,6 +420,7 @@ describe('project creation wizard', () => {expect(body.name).toBe('My New Project')expect(body.organization_slug).toBe(ORG_SLUG)expect(body.desired_instance_size).toBe('micro')+ expect(body.region_selection).toMatchObject({ name: 'Americas' })await waitFor(() => expect(routerMock.asPath).toBe('/project/new-project-ref'))})@@ -519,72 +530,6 @@ describe('project creation wizard', () => {expect(regionSelection).toMatchObject({ name: 'Americas' })})- test('submits the recommended region without manual selection', async () => {- mockWizardEndpoints()- const onRequest = vi.fn()- mockCreateProject(onRequest)-- await renderWizard()-- await fillProjectName('Recommended Region Project')- await generateAndWaitForStrongPassword()- expect(getSelectTriggerByLabel('Region')).toHaveTextContent('Americas')-- const regionSelection = await submitAndReadRegionSelection(onRequest)- expect(regionSelection).toMatchObject({ name: 'Americas' })- })-- test('surfaces the recommended smart region with a "Recommended" badge', async () => {- mockWizardEndpoints()-- await renderWizard()-- await screen.findByPlaceholderText('Project name')- await user.click(getSelectTriggerByLabel('Region'))-- const recommendedOption = await screen.findByRole('option', { name: /Americas/ })- expect(within(recommendedOption).getByText('Recommended')).toBeInTheDocument()- })-- test('submits the user-selected region', async () => {- mockWizardEndpoints()- const onRequest = vi.fn()- mockCreateProject(onRequest)-- await renderWizard()-- await fillProjectName('Region Project')- await generateAndWaitForStrongPassword()- await selectRegion(/Americas/)-- fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))-- await waitFor(() => expect(onRequest).toHaveBeenCalled())- expect(onRequest.mock.calls[0][0].region_selection).toMatchObject({ name: 'Americas' })- })-- test('defaults to the Auto option when it is available', async () => {- mockWizardEndpoints({ availableRegions: AVAILABLE_REGIONS_WITH_AUTO })-- await renderWizard()-- await waitFor(() => expect(getSelectTriggerByLabel('Region')).toHaveTextContent('Auto'))- })-- test('hides the smart and specific region badges while Auto is recommended', async () => {- mockWizardEndpoints({ availableRegions: AVAILABLE_REGIONS_WITH_AUTO })-- await renderWizard()-- await screen.findByPlaceholderText('Project name')- await user.click(getSelectTriggerByLabel('Region'))-- const autoOption = await screen.findByRole('option', { name: /Auto/ })- expect(within(autoOption).getByText('Recommended')).toBeInTheDocument()- const americasOption = screen.getByRole('option', { name: /Americas/ })- expect(within(americasOption).queryByText('Recommended')).not.toBeInTheDocument()- })-test('defaults to the first general region when there is no recommendation', async () => {mockWizardEndpoints({availableRegions: { ...DEFAULT_AVAILABLE_REGIONS, recommendations: {} },@@ -595,7 +540,7 @@ describe('project creation wizard', () => {await waitFor(() => expect(getSelectTriggerByLabel('Region')).toHaveTextContent('Americas'))})- test('keeps the Auto option selected and submits it as an auto region selection', async () => {+ test('defaults to the recommended Auto option and submits it as an auto region selection', async () => {mockWizardEndpoints({ availableRegions: AVAILABLE_REGIONS_WITH_AUTO })const onRequest = vi.fn()mockCreateProject(onRequest)@@ -604,10 +549,18 @@ describe('project creation wizard', () => {await fillProjectName('Auto Region Project')await generateAndWaitForStrongPassword()- await selectRegion(/Auto/)-await waitFor(() => expect(getSelectTriggerByLabel('Region')).toHaveTextContent('Auto'))+ // Only Auto carries the "Recommended" badge while it is recommended+ await user.click(getSelectTriggerByLabel('Region'))+ const autoOption = await findOption(/Auto/)+ expect(within(autoOption).getByText('Recommended')).toBeInTheDocument()+ const americasOption = within(screen.getByRole('listbox')).getByRole('option', {+ name: /Americas/,+ })+ expect(within(americasOption).queryByText('Recommended')).not.toBeInTheDocument()+ await user.click(autoOption)+const regionSelection = await submitAndReadRegionSelection(onRequest)expect(regionSelection).toMatchObject({ code: 'auto', type: 'auto' })})@@ -644,7 +597,7 @@ describe('project creation wizard', () => {expect(screen.getByText('General regions')).toBeInTheDocument()expect(getSelectTriggerByLabel('Region')).toHaveTextContent('Americas')- await user.click(await screen.findByRole('option', { name: /East US/ }))+ await user.click(await findOption(/East US/))expect(screen.queryByRole('button', { name: 'Need a specific region?' })@@ -660,7 +613,9 @@ describe('project creation wizard', () => {await screen.findByPlaceholderText('Project name')await user.click(getSelectTriggerByLabel('Region'))- expect(await screen.findByText('General regions')).toBeInTheDocument()+ const recommendedOption = await findOption(/Americas/)+ expect(within(recommendedOption).getByText('Recommended')).toBeInTheDocument()+ expect(screen.getByText('General regions')).toBeInTheDocument()expect(screen.getByText('Specific regions')).toBeInTheDocument()expect(screen.queryByRole('button', { name: 'Need a specific region?' })@@ -706,7 +661,7 @@ describe('project creation wizard', () => {response: () => HttpResponse.error(),})await user.click(getSelectTriggerByLabel('Compute size'))- await user.click(await screen.findByRole('option', { name: /2 GB RAM/ }))+ await user.click(await findOption(/2 GB RAM/))await screen.findByText('Error loading available regions')const submitButton = screen.getByRole('button', { name: 'Create new project' })@@ -755,7 +710,9 @@ describe('project creation wizard', () => {expect(await screen.findByText('General regions')).toBeInTheDocument()expect(screen.queryByText('Specific regions')).not.toBeInTheDocument()- expect(screen.queryByRole('option', { name: /North Virginia/ })).not.toBeInTheDocument()+ expect(+ within(screen.getByRole('listbox')).queryByRole('option', { name: /North Virginia/ })+ ).not.toBeInTheDocument()const upgradeLink = screen.getByRole('link', { name: 'Upgrade to Pro' })expect(upgradeLink).toHaveAttribute(@@ -767,26 +724,7 @@ describe('project creation wizard', () => {'href',expect.stringMatching(/\/guides\/platform\/regions$/))- })-- test('the upgrade footer replaces the specific-regions link for a free-plan org in the test arm', async () => {- mockWizardEndpoints({- organizations: [mockOrg({ plan: { id: 'free', name: 'Free' } })],- })-- await renderWizard({- flags: {- freeTierGeneralRegionEnrollment: true,- freeTierGeneralRegionSelection: true,- },- })-- await screen.findByPlaceholderText('Project name')- await user.click(getSelectTriggerByLabel('Region'))-- expect(await screen.findByText('General regions')).toBeInTheDocument()- expect(screen.queryByText('Specific regions')).not.toBeInTheDocument()- expect(screen.getByRole('link', { name: 'Upgrade to Pro' })).toBeInTheDocument()+ // The upgrade footer replaces the "Need a specific region?" linkexpect(screen.queryByText('Need a specific region?')).not.toBeInTheDocument()})@@ -849,11 +787,13 @@ describe('project creation wizard', () => {await generateAndWaitForStrongPassword()await user.click(getSelectTriggerByLabel('Region'))- const saoPaulo = await screen.findByRole('option', { name: /São Paulo/ })+ const saoPaulo = await findOption(/São Paulo/)expect(saoPaulo).not.toHaveAttribute('aria-disabled', 'true')expect(within(saoPaulo).getByText('Unavailable')).toBeInTheDocument()expect(- within(screen.getByRole('option', { name: /North Virginia/ })).queryByText('Unavailable')+ within(+ within(screen.getByRole('listbox')).getByRole('option', { name: /North Virginia/ })+ ).queryByText('Unavailable')).not.toBeInTheDocument()await user.click(saoPaulo)@@ -871,37 +811,42 @@ describe('project creation wizard', () => {expect(screen.queryByText(copy.title)).not.toBeInTheDocument()}- test('keeps a capacity-restricted region selectable, explains it, and blocks submission', async () => {- mockWizardEndpoints({ availableRegions: availableRegionsWithSaoPaulo('capacity') })- const onRequest = vi.fn()- mockCreateProject(onRequest)-- await renderWizard()-- await expectSelectableRestrictedRegion(onRequest, CAPACITY_COPY)- })-- test('labels an "other" platform status with generic copy instead of greying it out silently', async () => {- mockWizardEndpoints({ availableRegions: availableRegionsWithSaoPaulo('other') })- const onRequest = vi.fn()- mockCreateProject(onRequest)-- await renderWizard()-- await expectSelectableRestrictedRegion(onRequest, GENERIC_COPY)- })-- test('applies a flag-only restriction the same way when the platform reports no status', async () => {- mockWizardEndpoints({ availableRegions: availableRegionsWithSaoPaulo() })- const onRequest = vi.fn()- mockCreateProject(onRequest)-- await renderWizard({+ test.each<{+ scenario: string+ status: 'capacity' | 'other' | undefined+ flags: Record<string, boolean | string>+ copy: typeof GENERIC_COPY+ }>([+ {+ scenario: 'a capacity platform status',+ status: 'capacity' as const,+ flags: {},+ copy: CAPACITY_COPY,+ },+ {+ scenario: 'an "other" platform status (generic copy, not silently greyed out)',+ status: 'other' as const,+ flags: {},+ copy: GENERIC_COPY,+ },+ {+ scenario: 'a flag-only restriction with no platform status',+ status: undefined,flags: { projectCreationRestrictedRegions: '{"sa-east-1":"unavailable"}' },- })+ copy: GENERIC_COPY,+ },+ ])(+ 'keeps the region selectable, explains it, and blocks submission for $scenario',+ async ({ status, flags, copy }) => {+ mockWizardEndpoints({ availableRegions: availableRegionsWithSaoPaulo(status) })+ const onRequest = vi.fn()+ mockCreateProject(onRequest)- await expectSelectableRestrictedRegion(onRequest, GENERIC_COPY)- })+ await renderWizard({ flags })++ await expectSelectableRestrictedRegion(onRequest, copy)+ }+ )})})@@ -1037,7 +982,7 @@ describe('project creation wizard', () => {)await user.click(screen.getByLabelText('Postgres version'))- await user.click(await screen.findByRole('option', { name: /17\.9\.9\.999/ }))+ await user.click(await findOption(/17\.9\.9\.999/))expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')const requestsBeforeRegionChange = onAvailableVersionsRequest.mock.calls.length@@ -1067,7 +1012,7 @@ describe('project creation wizard', () => {expect(screen.getByLabelText('Postgres version')).toHaveTextContent('15.6.1.139'))await user.click(screen.getByLabelText('Postgres version'))- await user.click(await screen.findByRole('option', { name: /17\.9\.9\.999/ }))+ await user.click(await findOption(/17\.9\.9\.999/))expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')fireEvent.click(panelToggle)@@ -1120,7 +1065,7 @@ describe('project creation wizard', () => {})describe('high availability', () => {- test('shows the high availability toggle when the entitlement is enabled', async () => {+ test('shows the high availability toggle when the entitlement is enabled, and hides gated sections by default', async () => {mockWizardEndpoints()await renderWizard()@@ -1136,6 +1081,9 @@ describe('project creation wizard', () => {expect(screen.queryByRole('button', { name: 'Internal-only Configuration' })).not.toBeInTheDocument()+ // No github_connections entitlement by default+ expect(screen.queryByText('GitHub (optional)')).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Connect GitHub' })).not.toBeInTheDocument()})test('hides the high availability toggle when the org lacks the entitlement', async () => {@@ -1321,6 +1269,7 @@ describe('project creation wizard', () => {await waitFor(() => expect(onRequest).toHaveBeenCalled())const body = onRequest.mock.calls[0][0]expect(body.high_availability).toBe(false)+ expect(body.cloud_provider).toBe('AWS')expect(body.postgres_engine).toBeUndefined()expect(body.release_channel).toBeUndefined()expect(body.custom_supabase_internal_requests).toBeUndefined()@@ -1351,7 +1300,7 @@ describe('project creation wizard', () => {expect(screen.getByLabelText('Postgres version')).toHaveTextContent('15.6.1.139'))await user.click(screen.getByLabelText('Postgres version'))- await user.click(await screen.findByRole('option', { name: /17\.9\.9\.999/ }))+ await user.click(await findOption(/17\.9\.9\.999/))expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')const highAvailabilitySwitch = await screen.findByRole('switch', {@@ -1364,29 +1313,6 @@ describe('project creation wizard', () => {expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999'))})-- test('restores the standard Postgres configuration when high availability is disabled', async () => {- mockWizardEndpoints()- const onRequest = vi.fn()- mockCreateProject(onRequest)-- await renderWizard()-- await fillProjectName('Standard Project')- await generateAndWaitForStrongPassword()- const highAvailabilitySwitch = await screen.findByRole('switch')- await user.click(highAvailabilitySwitch)- await user.click(highAvailabilitySwitch)-- fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))-- await waitFor(() => expect(onRequest).toHaveBeenCalled())- const body = onRequest.mock.calls[0][0]- expect(body.high_availability).toBe(false)- expect(body.cloud_provider).toBe('AWS')- expect(body.postgres_engine).toBeUndefined()- expect(body.custom_supabase_internal_requests).toBeUndefined()- })})describe('security options', () => {@@ -1458,8 +1384,9 @@ describe('project creation wizard', () => {await renderWizard()await fillProjectName('Weak Password Project')- const passwordInput = screen.getByPlaceholderText('Type in a strong password')- await user.type(passwordInput, 'password')+ fireEvent.change(screen.getByPlaceholderText('Type in a strong password'), {+ target: { value: 'password' },+ })await waitFor(() =>expect(screen.getByRole('progressbar')).not.toHaveAttribute('aria-valuenow', '100')@@ -1488,16 +1415,6 @@ describe('project creation wizard', () => {})describe('github integration', () => {- test('hides the github field without entitlement access', async () => {- mockWizardEndpoints()-- await renderWizard()-- await screen.findByPlaceholderText('Project name')- expect(screen.queryByText('GitHub (optional)')).not.toBeInTheDocument()- expect(screen.queryByRole('button', { name: 'Connect GitHub' })).not.toBeInTheDocument()- })-test('selecting a connected repository fills in the project name and submission payload', async () => {mockWizardEndpoints({entitlements: [@@ -1539,19 +1456,6 @@ describe('project creation wizard', () => {})})- describe('feature flags', () => {- test('hides internal-only configuration by default', async () => {- mockWizardEndpoints()-- await renderWizard()-- await screen.findByPlaceholderText('Project name')- expect(- screen.queryByRole('button', { name: 'Internal-only Configuration' })- ).not.toBeInTheDocument()- })- })-test('shows an error toast when project creation fails', async () => {mockWizardEndpoints()addAPIMock({diff --git a/apps/studio/tests/pages/project/[ref]/index.test.tsx b/apps/studio/tests/pages/project/[ref]/index.test.tsxdeleted file mode 100644index 26e5bfd32b0..00000000000--- a/apps/studio/tests/pages/project/[ref]/index.test.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { screen } from '@testing-library/react'-import { describe, expect, test, vi } from 'vitest'--import { customRender as render } from '@/tests/lib/custom-render'--vi.mock('@/components/interfaces/ProjectHome/Home', () => ({- ProjectHome: () => <div data-testid="project-home" />,-}))--vi.mock('@/components/layouts/DefaultLayout', () => ({- default: ({ children }: { children: React.ReactNode }) => <>{children}</>,-}))--vi.mock('@/components/layouts/ProjectLayout', () => ({- ProjectLayoutWithAuth: ({ children }: { children: React.ReactNode }) => <>{children}</>,-}))--vi.mock('@/lib/gotrue', () => ({- auth: { onAuthStateChange: vi.fn() },-}))--describe('project home page', () => {- test('renders ProjectHome', async () => {- const { default: HomePage } = await import('@/pages/project/[ref]/index')- render(<HomePage dehydratedState={undefined} />)- expect(screen.getByTestId('project-home')).toBeInTheDocument()- })-})diff --git a/apps/studio/tests/pages/project/[ref]/settings/api-keys/index.test.tsx b/apps/studio/tests/pages/project/[ref]/settings/api-keys/index.test.tsxindex de2a2a4ccb0..8adf93d22ce 100644--- a/apps/studio/tests/pages/project/[ref]/settings/api-keys/index.test.tsx+++ b/apps/studio/tests/pages/project/[ref]/settings/api-keys/index.test.tsx@@ -102,39 +102,35 @@ describe('/project/[ref]/settings/api-keys', () => {expect(screen.queryByText('ApiKeysFeedbackBanner')).not.toBeInTheDocument()})- it('renders the CLI admonition above the keys on self-hosted (CLI mode)', () => {- mockIsPlatform.value = false- mockUseDeploymentMode.mockReturnValue({- isPlatform: false,+ it.each([+ {+ mode: 'CLI',isCli: true,isSelfHosted: false,- })-- render(<ApiKeysPage dehydratedState={{}} />)-- expect(screen.getByText(/Local development with the Supabase CLI/i)).toBeInTheDocument()- expect(screen.queryByText(/Self-hosted Supabase/i)).not.toBeInTheDocument()- expect(screen.getByText('PublishableAPIKeys')).toBeInTheDocument()- expect(screen.getByText('SecretAPIKeys')).toBeInTheDocument()- expect(screen.queryByText('ApiKeysCreateCallout')).not.toBeInTheDocument()- expect(screen.queryByText('ApiKeysFeedbackBanner')).not.toBeInTheDocument()- })-- it('renders the self-hosted admonition above the keys on self-hosted (Docker mode)', () => {- mockIsPlatform.value = false- mockUseDeploymentMode.mockReturnValue({- isPlatform: false,+ shown: /Local development with the Supabase CLI/i,+ hidden: /Self-hosted Supabase/i,+ },+ {+ mode: 'Docker',isCli: false,isSelfHosted: true,- })-- render(<ApiKeysPage dehydratedState={{}} />)-- expect(screen.getByText(/Self-hosted Supabase/i)).toBeInTheDocument()- expect(screen.queryByText(/Local development with the Supabase CLI/i)).not.toBeInTheDocument()- expect(screen.getByText('PublishableAPIKeys')).toBeInTheDocument()- expect(screen.getByText('SecretAPIKeys')).toBeInTheDocument()- expect(screen.queryByText('ApiKeysCreateCallout')).not.toBeInTheDocument()- expect(screen.queryByText('ApiKeysFeedbackBanner')).not.toBeInTheDocument()- })+ shown: /Self-hosted Supabase/i,+ hidden: /Local development with the Supabase CLI/i,+ },+ ])(+ 'renders the matching admonition above the keys on self-hosted ($mode mode)',+ ({ isCli, isSelfHosted, shown, hidden }) => {+ mockIsPlatform.value = false+ mockUseDeploymentMode.mockReturnValue({ isPlatform: false, isCli, isSelfHosted })++ render(<ApiKeysPage dehydratedState={{}} />)++ expect(screen.getByText(shown)).toBeInTheDocument()+ expect(screen.queryByText(hidden)).not.toBeInTheDocument()+ expect(screen.getByText('PublishableAPIKeys')).toBeInTheDocument()+ expect(screen.getByText('SecretAPIKeys')).toBeInTheDocument()+ expect(screen.queryByText('ApiKeysCreateCallout')).not.toBeInTheDocument()+ expect(screen.queryByText('ApiKeysFeedbackBanner')).not.toBeInTheDocument()+ }+ )})diff --git a/apps/studio/tests/pages/project/[ref]/settings/infrastructure.test.tsx b/apps/studio/tests/pages/project/[ref]/settings/infrastructure.test.tsxindex 637c768d87d..22f29fb31b8 100644--- a/apps/studio/tests/pages/project/[ref]/settings/infrastructure.test.tsx+++ b/apps/studio/tests/pages/project/[ref]/settings/infrastructure.test.tsx@@ -320,7 +320,7 @@ describe('/project/[ref]/settings/infrastructure', () => {})test('loads the complete infrastructure page through MSW and resets an interaction', async () => {- const user = userEvent.setup()+ const user = userEvent.setup({ delay: null })renderInfrastructurePage()expect(screen.getByRole('heading', { name: 'Infrastructure', level: 1 })).toBeInTheDocument()@@ -343,6 +343,12 @@ describe('/project/[ref]/settings/infrastructure', () => {expect(screen.getByText('Dedicated · 2 vCPUs')).toBeInTheDocument() // Largeexpect(screen.queryByText(/-core/)).not.toBeInTheDocument()+ // Compute stays editable for non High Availability projects+ expect(+ screen.queryByText("Compute size can't be changed on High Availability projects")+ ).not.toBeInTheDocument()+ expect(screen.getByText('Contact Us')).toBeInTheDocument()+await user.click(screen.getByText('Small'))expect(screen.getByRole('button', { name: 'Review changes' })).toBeEnabled()@@ -353,7 +359,7 @@ describe('/project/[ref]/settings/infrastructure', () => {})test('focuses the recommended compute option after closing the add replica dialog', async () => {- const user = userEvent.setup()+ const user = userEvent.setup({ delay: null })renderInfrastructurePage()await user.click(await screen.findByRole('button', { name: 'Add read replica' }))@@ -365,7 +371,7 @@ describe('/project/[ref]/settings/infrastructure', () => {})test('reviews and confirms a compute resize through the add-on API', async () => {- const user = userEvent.setup()+ const user = userEvent.setup({ delay: null })let addonRequest: unknownaddAPIMock({@@ -398,7 +404,7 @@ describe('/project/[ref]/settings/infrastructure', () => {})test('renders compute as read-only for High Availability projects', async () => {- const user = userEvent.setup()+ const user = userEvent.setup({ delay: null })addAPIMock({method: 'get',@@ -455,22 +461,6 @@ describe('/project/[ref]/settings/infrastructure', () => {expect(screen.queryByRole('button', { name: 'Review changes' })).not.toBeInTheDocument()})- test('keeps compute editable for non High Availability projects', async () => {- const user = userEvent.setup()- renderInfrastructurePage()-- expect(- screen.queryByText("Compute size can't be changed on High Availability projects")- ).not.toBeInTheDocument()-- const smallCompute = await screen.findByRole('radio', { name: /Small/ })- expect(smallCompute).toBeEnabled()- expect(screen.getByText('Contact Us')).toBeInTheDocument()-- await user.click(smallCompute)- expect(screen.getByRole('button', { name: 'Review changes' })).toBeEnabled()- })-test('submits disk and autoscaling changes to both infrastructure APIs', async () => {const user = userEvent.setup({ delay: null })let diskRequest: unknowndiff --git a/apps/studio/tests/pages/project/[ref]/settings/jwt/index.test.tsx b/apps/studio/tests/pages/project/[ref]/settings/jwt/index.test.tsxindex e1abf4f5b33..faa4e5986eb 100644--- a/apps/studio/tests/pages/project/[ref]/settings/jwt/index.test.tsx+++ b/apps/studio/tests/pages/project/[ref]/settings/jwt/index.test.tsx@@ -70,27 +70,12 @@ describe('/project/[ref]/settings/jwt', () => {expect(screen.queryByText('LocalSetupGuide')).not.toBeInTheDocument()})- it('renders only the CLI LocalSetupGuide on self-hosted (CLI mode)', () => {+ it.each([+ { mode: 'CLI', isCli: true, isSelfHosted: false },+ { mode: 'Docker', isCli: false, isSelfHosted: true },+ ])('renders only the LocalSetupGuide on self-hosted ($mode mode)', ({ isCli, isSelfHosted }) => {mockIsPlatform.value = false- mockUseDeploymentMode.mockReturnValue({- isPlatform: false,- isCli: true,- isSelfHosted: false,- })-- render(<JWTSigningKeysPage dehydratedState={{}} />)-- expect(screen.queryByText('JWTSecretKeysTable')).not.toBeInTheDocument()- expect(screen.getAllByText('LocalSetupGuide')).toHaveLength(1)- })-- it('renders only the self-hosted LocalSetupGuide on self-hosted (Docker mode)', () => {- mockIsPlatform.value = false- mockUseDeploymentMode.mockReturnValue({- isPlatform: false,- isCli: false,- isSelfHosted: true,- })+ mockUseDeploymentMode.mockReturnValue({ isPlatform: false, isCli, isSelfHosted })render(<JWTSigningKeysPage dehydratedState={{}} />)diff --git a/apps/studio/tests/pages/project/[ref]/settings/jwt/legacy.test.tsx b/apps/studio/tests/pages/project/[ref]/settings/jwt/legacy.test.tsxindex ea67c0b36ae..480d83faf62 100644--- a/apps/studio/tests/pages/project/[ref]/settings/jwt/legacy.test.tsx+++ b/apps/studio/tests/pages/project/[ref]/settings/jwt/legacy.test.tsx@@ -5,21 +5,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import JWTKeysLegacyPage from '@/pages/project/[ref]/settings/jwt/legacy'import { customRender as render } from '@/tests/lib/custom-render'-const { mockIsPlatform, mockUseIsFeatureEnabled, mockUseJwtSecretUpdatingStatusQuery } = vi.hoisted(- () => ({- mockIsPlatform: { value: true },- mockUseIsFeatureEnabled: vi.fn(),- mockUseJwtSecretUpdatingStatusQuery: vi.fn(),- })-)+const { mockUseIsFeatureEnabled, mockUseJwtSecretUpdatingStatusQuery } = vi.hoisted(() => ({+ mockUseIsFeatureEnabled: vi.fn(),+ mockUseJwtSecretUpdatingStatusQuery: vi.fn(),+}))vi.mock('common', async () => {const actual = await vi.importActual<Record<string, unknown>>('common')return {...actual,- get IS_PLATFORM() {- return mockIsPlatform.value- },useParams: () => ({ ref: 'project-ref' }),}})@@ -53,22 +47,21 @@ vi.mock('@/components/interfaces/JwtSecrets/jwt-settings', () => ({describe('/project/[ref]/settings/jwt/legacy', () => {beforeEach(() => {- mockIsPlatform.value = truemockUseIsFeatureEnabled.mockReturnValue({ projectSettingsLegacyJwtKeys: true })mockUseJwtSecretUpdatingStatusQuery.mockReturnValue({ data: undefined })})- it('renders the JWT settings on platform', () => {+ it('renders the JWT settings when legacy JWT keys are enabled', () => {render(<JWTKeysLegacyPage dehydratedState={{}} />)expect(screen.getByText('JWTSettings')).toBeInTheDocument()})- it('renders the JWT settings on self-hosted', () => {- mockIsPlatform.value = false+ it('hides the JWT settings when legacy JWT keys are disabled', () => {+ mockUseIsFeatureEnabled.mockReturnValue({ projectSettingsLegacyJwtKeys: false })render(<JWTKeysLegacyPage dehydratedState={{}} />)- expect(screen.getByText('JWTSettings')).toBeInTheDocument()+ expect(screen.queryByText('JWTSettings')).not.toBeInTheDocument()})})diff --git a/apps/studio/tests/setup/dom.ts b/apps/studio/tests/setup/dom.tsnew file mode 100644index 00000000000..bb45398cb9b--- /dev/null+++ b/apps/studio/tests/setup/dom.ts@@ -0,0 +1,14 @@+import { afterEach } from 'vitest'++// Pure-logic `.test.ts` files run in the node environment, where these DOM polyfills and+// Testing Library hooks are neither needed nor valid. Files that opt into jsdom with a+// `// @vitest-environment jsdom` docblock still get the full DOM setup.+if (typeof window !== 'undefined') {+ await import('@testing-library/jest-dom/vitest')+ await import('./polyfills')++ const { cleanup } = await import('@testing-library/react')+ afterEach(() => {+ cleanup()+ })+}diff --git a/apps/studio/tests/setup/radix.js b/apps/studio/tests/setup/radix.jsindex 1e26527cd24..39b946329bb 100644--- a/apps/studio/tests/setup/radix.js+++ b/apps/studio/tests/setup/radix.js@@ -14,27 +14,30 @@* Needed to interact with dropdown components, with the `clickDropdown` helper.*/-class PointerEvent extends Event {- constructor(type, props) {- super(type, props)- if (props.button != null) {- this.button = props.button- }- if (props.ctrlKey != null) {- this.ctrlKey = props.ctrlKey+// Pure-logic tests run in the node environment, which has no `window` to patch.+if (typeof window !== 'undefined') {+ class PointerEvent extends Event {+ constructor(type, props) {+ super(type, props)+ if (props.button != null) {+ this.button = props.button+ }+ if (props.ctrlKey != null) {+ this.ctrlKey = props.ctrlKey+ }}}-}-window.PointerEvent = PointerEvent-window.HTMLElement.prototype.scrollIntoView = function () {}+ window.PointerEvent = PointerEvent+ window.HTMLElement.prototype.scrollIntoView = function () {}-// // https://github.com/radix-ui/primitives/issues/420#issuecomment-771615182-window.ResizeObserver = class ResizeObserver {- constructor(cb) {- this.cb = cb+ // // https://github.com/radix-ui/primitives/issues/420#issuecomment-771615182+ window.ResizeObserver = class ResizeObserver {+ constructor(cb) {+ this.cb = cb+ }+ observe() {}+ unobserve() {}+ disconnect() {}}- observe() {}- unobserve() {}- disconnect() {}}diff --git a/apps/studio/tests/unit/LogicalBackupCliInstructions.test.ts b/apps/studio/tests/unit/LogicalBackupCliInstructions.test.tsindex e2f0444f007..fbb6e149107 100644--- a/apps/studio/tests/unit/LogicalBackupCliInstructions.test.ts+++ b/apps/studio/tests/unit/LogicalBackupCliInstructions.test.ts@@ -19,17 +19,6 @@ describe('buildDirectPostgresConnectionUri', () => {)})- it('uses the password placeholder, never a real password', () => {- const uri = buildDirectPostgresConnectionUri({- db_user: 'postgres',- db_host: 'db.abcdef.supabase.co',- db_port: 5432,- db_name: 'postgres',- })- expect(uri).toContain(DB_PASSWORD_PLACEHOLDER)- expect(uri).not.toContain('secret')- })-it('includes a non-default port', () => {const uri = buildDirectPostgresConnectionUri({db_user: 'postgres',@@ -44,11 +33,6 @@ describe('buildDirectPostgresConnectionUri', () => {describe('buildLogicalBackupShellScript', () => {const testUri = `postgresql://postgres:${DB_PASSWORD_PLACEHOLDER}@db.abcdef.supabase.co:5432/postgres`- it('produces exactly three commands', () => {- const script = buildLogicalBackupShellScript(testUri)- expect(script.split('\n')).toHaveLength(3)- })-it('wraps the connection URI in single quotes to prevent shell expansion', () => {const script = buildLogicalBackupShellScript(testUri)for (const line of script.split('\n')) {@@ -56,8 +40,10 @@ describe('buildLogicalBackupShellScript', () => {}})- it('dumps roles, schema, and data in that order', () => {- const [roles, schema, data] = buildLogicalBackupShellScript(testUri).split('\n')+ it('dumps roles, schema, and data in that order as three commands', () => {+ const lines = buildLogicalBackupShellScript(testUri).split('\n')+ expect(lines).toHaveLength(3)+ const [roles, schema, data] = linesexpect(roles).toContain('--role-only')expect(roles).toContain('-f roles.sql')expect(schema).toContain('-f schema.sql')diff --git a/apps/studio/tests/unit/get-return-to-path.test.ts b/apps/studio/tests/unit/get-return-to-path.test.tsindex 38f4acb83f8..5bac1246fa4 100644--- a/apps/studio/tests/unit/get-return-to-path.test.ts+++ b/apps/studio/tests/unit/get-return-to-path.test.ts@@ -1,3 +1,4 @@+// @vitest-environment jsdomimport { describe, expect, it } from 'vitest'import { DEFAULT_FALLBACK_PATH, getReturnToPath } from '@/lib/gotrue'diff --git a/apps/studio/tests/unit/lints/mcp-advisors.test.ts b/apps/studio/tests/unit/lints/mcp-advisors.test.tsindex 486b05ee46d..59ff379a153 100644--- a/apps/studio/tests/unit/lints/mcp-advisors.test.ts+++ b/apps/studio/tests/unit/lints/mcp-advisors.test.ts@@ -55,33 +55,17 @@ describe('MCP advisor operations pass exposedSchemas to getLints', () => {})})- it('getSecurityAdvisors should pass exposedSchemas to getLints', async () => {- const ops = getDebuggingOperations({ headers })- await ops.getSecurityAdvisors('test-project')-- expect(mockGetLints).toHaveBeenCalledOnce()- const callArgs = mockGetLints.mock.calls[0][0]- expect(callArgs).toHaveProperty('exposedSchemas')- expect(callArgs.exposedSchemas).toBeTruthy()- })-- it('getPerformanceAdvisors should pass exposedSchemas to getLints', async () => {- const ops = getDebuggingOperations({ headers })- await ops.getPerformanceAdvisors('test-project')-- expect(mockGetLints).toHaveBeenCalledOnce()- const callArgs = mockGetLints.mock.calls[0][0]- expect(callArgs).toHaveProperty('exposedSchemas')- expect(callArgs.exposedSchemas).toBeTruthy()- })-- it('should use DEFAULT_EXPOSED_SCHEMAS constant', async () => {- const ops = getDebuggingOperations({ headers })- await ops.getSecurityAdvisors('test-project')-- const callArgs = mockGetLints.mock.calls[0][0]- expect(callArgs.exposedSchemas).toBe(DEFAULT_EXPOSED_SCHEMAS)- })+ it.each(['getSecurityAdvisors', 'getPerformanceAdvisors'] as const)(+ '%s passes DEFAULT_EXPOSED_SCHEMAS to getLints',+ async (operation) => {+ const ops = getDebuggingOperations({ headers })+ await ops[operation]('test-project')++ expect(mockGetLints).toHaveBeenCalledWith(+ expect.objectContaining({ exposedSchemas: DEFAULT_EXPOSED_SCHEMAS })+ )+ }+ )it('getSecurityAdvisors should filter to SECURITY category', async () => {const ops = getDebuggingOperations({ headers })diff --git a/apps/studio/tests/vitestSetup.ts b/apps/studio/tests/vitestSetup.tsindex 97fc63a2a30..346524c3fda 100644--- a/apps/studio/tests/vitestSetup.ts+++ b/apps/studio/tests/vitestSetup.ts@@ -1,7 +1,5 @@-import '@testing-library/jest-dom/vitest'import './lib/disabled-matchers'-import { cleanup } from '@testing-library/react'import dayjs from 'dayjs'import relativeTime from 'dayjs/plugin/relativeTime'import timezone from 'dayjs/plugin/timezone'@@ -63,7 +61,6 @@ beforeAll(() => {afterEach(() => {mswServer.resetHandlers()- cleanup()})afterAll(() => {diff --git a/apps/studio/vercel-content-types.test.ts b/apps/studio/vercel-content-types.test.tsdeleted file mode 100644index dc2045d26d0..00000000000--- a/apps/studio/vercel-content-types.test.ts+++ /dev/null@@ -1,94 +0,0 @@-import { createRequire } from 'node:module'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { z } from 'zod'--const require = createRequire(import.meta.url)-const sdkRequire = createRequire(require.resolve('@vercel/config/v1'))-const { getTransformedRoutes } = sdkRequire('@vercel/routing-utils')-const compiledConfigSchema = z.object({- error: z.unknown(),- routes: z- .array(z.object({ src: z.string().optional(), headers: z.record(z.string()).optional() }))- .nullable(),-})--afterEach(() => {- vi.unstubAllEnvs()- vi.resetModules()-})--describe.each(['', '/dashboard'])('TanStack content types with base path "%s"', (basePath) => {- let compiledRoutes: z.infer<typeof compiledConfigSchema>['routes']-- beforeEach(async () => {- vi.resetModules()- vi.stubEnv('STUDIO_FRAMEWORK', 'tanstack')- vi.stubEnv('NEXT_PUBLIC_BASE_PATH', basePath)- const { config } = await import('./vercel')- const compiled: unknown = getTransformedRoutes({ headers: config.headers })- const result = compiledConfigSchema.parse(compiled)- expect(result.error).toBeNull()- compiledRoutes = result.routes- })-- function headersForPath(pathname: string) {- const headers: Record<string, string> = {}- for (const route of compiledRoutes ?? []) {- if (route.src && new RegExp(route.src).test(pathname)) Object.assign(headers, route.headers)- }- return headers- }-- it.each(['edge-runtime.d.ts', 'lib.deno.d.ts'])(- 'serves %s as TypeScript at root and base path',- (file) => {- for (const prefix of new Set(['', basePath])) {- const headers = headersForPath(`${prefix}/deno/${file}`)- expect(headers['content-type']).toBe('text/typescript')- expect(headers['X-Content-Type-Options']).toBe('nosniff')- expect(headers['Cache-Control']).toBeUndefined()- }- }- )-- it.each([- '/deno/edge-runtime.d.ts.map',- '/deno/edge-runtime.d.tsx',- '/deno/edge-runtime.dXts',- '/deno/edge-runtime.d.ts/extra',- '/deno/edge-runtime.d.tsextra',- '/deno-other/edge-runtime.d.ts',- '/edge-runtime.d.ts',- '/img/example.ts',- ])('does not override content type for %s', (pathname) => {- for (const prefix of new Set(['', basePath])) {- expect(headersForPath(`${prefix}${pathname}`)['content-type']).toBeUndefined()- }- })-- it.each(['/api/example.ts', '/api/deno/example.ts', '/_serverFn/example.ts'])(- 'preserves dynamic content type and private caching for %s',- (pathname) => {- for (const prefix of new Set(['', basePath])) {- const headers = headersForPath(`${prefix}${pathname}`)- expect(headers['content-type']).toBeUndefined()- expect(headers['Cache-Control']).toBe('private, no-store')- }- }- )-- it('preserves JSON content type for the flags endpoint', () => {- expect(headersForPath('/.well-known/vercel/flags')['content-type']).toBe('application/json')- })-})--it.each([undefined, 'next'])(- 'leaves the Next Vercel configuration untouched (%s)',- async (framework) => {- vi.resetModules()- vi.stubEnv('STUDIO_FRAMEWORK', framework)- vi.stubEnv('NEXT_PUBLIC_BASE_PATH', '/dashboard')- const { config } = await import('./vercel')- expect(config).toEqual({})- }-)diff --git a/apps/studio/vercel.test.ts b/apps/studio/vercel.test.tsindex ee2f729c77f..6aee50220f8 100644--- a/apps/studio/vercel.test.ts+++ b/apps/studio/vercel.test.ts@@ -1,6 +1,6 @@import { createRequire } from 'node:module'import type { VercelConfig } from '@vercel/config/v1'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'// Compile with the routing utilities consumed by the installed Vercel config SDK.const require = createRequire(import.meta.url)@@ -71,3 +71,67 @@ describe.each(['', '/dashboard'])('Vercel headers with base path "%s"', (basePat})})++describe.each(['', '/dashboard'])('TanStack content types with base path "%s"', (basePath) => {+ let compiledRoutes: ReturnType<typeof getTransformedRoutes>['routes']++ beforeEach(async () => {+ vi.resetModules()+ vi.stubEnv('STUDIO_FRAMEWORK', 'tanstack')+ vi.stubEnv('NEXT_PUBLIC_BASE_PATH', basePath)+ const { config } = await import('./vercel')+ const result = getTransformedRoutes({ headers: config.headers })+ expect(result.error).toBeNull()+ compiledRoutes = result.routes+ })++ function headersForPath(pathname: string) {+ const headers: Record<string, string> = {}+ for (const route of compiledRoutes ?? []) {+ if (route.src && new RegExp(route.src).test(pathname)) Object.assign(headers, route.headers)+ }+ return headers+ }++ it.each(['edge-runtime.d.ts', 'lib.deno.d.ts'])(+ 'serves %s as TypeScript at root and base path',+ (file) => {+ for (const prefix of new Set(['', basePath])) {+ const headers = headersForPath(`${prefix}/deno/${file}`)+ expect(headers['content-type']).toBe('text/typescript')+ expect(headers['X-Content-Type-Options']).toBe('nosniff')+ expect(headers['Cache-Control']).toBeUndefined()+ }+ }+ )++ it.each([+ '/deno/edge-runtime.d.ts.map',+ '/deno/edge-runtime.d.tsx',+ '/deno/edge-runtime.dXts',+ '/deno/edge-runtime.d.ts/extra',+ '/deno/edge-runtime.d.tsextra',+ '/deno-other/edge-runtime.d.ts',+ '/edge-runtime.d.ts',+ '/img/example.ts',+ ])('does not override content type for %s', (pathname) => {+ for (const prefix of new Set(['', basePath])) {+ expect(headersForPath(`${prefix}${pathname}`)['content-type']).toBeUndefined()+ }+ })++ it.each(['/api/example.ts', '/api/deno/example.ts', '/_serverFn/example.ts'])(+ 'preserves dynamic content type and private caching for %s',+ (pathname) => {+ for (const prefix of new Set(['', basePath])) {+ const headers = headersForPath(`${prefix}${pathname}`)+ expect(headers['content-type']).toBeUndefined()+ expect(headers['Cache-Control']).toBe('private, no-store')+ }+ }+ )++ it('preserves JSON content type for the flags endpoint', () => {+ expect(headersForPath('/.well-known/vercel/flags')['content-type']).toBe('application/json')+ })+})diff --git a/apps/studio/vitest.config.ts b/apps/studio/vitest.config.tsindex ec553266787..352e942a0d3 100644--- a/apps/studio/vitest.config.ts+++ b/apps/studio/vitest.config.ts@@ -20,20 +20,22 @@ export default defineConfig({},test: {globals: true,- environment: 'jsdom', // TODO(kamil): This should be set per test via header in .tsx files only// Retry flaky tests in CI only; failures locally should surface immediately.retry: IS_CI ? 2 : 0,+ // The DOM setup files (`dom.ts`, `radix.js`) no-op when there's no jsdom environment.setupFiles: [- resolve(dirname, './tests/setup/polyfills.ts'),+ resolve(dirname, './tests/setup/dom.ts'),resolve(dirname, './tests/vitestSetup.ts'),resolve(dirname, './tests/setup/radix.js'),],// Don't look for tests in the nextjs output directory- exclude: [- ...configDefaults.exclude,- `.next/*`,- 'tests/features/logs/logs-query.test.tsx',- 'tests/features/reports/storage-report.test.tsx',+ exclude: [...configDefaults.exclude, `.next/*`],+ // jsdom costs ~1s of setup per file, so pure-logic `.test.ts` files run in node.+ // A `.test.ts` file that needs the DOM (e.g. `renderHook`) opts in with a+ // `// @vitest-environment jsdom` docblock at the top of the file.+ projects: [+ { extends: true, test: { name: 'node', environment: 'node', include: ['**/*.test.ts'] } },+ { extends: true, test: { name: 'jsdom', environment: 'jsdom', include: ['**/*.test.tsx'] } },],reporters: [['default']],coverage: {