Files
supabase/packages/dev-tools/DevToolbarContext.tsx
Jordi Enric af324d4189 feat(dev-tools): rename devTelemetry() to devToolbar() and add devToolbarDefaultOn flag (#47494)
## What

- Renames the `window.devTelemetry()` helper to `window.devToolbar()`.
- Adds a `devToolbarDefaultOn` ConfigCat flag. When enabled, the dev
toolbar shows automatically without the user having to run
`window.devToolbar()` in the console.
- The toolbar remains gated to `local` and `staging` environments only —
the flag has no effect in production.

## Notes

- The `localStorage` key (`dev-telemetry-toolbar-enabled`) is
intentionally left unchanged so anyone who already enabled the toolbar
keeps their setting.
- Updated unit tests: renamed all references and added coverage for the
`devToolbarDefaultOn` flag across local, staging, and prod.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* Added a new default-on option for the dev toolbar in local or staging
environments when the feature flag is enabled.
* The toolbar can now be opened from a new global trigger when
available.

* **Bug Fixes**
* Improved toolbar enablement behavior across environments, including
production, to avoid showing the trigger when it shouldn’t appear.
* Updated cleanup behavior so the toolbar trigger is removed correctly
after unmounting.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 12:24:35 +02:00

219 lines
5.5 KiB
TypeScript

'use client'
import { ensurePlatformSuffix, posthogClient, useFlag, type ClientTelemetryEvent } from 'common'
import {
createContext,
useCallback,
useContext,
useEffect,
useRef,
useState,
type ReactNode,
} from 'react'
import type {
DevTelemetryEvent,
DevTelemetryToolbarContextType,
ServerTelemetryEvent,
} from './types'
import { getCookie } from './utils'
// Duplicated for tree-shaking — bundler must see literal process.env reference.
// Keep in sync: index.ts, DevToolbar.tsx, DevToolbarTrigger.tsx, feature-flags.tsx
const env = process.env.NEXT_PUBLIC_ENVIRONMENT
const IS_TOOLBAR_ENABLED = env === 'local' || env === 'staging'
const IS_LOCAL_DEV = env === 'local'
const MAX_EVENTS = 200
const STORAGE_KEY = 'dev-telemetry-toolbar-enabled'
const SSE_INITIAL_RETRY_MS = 1000
const SSE_MAX_RETRY_MS = 30000
const SSE_BACKOFF_MULTIPLIER = 2
declare global {
interface Window {
devToolbar?: () => void
}
}
const DevToolbarContext = createContext<DevTelemetryToolbarContextType | null>(null)
interface DevToolbarProviderProps {
children: ReactNode
apiUrl: string
}
export function DevToolbarProvider({ children, apiUrl }: DevToolbarProviderProps) {
const [isEnabled, setIsEnabled] = useState(false)
const [isOpen, setIsOpen] = useState(false)
const [events, setEvents] = useState<DevTelemetryEvent[]>([])
const isDefaultOn = useFlag('devToolbarDefaultOn')
const sseRetryDelayRef = useRef(SSE_INITIAL_RETRY_MS)
const sseRetryTimeoutRef = useRef<NodeJS.Timeout | null>(null)
const dismissToolbar = useCallback(() => {
try {
localStorage.removeItem(STORAGE_KEY)
} catch {}
setIsEnabled(false)
setIsOpen(false)
}, [])
useEffect(() => {
if (!IS_TOOLBAR_ENABLED) return
let stored: string | null = null
try {
stored = localStorage.getItem(STORAGE_KEY)
} catch {}
if (stored === 'true' || isDefaultOn) {
setIsEnabled(true)
}
window.devToolbar = () => {
try {
localStorage.setItem(STORAGE_KEY, 'true')
} catch {}
setIsEnabled(true)
}
return () => {
delete window.devToolbar
}
}, [isDefaultOn])
const appendEvent = useCallback((event: DevTelemetryEvent) => {
setEvents((prev) => {
const key = `${event.source}-${event.id}`
if (prev.some((e) => `${e.source}-${e.id}` === key)) return prev
return [...prev.slice(-(MAX_EVENTS - 1)), event]
})
}, [])
useEffect(() => {
if (!isEnabled) return
const unsubscribe = posthogClient.subscribeToEvents((clientEvent: ClientTelemetryEvent) => {
appendEvent({
id: clientEvent.id,
timestamp: clientEvent.timestamp,
source: 'client',
eventType: clientEvent.eventType,
eventName: clientEvent.eventName,
distinctId: clientEvent.distinctId,
properties: clientEvent.properties,
})
})
return unsubscribe
}, [appendEvent, isEnabled])
useEffect(() => {
if (!IS_LOCAL_DEV || !isEnabled || typeof EventSource === 'undefined') return
let eventSource: EventSource | null = null
let isMounted = true
const connect = () => {
if (!isMounted) return
const sessionId = getCookie('session_id')
const streamUrl = `${ensurePlatformSuffix(apiUrl)}/telemetry/stream${
sessionId ? `?session_id=${encodeURIComponent(sessionId)}` : ''
}`
eventSource = new EventSource(streamUrl, { withCredentials: true })
eventSource.onopen = () => {
sseRetryDelayRef.current = SSE_INITIAL_RETRY_MS
}
eventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data) as ServerTelemetryEvent
appendEvent({
id: data.id,
timestamp: data.timestamp,
source: 'server',
eventType: data.eventType,
eventName: data.eventName,
distinctId: data.distinctId,
properties: data.properties,
})
} catch (e) {
console.error('[DevToolbar] Failed to parse SSE event:', e)
}
}
eventSource.onerror = () => {
if (!isMounted) return
eventSource?.close()
eventSource = null
const delay = sseRetryDelayRef.current
console.warn(`[DevToolbar] SSE connection error, reconnecting in ${delay}ms...`)
if (sseRetryTimeoutRef.current) {
clearTimeout(sseRetryTimeoutRef.current)
sseRetryTimeoutRef.current = null
}
sseRetryTimeoutRef.current = setTimeout(() => {
if (isMounted) {
connect()
}
}, delay)
sseRetryDelayRef.current = Math.min(delay * SSE_BACKOFF_MULTIPLIER, SSE_MAX_RETRY_MS)
}
}
connect()
return () => {
isMounted = false
eventSource?.close()
if (sseRetryTimeoutRef.current) {
clearTimeout(sseRetryTimeoutRef.current)
sseRetryTimeoutRef.current = null
}
}
}, [apiUrl, appendEvent, isEnabled])
if (!IS_TOOLBAR_ENABLED) {
return <>{children}</>
}
return (
<DevToolbarContext.Provider
value={{
isEnabled,
isOpen,
setIsOpen,
events,
setEvents,
dismissToolbar,
}}
>
{children}
</DevToolbarContext.Provider>
)
}
export function useDevToolbar() {
const context = useContext(DevToolbarContext)
if (!context) {
return {
isEnabled: false,
isOpen: false,
setIsOpen: () => {},
events: [],
setEvents: () => {},
dismissToolbar: () => {},
}
}
return context
}