Files
supabase/packages/dev-tools/DevToolbarContext.tsx
Danny White fb4c3ec6d4 feat(studio): add dev toolbar launcher to account settings menu (#49285)
## What kind of change does this PR introduce?

Feature

## What is the current behavior?

The dev toolbar is only discoverable via `window.devToolbar()` in the
browser console, or by having your email on the `devToolbarDefaultOn`
ConfigCat flag. Once enabled, Studio shows a floating trigger button.

## What is the new behavior?

In local and staging Studio, the account/settings dropdown (avatar menu)
includes a **Local tools** section above **Theme** with a **Dev
toolbar** checkbox toggle.

- **On**: shows the floating orb (persists via localStorage, same as
`window.devToolbar()`)
- **Off**: hides the orb and dismisses the toolbar

Open the panel itself via the orb once it is visible. Production builds
are unchanged (`isAvailable` is false and the menu item is hidden).

| After |
| --- |
| <img width="226" height="204" alt="CleanShot 2026-08-20 at 12 46
38@2x"
src="https://github.com/user-attachments/assets/c846b119-626d-48f5-9a02-aef4d006326c"
/> |
| <img width="558" height="1024" alt="CleanShot 2026-08-20 at 12 47
04@2x"
src="https://github.com/user-attachments/assets/4b3dd22b-537b-4874-821d-c202033c4ad7"
/> |

## Manual testing

Run `pnpm dev:studio` and open http://localhost:8082.

1. **Find the entry point:** top-right avatar/settings menu → **Local
tools** → **Dev toolbar** (above **Theme**). Should not appear in
production builds.
2. **Turn it on:** check **Dev toolbar**. A green floating orb should
appear (default bottom-right).
3. **Open the panel:** click the orb. The **Dev Toolbar** sheet should
open with Events and Flags tabs.
4. **Event count:** navigate around Studio (e.g. open a project, switch
pages). The orb badge should increment and stay readable in light and
dark mode.
5. **Turn it off:** reopen the avatar menu and uncheck **Dev toolbar**.
The orb and panel should disappear.
6. **Close vs hide:** with the toolbar on, open the sheet and use
**Close** (X). The orb should remain; only the sheet closes.

Optional: confirm `window.devToolbar()` in the browser console still
enables the orb.

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

* **New Features**
* Added a Local tools option to enable the development toolbar when
available.
* Toolbar activation and dismissal preferences now persist between
sessions.
* Added clearer event-count badges with responsive sizing for larger
counts.

* **Improvements**
  * Simplified toolbar controls by removing the separate hide option.
* Improved toolbar availability handling across local and production
environments.

* **Tests**
* Expanded coverage for activation, persistence, visibility, and
event-count badges.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Danny White <dnywh@users.noreply.github.com>
Co-authored-by: Sean Oliver <882952+seanoliver@users.noreply.github.com>
2026-08-21 10:53:50 +10:00

227 lines
5.8 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 enableToolbar = useCallback(() => {
try {
localStorage.setItem(STORAGE_KEY, 'true')
} catch {}
setIsEnabled(true)
}, [])
// Persist 'false' rather than clearing the key, so an explicit opt-out survives
// a reload and takes precedence over the devToolbarDefaultOn flag.
const dismissToolbar = useCallback(() => {
try {
localStorage.setItem(STORAGE_KEY, 'false')
} 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' || (stored !== 'false' && isDefaultOn)) {
setIsEnabled(true)
}
window.devToolbar = enableToolbar
return () => {
delete window.devToolbar
}
}, [enableToolbar, 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={{
isAvailable: IS_TOOLBAR_ENABLED,
isEnabled,
isOpen,
setIsOpen,
enableToolbar,
events,
setEvents,
dismissToolbar,
}}
>
{children}
</DevToolbarContext.Provider>
)
}
export function useDevToolbar() {
const context = useContext(DevToolbarContext)
if (!context) {
return {
isAvailable: false,
isEnabled: false,
isOpen: false,
setIsOpen: () => {},
enableToolbar: () => {},
events: [],
setEvents: () => {},
dismissToolbar: () => {},
}
}
return context
}