Files
kemal.earth b7d8b2d311 feat(studio): traces tab in unified logs (#54393)
## Problem

Unified Logs can show the logs correlated with a request, but not the
trace behind it. Where time actually went across services isn't visible
anywhere in Studio.

Part 3 of 3, and the one that ships the feature. Builds on the `Trace`
primitives from part 1 and the spans query from part 2.

## Solution

Adds a **Trace** tab to the log detail panel, composed entirely from the
shared `Trace` primitives — header, summary strip, waterfall, inspector
— and ships it as a feature preview.

**Resolving the trace id.** The selected log's own trace id wins. A
related log's id is used only as a fallback, and only when there's
exactly one candidate — picking between several would be a guess. The
ids come from the correlated logs the Timeline tab already fetches, so
the two tabs share a cache entry instead of each making a request.

**Mapping spans.** `RequestTrace.utils.ts` turns the endpoint's spans
into `Trace`'s `Span`/`TraceData` shape. Three things worth noting:

- Span names come from OTel attributes where the raw name isn't useful
on its own — a span named `GET` becomes `GET /rest/v1/orders` from
`http.route`, falling back to the path from `url.full` for outbound
fetches that have no server-matched route.
- `Date.parse` only resolves whole milliseconds, so two spans less than
a millisecond apart would round to the same instant and render stacked.
The fractional part of the ISO string is added back.
- Spans with a missing or invalid start time are counted and reported
rather than dropped silently.

**States.** The tab is always present when the Timeline is, so a request
with no trace shows an empty state rather than a tab that appears and
disappears as the trace resolves. Separate states cover: no trace id, a
trace with no spans, spans that exist but can't be placed, and a failed
fetch. `meta.partial` surfaces as a badge, since a trace can be
incomplete while spans are still being collected.

**Feature preview.** Listed under Observability as "Request traces",
following the same pattern as the Explorer and Storage versioning
previews. Two gates gives the kill switch and the opt-in independently:

- `enableTracesWaterfall` (ConfigCat) controls whether the preview is
listed at all
- The user's opt-in controls the tab, stored in local storage and
preserved across sign-out

It's not default opt-in, so nobody gets the tab without choosing it —
the endpoint is still alpha.

Also removes the temporary `knip.jsonc` entry added in part 2, now that
the query has an importer.

## Review instructions

1. Open the feature preview modal and confirm **Request traces** is
listed under Observability, with a panel describing the feature. Enable
it.
2. Open **Logs** and select a request log that has a trace id.
3. Confirm the **Trace** tab appears beside Timeline, with the header,
the summary strip (trace start, duration, services, depth, span count)
and the waterfall.
4. Select a span and confirm the inspector opens with its attributes and
events.
5. Select a request with no trace id and confirm the tab is still there,
showing an empty state.
6. Turn the preview off and confirm the tab disappears while Timeline is
unaffected.
7. `pnpm --filter studio test
components/interfaces/UnifiedLogs/components/RequestTrace.utils.test.ts
components/interfaces/UnifiedLogs/components/RequestTimeline.platform.test.tsx`

Note the traces endpoint is in alpha: a request only has a trace when
its logs carry a trace ID, so landing on the empty state in step 2 isn't
necessarily this PR misbehaving. The component tests cover every state
against mocked responses.
2026-12-04 11:24:48 +00:00

335 lines
14 KiB
TypeScript

import { useLocation, useNavigate } from '@tanstack/react-router'
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import { ExternalLinkIcon, EyeIcon, EyeOffIcon, FlaskConicalIcon } from 'lucide-react'
import { ReactNode } from 'react'
import { toast } from 'sonner'
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
Badge,
Button,
cn,
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogSection,
DialogSectionSeparator,
DialogTitle,
ScrollArea,
Select,
SelectContent,
SelectItem,
SelectTrigger,
Tooltip,
TooltipContent,
TooltipTrigger,
} from 'ui'
import { AdvisorRulesPreview } from './AdvisorRulesPreview'
import { CLSPreview } from './CLSPreview'
import { ExplorerPreview } from './ExplorerPreview'
import { useFeaturePreviewContext, useFeaturePreviewModal } from './FeaturePreviewContext'
import { JitDbAccessPreview } from './JitDbAccessPreview'
import { PgDeltaDiffPreview } from './PgDeltaDiffPreview'
import { PipelineCreationPreview } from './PipelineCreationPreview'
import { PlatformWebhooksPreview } from './PlatformWebhooksPreview'
import { SqlEditorManualSavePreview } from './SqlEditorManualSavePreview'
import { StorageVersioningPreview } from './StorageVersioningPreview'
import { TracesPreview } from './TracesPreview'
import { UnifiedLogsPreview } from './UnifiedLogsPreview'
import { FeaturePreview, useVisibleFeaturePreviewsByCategory } from './useFeaturePreviews'
import { useBannerStack } from '@/components/ui/BannerStack/BannerStackProvider'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { navigateToUrl } from '@/lib/navigation'
import { useTrack } from '@/lib/telemetry/track'
const FEATURE_PREVIEW_KEY_TO_CONTENT: {
[key: string]: ReactNode
} = {
[LOCAL_STORAGE_KEYS.UI_PREVIEW_PIPELINE_CREATION]: <PipelineCreationPreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_PG_DELTA_DIFF]: <PgDeltaDiffPreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_ADVISOR_RULES]: <AdvisorRulesPreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]: <CLSPreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS]: <UnifiedLogsPreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_PLATFORM_WEBHOOKS]: <PlatformWebhooksPreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_JIT_DB_ACCESS]: <JitDbAccessPreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_SQL_EDITOR_MANUAL_SAVE]: <SqlEditorManualSavePreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_EXPLORER]: <ExplorerPreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_STORAGE_VERSIONING]: <StorageVersioningPreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_TRACES]: <TracesPreview />,
}
export const FeaturePreviewModal = () => {
const navigate = useNavigate()
const currentPath = useLocation({ select: (location) => location.pathname.replace(/\/$/, '') })
const { ref } = useParams()
const { dismissBanner } = useBannerStack()
const previewsByCategory = useVisibleFeaturePreviewsByCategory()
const {
showFeaturePreviewModal,
selectedFeatureKey,
selectFeaturePreview,
toggleFeaturePreviewModal,
} = useFeaturePreviewModal()
const featurePreviewContext = useFeaturePreviewContext()
const track = useTrack()
const { flags, onUpdateFlag } = featurePreviewContext
const allFeaturePreviews = previewsByCategory.flatMap(({ previews }) => previews)
const selectedFeature =
allFeaturePreviews.find((preview) => preview.key === selectedFeatureKey) ??
allFeaturePreviews[0]
const isSelectedFeatureEnabled = flags[selectedFeature?.key]
const canDisableSelectedFeature = selectedFeature?.isForced !== true
const selectedFeatureRoute = selectedFeature?.getRoute?.(ref)
const hasRoute = selectedFeatureRoute !== undefined && ref !== undefined
const isAlreadyOnFeatureRoute =
hasRoute &&
(currentPath === selectedFeatureRoute ||
(selectedFeature.matchesSubroutes === true &&
currentPath.startsWith(`${selectedFeatureRoute}/`)))
const shouldRedirect = hasRoute && !isAlreadyOnFeatureRoute
const toggleFeature = () => {
if (!selectedFeature) return
const isEnabling = !isSelectedFeatureEnabled
onUpdateFlag(selectedFeature.key, isEnabling)
track(isEnabling ? 'feature_preview_enabled' : 'feature_preview_disabled', {
feature: selectedFeature.key,
})
if (!isEnabling) {
toast(`${selectedFeature.name} disabled`)
return
}
if (shouldRedirect) {
// Navigating away drops the `featurePreviewModal` query param, which is
// what closes the modal. Don't also close it via
// toggleFeaturePreviewModal — its queued nuqs URL update races the push
// and can navigate back to the current page, swallowing the redirect.
navigateToUrl(navigate, selectedFeatureRoute)
toast.success(`${selectedFeature.name} enabled`, {
description: "We've taken you to where you can try it out.",
})
if (selectedFeature.bannerId) dismissBanner(selectedFeature.bannerId)
} else {
toggleFeaturePreviewModal(false)
toast.success(`${selectedFeature.name} enabled`, {
description: "It's now active across the dashboard.",
})
}
}
return (
<Dialog open={showFeaturePreviewModal} onOpenChange={toggleFeaturePreviewModal}>
<DialogContent size="xlarge" className="flex flex-col max-w-4xl! h-[90dvh] md:h-auto">
<DialogHeader>
<DialogTitle>Dashboard feature previews</DialogTitle>
<DialogDescription>Get early access to new features and give feedback</DialogDescription>
</DialogHeader>
<DialogSectionSeparator />
<DialogSection className="p-0! flex-1 min-h-0 h-full">
{allFeaturePreviews.length > 0 ? (
<div className="max-h-full flex-1 min-h-0 h-full flex flex-col gap-y-1 md:gap-y-4 md:flex-row">
<div>
<ScrollArea className="hidden md:block h-[550px] w-[280px] border-r">
<Accordion
type="multiple"
defaultValue={previewsByCategory.map(({ category }) => category ?? 'others')}
>
{previewsByCategory.map(({ category, previews }) => (
<AccordionItem key={category ?? 'others'} value={category ?? 'others'}>
<AccordionTrigger className="text-xs font-mono uppercase tracking-tight px-4 text-foreground-lighter py-2 bg-tertiary dark:bg-transparent">
{category ?? 'others'}
</AccordionTrigger>
<AccordionContent className="[&>div]:pb-0">
{previews.map((feature) => (
<FeaturePreviewItem
key={feature.key}
feature={feature}
selectedFeature={selectedFeature}
selectFeaturePreview={selectFeaturePreview}
/>
))}
</AccordionContent>
</AccordionItem>
))}
</Accordion>
{/* {allFeaturePreviews.map((feature) => (
<FeaturePreviewItem
key={feature.key}
feature={feature}
selectedFeature={selectedFeature}
selectFeaturePreview={selectFeaturePreview}
/>
))} */}
</ScrollArea>
</div>
<div className="block md:hidden px-4 pt-4">
<Select
value={selectedFeature.key}
onValueChange={selectFeaturePreview}
defaultValue={selectedFeature.name}
>
<SelectTrigger id="feature-preview-select">
<div className="flex items-center gap-x-2">
{(flags[selectedFeature.key] ?? false) ? (
<EyeIcon size={14} strokeWidth={2} className="text-primary" />
) : (
<EyeOffIcon size={14} strokeWidth={1.5} className="text-foreground-light" />
)}
<p>{selectedFeature.name}</p>
{selectedFeature.isNew && <Badge variant="success">New</Badge>}
</div>
</SelectTrigger>
<SelectContent className="p-0! [&>div]:w-full! [&>div]:p-0! [&>div]:flex! [&>div]:flex-col! w-full flex">
{allFeaturePreviews.map((feature) => (
<SelectItem
key={feature.key}
value={feature.key}
className="p-0 [&>span:nth-child(2)]:w-full [&>span:nth-child(1)]:left-3"
>
<FeaturePreviewItem
feature={feature}
selectedFeature={selectedFeature}
selectFeaturePreview={selectFeaturePreview}
className="pl-10 py-3 bg-transparent"
/>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="w-full h-auto min-h-0 max-h-auto md:max-h-[550px] p-4 pb-0 flex flex-col">
<div className="flex items-center justify-between border-b gap-2 pb-3">
<p>{selectedFeature?.name}</p>
<div className="flex items-center gap-x-2">
{selectedFeature?.discussionsUrl !== undefined && (
<Button asChild icon={<ExternalLinkIcon strokeWidth={1.5} />}>
<a
href={selectedFeature.discussionsUrl}
target="_blank"
rel="noreferrer noopener"
>
Give feedback
</a>
</Button>
)}
{isSelectedFeatureEnabled && (
<ButtonTooltip
disabled={!canDisableSelectedFeature}
onClick={() => toggleFeature()}
tooltip={{
content: {
side: 'bottom',
className: 'max-w-64 text-center',
text: canDisableSelectedFeature
? undefined
: 'This feature is now the default and can no longer be turned off',
},
}}
>
Disable feature
</ButtonTooltip>
)}
{!isSelectedFeatureEnabled && (
<Tooltip>
<TooltipTrigger asChild>
<Button onClick={() => toggleFeature()}>Enable feature</Button>
</TooltipTrigger>
<TooltipContent side="bottom" className="max-w-64 text-center">
{hasRoute
? 'Enables the feature and takes you to where you can try it out'
: 'Enables this preview across the dashboard'}
</TooltipContent>
</Tooltip>
)}
</div>
</div>
<div className="overflow-y-scroll pt-3 pb-4">
{FEATURE_PREVIEW_KEY_TO_CONTENT[selectedFeature?.key ?? '']}
</div>
</div>
</div>
) : (
<div className="h-[550px] flex flex-col items-center justify-center">
<FlaskConicalIcon size={30} strokeWidth={1.5} className="text-foreground-light" />
<div className="mt-1 mb-3 flex flex-col items-center gap-y-0.5">
<p className="text-sm">No feature previews available</p>
<p className="text-sm text-foreground-light">
Have an idea for the dashboard? Let us know via GitHub Discussions!
</p>
</div>
<Button asChild icon={<ExternalLinkIcon strokeWidth={1.5} />}>
<a
href="https://github.com/orgs/supabase/discussions/categories/feature-requests"
target="_blank"
rel="noreferrer noopener"
>
GitHub Discussions
</a>
</Button>
</div>
)}
</DialogSection>
</DialogContent>
</Dialog>
)
}
const FeaturePreviewItem = ({
feature,
selectedFeature,
selectFeaturePreview,
className,
}: {
feature: FeaturePreview
selectedFeature: FeaturePreview
selectFeaturePreview: (key: string) => void
className?: string
}) => {
const featurePreviewContext = useFeaturePreviewContext()
const { flags } = featurePreviewContext
const isEnabled = flags[feature.key] ?? false
return (
<button
type="button"
tabIndex={0}
key={feature.key}
onClick={() => selectFeaturePreview(feature.key)}
className={cn(
'w-full! flex-1 flex items-center justify-between p-4 cursor-pointer bg transition',
selectedFeature?.key === feature.key
? 'bg-muted dark:bg-accent text-foreground'
: 'bg-card text-foreground-light',
className
)}
>
<div className="flex items-center gap-x-3">
{isEnabled ? (
<EyeIcon size={14} strokeWidth={2} className="text-primary" />
) : (
<EyeOffIcon size={14} strokeWidth={1.5} className="text-foreground-light" />
)}
<p className="text-sm truncate" title={feature.name}>
{feature.name}
</p>
</div>
{feature.isNew && <Badge variant="success">New</Badge>}
</button>
)
}