Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat(dashboard): redesigned session page and session replay player (#640)

Carl-Gerhard Lindesvärd0d9a8970cd2f
diff --git a/apps/start/src/components/sessions/details/session-journey.tsx b/apps/start/src/components/sessions/details/session-journey.tsx
new file mode 100644
index 000000000..b0687a4f3
--- /dev/null
+++ b/apps/start/src/components/sessions/details/session-journey.tsx
@@ -0,0 +1,87 @@
+import { ChevronRightIcon, RouteIcon } from 'lucide-react';
+import type { SessionPageVisit } from './session-pages';
+import { WidgetHead, WidgetTitle } from '@/components/overview/overview-widget';
+import { Widget } from '@/components/widget';
+import { fancyMinutes } from '@/hooks/use-numer-formatter';
+import { cn } from '@/utils/cn';
+
+const MS_PER_SECOND = 1000;
+const MIN_BAR_PERCENT = 4;
+
+function StepBadge({ label, tone }: { label: string; tone: 'entry' | 'exit' }) {
+ return (
+ <span
+ className={cn(
+ 'rounded px-1 py-px font-semibold text-[10px] uppercase tracking-wider',
+ tone === 'entry'
+ ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400'
+ : 'bg-rose-500/10 text-rose-600 dark:text-rose-400'
+ )}
+ >
+ {label}
+ </span>
+ );
+}
+
+export function SessionJourney({ visits }: { visits: SessionPageVisit[] }) {
+ const pages = visits.filter((visit) => visit.view !== null);
+ if (pages.length === 0) {
+ return null;
+ }
+ const longest = Math.max(...pages.map((page) => page.durationMs), 1);
+
+ return (
+ <Widget className="w-full">
+ <WidgetHead>
+ <WidgetTitle icon={RouteIcon}>Journey</WidgetTitle>
+ </WidgetHead>
+ <ol className="row items-stretch overflow-x-auto p-4">
+ {pages.map((page, index) => {
+ const isFirst = index === 0;
+ const isLast = index === pages.length - 1;
+ const customEvents = page.events.length;
+ const barWidth = Math.max(
+ MIN_BAR_PERCENT,
+ (page.durationMs / longest) * 100
+ );
+ return (
+ <li
+ className="row shrink-0 items-center"
+ key={page.view?.id ?? index}
+ >
+ <div className="col w-36 gap-1.5 rounded-lg border bg-def-100 px-3 py-2.5 transition-colors hover:border-def-400">
+ <div className="row items-center gap-1.5">
+ <span className="font-mono text-2xs text-muted-foreground tabular-nums">
+ {index + 1}
+ </span>
+ {isFirst && <StepBadge label="Entry" tone="entry" />}
+ {isLast && <StepBadge label="Exit" tone="exit" />}
+ </div>
+ <span
+ className="truncate font-medium text-sm"
+ title={page.path}
+ >
+ {page.path}
+ </span>
+ <div className="h-1 overflow-hidden rounded-full bg-def-200">
+ <div
+ className="h-full rounded-full bg-highlight"
+ style={{ width: `${barWidth}%` }}
+ />
+ </div>
+ <span className="text-2xs text-muted-foreground tabular-nums">
+ {fancyMinutes(page.durationMs / MS_PER_SECOND)}
+ {customEvents > 0 &&
+ ` · ${customEvents} ${customEvents === 1 ? 'event' : 'events'}`}
+ </span>
+ </div>
+ {!isLast && (
+ <ChevronRightIcon className="mx-1 size-4 shrink-0 text-def-400" />
+ )}
+ </li>
+ );
+ })}
+ </ol>
+ </Widget>
+ );
+}
diff --git a/apps/start/src/components/sessions/details/session-metrics.tsx b/apps/start/src/components/sessions/details/session-metrics.tsx
new file mode 100644
index 000000000..a9b5099ea
--- /dev/null
+++ b/apps/start/src/components/sessions/details/session-metrics.tsx
@@ -0,0 +1,87 @@
+import type { IServiceEvent, IServiceSession } from '@openpanel/core';
+import {
+ type MetricUnit,
+ OverviewMetricCard,
+} from '@/components/overview/overview-metric-card';
+import { cn } from '@/utils/cn';
+
+const COLUMNS_BY_COUNT: Record<number, string> = {
+ 4: 'xl:grid-cols-4',
+ 5: 'xl:grid-cols-5',
+ 6: 'xl:grid-cols-6',
+};
+const MS_PER_SECOND = 1000;
+
+interface SessionMetric {
+ key: string;
+ label: string;
+ value: number;
+ unit: MetricUnit;
+}
+
+export function SessionMetrics({
+ session,
+ events,
+}: {
+ session: IServiceSession;
+ events: IServiceEvent[];
+}) {
+ const pageViews = events.filter((event) => event.name === 'screen_view');
+ const uniquePages = new Set(pageViews.map((event) => event.path || '/')).size;
+ const durationSeconds = session.duration / MS_PER_SECOND;
+ const hasPageViews = session.screenViewCount > 0;
+
+ // The card's 'min' unit takes seconds and renders them as a duration.
+ const metrics: SessionMetric[] = [
+ { key: 'duration', label: 'Duration', value: durationSeconds, unit: 'min' },
+ {
+ key: 'screenViews',
+ label: 'Page views',
+ value: session.screenViewCount,
+ unit: '',
+ },
+ { key: 'uniquePages', label: 'Unique pages', value: uniquePages, unit: '' },
+ { key: 'events', label: 'Events', value: session.eventCount, unit: '' },
+ ...(hasPageViews
+ ? [
+ {
+ key: 'timePerPage',
+ label: 'Time per page',
+ value: durationSeconds / session.screenViewCount,
+ unit: 'min' as const,
+ },
+ ]
+ : []),
+ ...(session.revenue > 0
+ ? [
+ {
+ key: 'revenue',
+ label: 'Revenue',
+ value: session.revenue,
+ unit: 'currency' as const,
+ },
+ ]
+ : []),
+ ];
+
+ return (
+ <div
+ className={cn(
+ 'card grid grid-cols-2 overflow-hidden rounded-md md:grid-cols-3',
+ COLUMNS_BY_COUNT[metrics.length]
+ )}
+ >
+ {metrics.map((metric) => (
+ <OverviewMetricCard
+ data={[]}
+ id={metric.key}
+ isLoading={false}
+ key={metric.key}
+ label={metric.label}
+ metric={{ current: metric.value, previous: null }}
+ unit={metric.unit}
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/apps/start/src/components/sessions/details/session-pages.ts b/apps/start/src/components/sessions/details/session-pages.ts
new file mode 100644
index 000000000..5a865a9a7
--- /dev/null
+++ b/apps/start/src/components/sessions/details/session-pages.ts
@@ -0,0 +1,77 @@
+import type { IServiceEvent } from '@openpanel/core';
+
+export interface SessionPageVisit {
+ /** The screen view that opened the page; null for events before the first one. */
+ view: IServiceEvent | null;
+ path: string;
+ startedAt: number;
+ durationMs: number;
+ events: IServiceEvent[];
+}
+
+function toMs(date: Date | string): number {
+ return date instanceof Date ? date.getTime() : new Date(date).getTime();
+}
+
+function pagePath(event: IServiceEvent): string {
+ return event.path || '/';
+}
+
+/**
+ * Within one millisecond the query's order is arbitrary, so an event goes after
+ * a screen view only when it happened on that view's page.
+ */
+function compareEvents(a: IServiceEvent, b: IServiceEvent): number {
+ const difference = toMs(a.createdAt) - toMs(b.createdAt);
+ const aIsView = a.name === 'screen_view';
+ const bIsView = b.name === 'screen_view';
+ if (difference !== 0 || aIsView === bIsView) {
+ return difference;
+ }
+ const view = aIsView ? a : b;
+ const other = aIsView ? b : a;
+ const viewGoesFirst = pagePath(other) === pagePath(view);
+ return viewGoesFirst === aIsView ? -1 : 1;
+}
+
+export function sortEventsAscending(events: IServiceEvent[]): IServiceEvent[] {
+ return [...events].sort(compareEvents);
+}
+
+/** Splits a session's events into page visits, each lasting until the next page. */
+export function groupEventsByPage(
+ events: IServiceEvent[],
+ sessionEndedAt: Date
+): SessionPageVisit[] {
+ const visits: SessionPageVisit[] = [];
+ for (const event of sortEventsAscending(events)) {
+ const isPageView = event.name === 'screen_view';
+ const current = visits.at(-1);
+ if (isPageView || !current) {
+ visits.push({
+ view: isPageView ? event : null,
+ path: isPageView ? pagePath(event) : '',
+ startedAt: toMs(event.createdAt),
+ durationMs: 0,
+ events: isPageView ? [] : [event],
+ });
+ continue;
+ }
+ current.events.push(event);
+ }
+
+ const endedAt = toMs(sessionEndedAt);
+ for (const [index, visit] of visits.entries()) {
+ const next = visits[index + 1];
+ const lastEvent = visit.events.at(-1);
+ const end =
+ next?.startedAt ??
+ Math.max(endedAt, lastEvent ? toMs(lastEvent.createdAt) : 0);
+ visit.durationMs = Math.max(0, end - visit.startedAt);
+ }
+ return visits;
+}
+
+export function getElapsedMs(event: IServiceEvent, sessionStart: Date): number {
+ return Math.max(0, toMs(event.createdAt) - toMs(sessionStart));
+}
diff --git a/apps/start/src/components/sessions/details/session-properties.tsx b/apps/start/src/components/sessions/details/session-properties.tsx
new file mode 100644
index 000000000..e3d1563bc
--- /dev/null
+++ b/apps/start/src/components/sessions/details/session-properties.tsx
@@ -0,0 +1,123 @@
+import type { IServiceEvent, IServiceSession } from '@openpanel/core';
+import { parseAsStringEnum, useQueryState } from 'nuqs';
+import {
+ WidgetButtons,
+ WidgetHead,
+} from '@/components/overview/overview-widget';
+import {
+ KeyValueGrid,
+ type KeyValueItem,
+} from '@/components/ui/key-value-grid';
+import { Widget } from '@/components/widget';
+import { fancyMinutes } from '@/hooks/use-numer-formatter';
+import { cn } from '@/utils/cn';
+
+const TABS = [
+ { key: 'session', label: 'Session' },
+ { key: 'source', label: 'Source' },
+ { key: 'device', label: 'Device' },
+] as const;
+type TabKey = (typeof TABS)[number]['key'];
+const MS_PER_SECOND = 1000;
+
+/** Lets the grid's filter links treat session fields like event properties. */
+function sessionAsEvent(session: IServiceSession): IServiceEvent {
+ return {
+ ...session,
+ name: 'screen_view',
+ sessionId: session.id,
+ properties: {},
+ path: session.exitPath,
+ origin: session.exitOrigin,
+ importedAt: undefined,
+ meta: undefined,
+ sdkName: undefined,
+ sdkVersion: undefined,
+ profile: undefined,
+ };
+}
+
+function withVersion(name: string, version: string): string {
+ return version ? `${name} ${version}` : name;
+}
+
+function getItems(session: IServiceSession, tab: TabKey): KeyValueItem[] {
+ const event = sessionAsEvent(session);
+ const items: Record<TabKey, KeyValueItem[]> = {
+ session: [
+ { name: 'id', value: session.id },
+ { name: 'createdAt', value: session.createdAt },
+ { name: 'endedAt', value: session.endedAt },
+ {
+ name: 'duration',
+ value: fancyMinutes(session.duration / MS_PER_SECOND),
+ },
+ { name: 'entryPath', value: session.entryPath },
+ { name: 'exitPath', value: session.exitPath },
+ { name: 'bounce', value: session.isBounce ? 'Yes' : 'No' },
+ { name: 'deviceId', value: session.deviceId },
+ ],
+ source: [
+ { name: 'referrerName', value: session.referrerName, event },
+ { name: 'referrerType', value: session.referrerType, event },
+ { name: 'referrer', value: session.referrer, event },
+ { name: 'utmSource', value: session.utmSource },
+ { name: 'utmMedium', value: session.utmMedium },
+ { name: 'utmCampaign', value: session.utmCampaign },
+ { name: 'utmContent', value: session.utmContent },
+ { name: 'utmTerm', value: session.utmTerm },
+ ],
+ device: [
+ { name: 'country', value: session.country, event },
+ { name: 'region', value: session.region, event },
+ { name: 'city', value: session.city, event },
+ { name: 'device', value: session.device, event },
+ { name: 'os', value: withVersion(session.os, session.osVersion) },
+ {
+ name: 'browser',
+ value: withVersion(session.browser, session.browserVersion),
+ },
+ { name: 'brand', value: session.brand, event },
+ { name: 'model', value: session.model, event },
+ ],
+ };
+ return items[tab].filter(
+ (item) =>
+ item.value !== '' && item.value !== null && item.value !== undefined
+ );
+}
+
+export function SessionProperties({ session }: { session: IServiceSession }) {
+ const [tab, setTab] = useQueryState(
+ 'tab',
+ parseAsStringEnum(TABS.map((t) => t.key)).withDefault('session')
+ );
+ const items = getItems(session, tab);
+
+ return (
+ <Widget className="w-full">
+ <WidgetHead>
+ <div className="title">Details</div>
+ <WidgetButtons>
+ {TABS.map((t) => (
+ <button
+ className={cn(t.key === tab && 'active')}
+ key={t.key}
+ onClick={() => setTab(t.key)}
+ type="button"
+ >
+ {t.label}
+ </button>
+ ))}
+ </WidgetButtons>
+ </WidgetHead>
+ {items.length > 0 ? (
+ <KeyValueGrid className="border-0" columns={1} copyable data={items} />
+ ) : (
+ <div className="p-4 text-muted-foreground text-sm">
+ Nothing recorded for this session.
+ </div>
+ )}
+ </Widget>
+ );
+}
diff --git a/apps/start/src/components/sessions/details/session-timeline.tsx b/apps/start/src/components/sessions/details/session-timeline.tsx
new file mode 100644
index 000000000..a309f42ad
--- /dev/null
+++ b/apps/start/src/components/sessions/details/session-timeline.tsx
@@ -0,0 +1,202 @@
+import type { IServiceEvent } from '@openpanel/core';
+import { ListTreeIcon, ZapIcon } from 'lucide-react';
+import { formatDuration } from '../replay/replay-utils';
+import { getElapsedMs, type SessionPageVisit } from './session-pages';
+import { EmptyState } from '@/components/empty-state';
+import { EventIcon } from '@/components/events/event-icon';
+import { useEventDrawer } from '@/components/events/use-event-drawer';
+import { WidgetHead, WidgetTitle } from '@/components/overview/overview-widget';
+import { Widget } from '@/components/widget';
+import { fancyMinutes } from '@/hooks/use-numer-formatter';
+import { formatTime } from '@/utils/date';
+
+const MS_PER_SECOND = 1000;
+const MAX_PROPERTY_CHIPS = 3;
+const MAX_CHIP_VALUE_LENGTH = 32;
+
+function getPropertyChips(event: IServiceEvent): [string, string][] {
+ return Object.entries(event.properties ?? {})
+ .filter(
+ ([key, value]) =>
+ !key.startsWith('__') &&
+ (typeof value === 'string' ||
+ typeof value === 'number' ||
+ typeof value === 'boolean')
+ )
+ .slice(0, MAX_PROPERTY_CHIPS)
+ .map(([key, value]) => {
+ const text = String(value);
+ return [
+ key,
+ text.length > MAX_CHIP_VALUE_LENGTH
+ ? `${text.slice(0, MAX_CHIP_VALUE_LENGTH)}…`
+ : text,
+ ];
+ });
+}
+
+function Elapsed({ ms }: { ms: number }) {
+ return (
+ <span className="font-mono text-2xs text-muted-foreground tabular-nums">
+ +{formatDuration(ms)}
+ </span>
+ );
+}
+
+function EventRow({
+ event,
+ sessionStart,
+ onOpen,
+}: {
+ event: IServiceEvent;
+ sessionStart: Date;
+ onOpen: () => void;
+}) {
+ const chips = getPropertyChips(event);
+ return (
+ <li className="relative">
+ <span className="absolute top-3.5 left-[-21px] size-2 rounded-full border-2 border-card bg-def-400" />
+ <button
+ className="row w-full items-start gap-2.5 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-def-100"
+ onClick={onOpen}
+ type="button"
+ >
+ <EventIcon meta={event.meta} name={event.name} size="xs" />
+ <span className="col min-w-0 flex-1 gap-1">
+ <span className="truncate text-sm">
+ {event.name.replace(/_/g, ' ')}
+ </span>
+ {chips.length > 0 && (
+ <span className="row flex-wrap gap-1">
+ {chips.map(([key, value]) => (
+ <span
+ className="max-w-full truncate rounded bg-def-200 px-1.5 py-px font-mono text-2xs"
+ key={key}
+ >
+ <span className="text-muted-foreground">{key}</span> {value}
+ </span>
+ ))}
+ </span>
+ )}
+ </span>
+ <span className="leading-5">
+ <Elapsed ms={getElapsedMs(event, sessionStart)} />
+ </span>
+ </button>
+ </li>
+ );
+}
+
+function PageHeader({
+ visit,
+ index,
+ sessionStart,
+ onOpen,
+}: {
+ visit: SessionPageVisit;
+ index: number;
+ sessionStart: Date;
+ onOpen?: () => void;
+}) {
+ const view = visit.view;
+ const content = (
+ <>
+ {view ? (
+ <span className="absolute top-1/2 left-[-27px] grid size-5 -translate-y-1/2 place-items-center rounded-full bg-highlight font-semibold text-[10px] text-white ring-4 ring-card">
+ {index}
+ </span>
+ ) : (
+ <span className="absolute top-1/2 left-[-22px] size-2.5 -translate-y-1/2 rounded-full bg-def-400 ring-4 ring-card" />
+ )}
+ <span className="col min-w-0 flex-1">
+ <span className="truncate font-semibold">
+ {view ? visit.path : 'Session started'}
+ </span>
+ <span className="text-2xs text-muted-foreground">
+ {formatTime(new Date(visit.startedAt))}
+ {view &&
+ ` · ${fancyMinutes(visit.durationMs / MS_PER_SECOND)} on page`}
+ </span>
+ </span>
+ {view && <Elapsed ms={getElapsedMs(view, sessionStart)} />}
+ </>
+ );
+
+ if (!onOpen) {
+ return (
+ <div className="row relative items-center gap-3 px-2 py-2">{content}</div>
+ );
+ }
+ return (
+ <button
+ className="row relative w-full items-center gap-3 rounded-md px-2 py-2 text-left transition-colors hover:bg-def-100"
+ onClick={onOpen}
+ type="button"
+ >
+ {content}
+ </button>
+ );
+}
+
+export function SessionTimeline({
+ visits,
+ sessionStart,
+}: {
+ visits: SessionPageVisit[];
+ sessionStart: Date;
+}) {
+ const { openEvent } = useEventDrawer();
+ const open = (event: IServiceEvent) =>
+ openEvent({ id: event.id, createdAt: event.createdAt });
+ let pageNumber = 0;
+
+ return (
+ <Widget className="w-full">
+ <WidgetHead>
+ <WidgetTitle icon={ListTreeIcon}>Timeline</WidgetTitle>
+ </WidgetHead>
+ {visits.length === 0 ? (
+ <EmptyState
+ description="This session has no events in it."
+ icon={ZapIcon}
+ title="No events"
+ variant="inline"
+ />
+ ) : (
+ <ol className="col gap-1 py-3 pr-3 pl-10">
+ {visits.map((visit, index) => {
+ const view = visit.view;
+ if (view) {
+ pageNumber++;
+ }
+ return (
+ <li
+ className="relative before:absolute before:top-0 before:bottom-0 before:left-[-17px] before:w-px before:bg-border first:before:top-5 last:before:bottom-auto last:before:h-5"
+ key={view?.id ?? `pre-${index}`}
+ >
+ <PageHeader
+ index={pageNumber}
+ onOpen={view ? () => open(view) : undefined}
+ sessionStart={sessionStart}
+ visit={visit}
+ />
+ {visit.events.length > 0 && (
+ <ul className="col gap-0.5 pb-2">
+ {visit.events.map((event) => (
+ <EventRow
+ event={event}
+ key={event.id}
+ onOpen={() => open(event)}
+ sessionStart={sessionStart}
+ />
+ ))}
+ </ul>
+ )}
+ </li>
+ );
+ })}
+ </ol>
+ )}
+ </Widget>
+ );
+}
diff --git a/apps/start/src/components/sessions/replay/browser-chrome.tsx b/apps/start/src/components/sessions/replay/browser-chrome.tsx
deleted file mode 100644
index 6162322f0..000000000
--- a/apps/start/src/components/sessions/replay/browser-chrome.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import type { ReactNode } from 'react';
-import { cn } from '@/utils/cn';
-
-export function BrowserChrome({
- url,
- children,
- right,
- controls = (
- <div className="flex gap-1.5">
- <div className="h-3 w-3 rounded-full bg-red-500" />
- <div className="h-3 w-3 rounded-full bg-yellow-500" />
- <div className="h-3 w-3 rounded-full bg-green-500" />
- </div>
- ),
- className,
-}: {
- url?: ReactNode;
- children: ReactNode;
- right?: ReactNode;
- controls?: ReactNode;
- className?: string;
-}) {
- return (
- <div
- className={cn(
- 'flex flex-col overflow-hidden rounded-lg border border-border bg-background',
- className
- )}
- >
- <div className="flex h-10 items-center gap-2 border-border border-b bg-background px-4 py-2">
- {controls}
- {url !== false && (
- <div className="mx-4 flex h-8 flex-1 items-center truncate rounded-md border border-border bg-def-100 px-3 py-1 text-sm">
- {url}
- </div>
- )}
- {right}
- </div>
- {children}
- </div>
- );
-}
diff --git a/apps/start/src/components/sessions/replay/index.tsx b/apps/start/src/components/sessions/replay/index.tsx
index fb26c8067..7b7b7193f 100644
--- a/apps/start/src/components/sessions/replay/index.tsx
+++ b/apps/start/src/components/sessions/replay/index.tsx
@@ -1,54 +1,30 @@
import type { IServiceEvent } from '@openpanel/core';
import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { Maximize2, Minimize2 } from 'lucide-react';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { BrowserChrome } from './browser-chrome';
-import { ReplayTime } from './replay-controls';
-import { ReplayTimeline } from './replay-timeline';
-import { getEventOffsetMs } from './replay-utils';
+import { FastForwardIcon, VideoOffIcon } from 'lucide-react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import {
ReplayProvider,
useCurrentTime,
useReplayContext,
-} from '@/components/sessions/replay/replay-context';
-import { ReplayEventFeed } from '@/components/sessions/replay/replay-event-feed';
-import { ReplayPlayer } from '@/components/sessions/replay/replay-player';
+} from './replay-context';
+import { ReplayControls, ReplayPlayPauseButton } from './replay-controls';
+import { ReplayEventFeed } from './replay-event-feed';
+import { getStageFitHeight, ReplayPlayer } from './replay-player';
+import { ReplayTimeline } from './replay-timeline';
+import {
+ type EventWithOffset,
+ findLastIndexAtTime,
+ getPageSegments,
+ type PageSegment,
+ type ReplayRecordEvent,
+ sortEventsByOffset,
+} from './replay-utils';
import { useTRPC } from '@/integrations/trpc/react';
+import { cn } from '@/utils/cn';
-function BrowserUrlBar({ events }: { events: IServiceEvent[] }) {
- const { startTime } = useReplayContext();
- const currentTime = useCurrentTime(250);
+const FEED_TICK_MS = 100;
- const currentUrl = useMemo(() => {
- if (startTime == null || !events.length) {
- return '';
- }
-
- const withOffset = events
- .map((ev) => ({
- event: ev,
- offsetMs: getEventOffsetMs(ev, startTime),
- }))
- .filter(({ offsetMs }) => offsetMs >= -10_000 && offsetMs <= currentTime)
- .sort((a, b) => a.offsetMs - b.offsetMs);
-
- const latest = withOffset.at(-1);
- if (!latest) {
- return '';
- }
-
- const { origin = '', path = '/' } = latest.event;
- return `${origin}${path}`;
- }, [events, currentTime, startTime]);
-
- return <span className="truncate text-muted-foreground">{currentUrl}</span>;
-}
-
-/**
- * Feeds remaining chunks into the player after it's ready.
- * Receives already-fetched chunks from the initial batch, then pages
- * through the rest using replayChunksFrom.
- */
+/** Pages through the chunks after the first batch and feeds them to the player. */
function ReplayChunkLoader({
sessionId,
projectId,
@@ -60,9 +36,12 @@ function ReplayChunkLoader({
}) {
const trpc = useTRPC();
const queryClient = useQueryClient();
- const { addEvent, refreshDuration } = useReplayContext();
+ const { addEvent, refreshDuration, isReady } = useReplayContext();
useEffect(() => {
+ if (!isReady) {
+ return;
+ }
let cancelled = false;
function loadFrom(index: number) {
@@ -84,13 +63,12 @@ function ReplayChunkLoader({
}
}
refreshDuration();
- const advanced = res.nextIndex > index;
- if (res.hasMore && advanced) {
+ if (res.hasMore && res.nextIndex > index) {
loadFrom(res.nextIndex);
}
})
.catch(() => {
- // chunk loading failed — replay may be incomplete
+ // A failed page leaves the replay shorter, not broken.
});
}
@@ -98,72 +76,211 @@ function ReplayChunkLoader({
return () => {
cancelled = true;
};
- }, []);
+ }, [
+ isReady,
+ queryClient,
+ trpc,
+ sessionId,
+ projectId,
+ fromIndex,
+ addEvent,
+ refreshDuration,
+ ]);
return null;
}
-function FullscreenButton({
- containerRef,
-}: {
- containerRef: React.RefObject<HTMLDivElement | null>;
-}) {
- const [isFullscreen, setIsFullscreen] = useState(false);
+function CurrentUrl({ segment }: { segment: PageSegment | undefined }) {
+ if (!segment) {
+ return <span className="truncate text-muted-foreground">about:blank</span>;
+ }
+ const host = segment.origin.replace(/^https?:\/\//, '');
+ return (
+ <span
+ className="fade-in-0 slide-in-from-bottom-1 min-w-0 animate-in truncate duration-300"
+ key={segment.id}
+ >
+ <span className="text-muted-foreground">{host}</span>
+ <span className="text-foreground">{segment.path}</span>
+ </span>
+ );
+}
- useEffect(() => {
- const onChange = () => setIsFullscreen(!!document.fullscreenElement);
- document.addEventListener('fullscreenchange', onChange);
- return () => document.removeEventListener('fullscreenchange', onChange);
- }, []);
+/** A big play button until the viewer starts the replay for the first time. */
+function StartOverlay() {
+ const { isPlaying, isReady } = useReplayContext();
+ const [hasStarted, setHasStarted] = useState(false);
- const toggle = useCallback(() => {
- if (!containerRef.current) {
- return;
+ useEffect(() => {
+ if (isPlaying) {
+ setHasStarted(true);
}
- if (document.fullscreenElement) {
- document.exitFullscreen();
- } else {
- containerRef.current.requestFullscreen();
+ }, [isPlaying]);
+
+ if (!isReady || hasStarted) {
+ return null;
+ }
+
+ return (
+ <div className="fade-in-0 absolute inset-0 z-10 grid animate-in place-items-center bg-background/20 backdrop-blur-[1.5px]">
+ <ReplayPlayPauseButton size="lg" />
+ </div>
+ );
+}
+
+function SkippingBadge() {
+ const { isSkipping, isPlaying } = useReplayContext();
+ if (!(isSkipping && isPlaying)) {
+ return null;
+ }
+ return (
+ <div className="fade-in-0 zoom-in-95 row absolute top-4 left-1/2 z-20 -translate-x-1/2 animate-in items-center gap-1.5 rounded-full bg-foreground/90 px-3 py-1.5 font-medium text-background text-xs shadow-lg backdrop-blur">
+ <FastForwardIcon className="size-3.5 animate-pulse" fill="currentColor" />
+ Skipping idle time
+ </div>
+ );
+}
+
+type StageStatus = 'loading' | 'error' | 'empty';
+
+function StagePlaceholder({ status }: { status: StageStatus }) {
+ if (status === 'loading') {
+ return (
+ <div className="absolute inset-0 grid place-items-center p-6">
+ <div className="col aspect-video w-full max-w-3xl overflow-hidden rounded-xl bg-card shadow-[0_0_0_1px_var(--border)]">
+ <div className="h-9 border-b bg-def-100" />
+ <div className="relative flex-1 overflow-hidden">
+ <div className="absolute inset-0 animate-pulse bg-def-100" />
+ <div className="absolute inset-0 grid place-items-center text-muted-foreground text-sm">
+ Loading recording…
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+ }
+ return (
+ <div className="col absolute inset-0 items-center justify-center gap-3 text-muted-foreground">
+ <VideoOffIcon className="size-8" />
+ <span className="text-sm">
+ {status === 'error'
+ ? 'The recording could not be loaded. Reload the page to try again.'
+ : 'No recording was captured for this session.'}
+ </span>
+ </div>
+ );
+}
+
+function getStageStatus(isLoading: boolean, isError: boolean): StageStatus {
+ if (isLoading) {
+ return 'loading';
+ }
+ return isError ? 'error' : 'empty';
+}
+
+function ReplayStage({
+ events,
+ playerEvents,
+ isLoading,
+ isError,
+ fullscreenTarget,
+}: {
+ events: IServiceEvent[];
+ playerEvents: ReplayRecordEvent[];
+ isLoading: boolean;
+ isError: boolean;
+ fullscreenTarget: React.RefObject<HTMLDivElement | null>;
+}) {
+ const { startTime, duration } = useReplayContext();
+ const currentTime = useCurrentTime(FEED_TICK_MS);
+
+ // Until the duration is known every event is kept; after that, only what
+ // the recording covers can be seeked to.
+ const sorted = useMemo<EventWithOffset[]>(() => {
+ if (startTime == null) {
+ return [];
}
- }, [containerRef]);
+ const all = sortEventsByOffset(events, startTime);
+ return duration > 0
+ ? all.filter(({ offsetMs }) => offsetMs <= duration)
+ : all;
+ }, [events, startTime, duration]);
+ const segments = useMemo(
+ () => getPageSegments(sorted, duration),
+ [sorted, duration]
+ );
+ const currentIndex = findLastIndexAtTime(sorted, currentTime);
+ const currentSegment =
+ segments.filter((segment) => segment.startMs <= currentTime).at(-1) ??
+ segments[0];
+ const hasRecording = playerEvents.length > 0;
+ const stageFitHeight = useMemo(
+ () => getStageFitHeight(playerEvents),
+ [playerEvents]
+ );
return (
- <button
- aria-label={isFullscreen ? 'Exit fullscreen' : 'Enter fullscreen'}
- className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:text-foreground"
- onClick={toggle}
- type="button"
- >
- {isFullscreen ? (
- <Minimize2 className="h-3.5 w-3.5" />
- ) : (
- <Maximize2 className="h-3.5 w-3.5" />
- )}
- </button>
+ <div className="grid in-[:fullscreen]:h-full min-h-0 lg:grid-cols-[minmax(0,1fr)_320px]">
+ <div className="@container col min-w-0">
+ <div
+ className={cn(
+ 'relative h-[max(360px,min(clamp(420px,64vh,760px),var(--stage-fit)))] in-[:fullscreen]:h-auto in-[:fullscreen]:flex-1 overflow-hidden bg-def-100',
+ 'bg-[radial-gradient(var(--def-300)_1px,transparent_1px)] [background-size:18px_18px]'
+ )}
+ style={{ '--stage-fit': stageFitHeight } as React.CSSProperties}
+ >
+ <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_80%_60%_at_50%_0%,color-mix(in_oklab,var(--highlight)_14%,transparent),transparent)]" />
+ {hasRecording ? (
+ <ReplayPlayer
+ events={playerEvents}
+ overlay={<StartOverlay />}
+ url={<CurrentUrl segment={currentSegment} />}
+ />
+ ) : (
+ <StagePlaceholder status={getStageStatus(isLoading, isError)} />
+ )}
+ <SkippingBadge />
+ </div>
+ <div className="col gap-3 border-t bg-card px-4 pt-2 pb-3">
+ <ReplayTimeline
+ currentSegmentId={currentSegment?.id ?? null}
+ events={sorted}
+ segments={segments}
+ />
+ <ReplayControls events={sorted} fullscreenTarget={fullscreenTarget} />
+ </div>
+ </div>
+ <aside className="relative hidden border-l bg-card lg:block">
+ <div className="absolute inset-0">
+ <ReplayEventFeed
+ currentIndex={currentIndex}
+ events={sorted}
+ isLoading={isLoading || (hasRecording && startTime == null)}
+ />
+ </div>
+ </aside>
+ </div>
);
}
-function ReplayContent({
+export function ReplayShell({
sessionId,
projectId,
+ events,
}: {
sessionId: string;
projectId: string;
+ events: IServiceEvent[];
}) {
const trpc = useTRPC();
- const containerRef = useRef<HTMLDivElement>(null);
+ const rootRef = useRef<HTMLDivElement>(null);
- const { data: eventsData } = useQuery(
- trpc.event.events.queryOptions({
- projectId,
- sessionId,
- filters: [],
- columnVisibility: {},
- })
- );
-
- // Fetch first batch of chunks (includes chunk 0 for player init + more)
- const { data: firstBatch, isLoading: replayLoading } = useQuery(
+ // The first batch carries the full snapshot the player needs to start.
+ const {
+ data: firstBatch,
+ isLoading,
+ isError,
+ } = useQuery(
trpc.session.replayChunksFrom.queryOptions({
sessionId,
projectId,
@@ -171,67 +288,30 @@ function ReplayContent({
})
);
- const events = eventsData?.data ?? [];
- const playerEvents =
- firstBatch?.data.flatMap((row) => row?.events ?? []) ?? [];
- const hasMore = firstBatch?.hasMore ?? false;
- const hasReplay = playerEvents.length !== 0;
-
- function renderReplay() {
- if (replayLoading) {
- return (
- <div className="col h-[320px] items-center justify-center gap-4 bg-background">
- <div className="h-8 w-8 animate-pulse rounded-full bg-muted" />
- <div>Loading session replay</div>
- </div>
- );
- }
- if (hasReplay) {
- return <ReplayPlayer events={playerEvents} />;
- }
- return (
- <div className="flex h-[320px] items-center justify-center bg-background text-muted-foreground text-sm">
- No replay data available for this session.
- </div>
- );
- }
+ const playerEvents = useMemo(
+ () => firstBatch?.data.flatMap((row) => row?.events ?? []) ?? [],
+ [firstBatch]
+ );
return (
- <ReplayProvider>
+ // Keyed so playback state (e.g. the start overlay) resets per session.
+ <ReplayProvider key={sessionId}>
<div
- className="grid gap-4 lg:grid-cols-[1fr_380px] [&:fullscreen]:flex [&:fullscreen]:flex-col [&:fullscreen]:bg-background [&:fullscreen]:p-4"
+ className="card overflow-hidden [&:fullscreen]:rounded-none [&:fullscreen]:border-0"
id="replay"
- ref={containerRef}
+ ref={rootRef}
>
- <div className="flex min-w-0 flex-col overflow-hidden">
- <BrowserChrome
- right={
- <div className="flex items-center gap-2">
- {hasReplay && <ReplayTime />}
- <FullscreenButton containerRef={containerRef} />
- </div>
- }
- url={
- hasReplay ? (
- <BrowserUrlBar events={events} />
- ) : (
- <span className="text-muted-foreground">about:blank</span>
- )
- }
- >
- {renderReplay()}
- {hasReplay && <ReplayTimeline events={events} />}
- </BrowserChrome>
- </div>
- <div className="relative hidden lg:block">
- <div className="absolute inset-0">
- <ReplayEventFeed events={events} replayLoading={replayLoading} />
- </div>
- </div>
+ <ReplayStage
+ events={events}
+ fullscreenTarget={rootRef}
+ isError={isError}
+ isLoading={isLoading}
+ playerEvents={playerEvents}
+ />
</div>
- {hasReplay && hasMore && (
+ {firstBatch?.hasMore && (
<ReplayChunkLoader
- fromIndex={firstBatch?.nextIndex ?? 0}
+ fromIndex={firstBatch.nextIndex}
projectId={projectId}
sessionId={sessionId}
/>
@@ -239,13 +319,3 @@ function ReplayContent({
</ReplayProvider>
);
}
-
-export function ReplayShell({
- sessionId,
- projectId,
-}: {
- sessionId: string;
- projectId: string;
-}) {
- return <ReplayContent projectId={projectId} sessionId={sessionId} />;
-}
diff --git a/apps/start/src/components/sessions/replay/replay-context.tsx b/apps/start/src/components/sessions/replay/replay-context.tsx
index cba34b19a..d70bc52cf 100644
--- a/apps/start/src/components/sessions/replay/replay-context.tsx
+++ b/apps/start/src/components/sessions/replay/replay-context.tsx
@@ -7,6 +7,11 @@ import {
useRef,
useState,
} from 'react';
+import {
+ getClick,
+ isUserInteraction,
+ type ReplayRecordEvent,
+} from './replay-utils';
export interface ReplayPlayerInstance {
play: () => void;
@@ -14,9 +19,10 @@ export interface ReplayPlayerInstance {
toggle: () => void;
goto: (timeOffset: number, play?: boolean) => void;
setSpeed: (speed: number) => void;
+ toggleSkipInactive: () => void;
+ triggerResize: () => void;
getMetaData: () => { startTime: number; endTime: number; totalTime: number };
- getReplayer: () => { getCurrentTime: () => number };
- addEvent: (event: { type: number; data: unknown; timestamp: number }) => void;
+ addEvent: (event: ReplayRecordEvent) => void;
addEventListener: (
event: string,
handler: (e: { payload: unknown }) => void
@@ -27,41 +33,49 @@ export interface ReplayPlayerInstance {
type CurrentTimeListener = (t: number) => void;
+export interface RecordingActivity {
+ interactions: number[];
+ clicks: { timestamp: number; x: number; y: number }[];
+}
+
+export const SPEED_OPTIONS = [0.5, 1, 2, 4, 8] as const;
+export type ReplaySpeed = (typeof SPEED_OPTIONS)[number];
+const DEFAULT_SPEED: ReplaySpeed = 1;
+export const DEFAULT_SKIP_INACTIVE = true;
+
interface ReplayContextValue {
// High-frequency value — read via ref, not state. Use subscribeToCurrentTime
// or useCurrentTime() to get updates without causing 60fps re-renders.
currentTimeRef: React.MutableRefObject<number>;
subscribeToCurrentTime: (fn: CurrentTimeListener) => () => void;
- // Low-frequency state (safe to consume directly)
isPlaying: boolean;
+ isSkipping: boolean;
duration: number;
startTime: number | null;
isReady: boolean;
- // Playback controls
+ speed: ReplaySpeed;
+ skipInactive: boolean;
+ activity: RecordingActivity;
play: () => void;
pause: () => void;
toggle: () => void;
seek: (timeMs: number) => void;
- setSpeed: (speed: number) => void;
- // Lazy chunk loading
- addEvent: (event: { type: number; data: unknown; timestamp: number }) => void;
+ setSpeed: (speed: ReplaySpeed) => void;
+ toggleSkipInactive: () => void;
+ addEvent: (event: ReplayRecordEvent) => void;
refreshDuration: () => void;
- // Called by ReplayPlayer to register/unregister the rrweb instance
onPlayerReady: (
player: ReplayPlayerInstance,
- playerStartTime: number
+ initialEvents: ReplayRecordEvent[]
) => void;
onPlayerDestroy: () => void;
- // State setters exposed so ReplayPlayer can wire rrweb event listeners
setCurrentTime: (t: number) => void;
setIsPlaying: (p: boolean) => void;
- setDuration: (d: number) => void;
+ setIsSkipping: (s: boolean) => void;
}
const ReplayContext = createContext<ReplayContextValue | null>(null);
-const SPEED_OPTIONS = [0.5, 1, 2, 4, 8] as const;
-
export function useReplayContext() {
const ctx = useContext(ReplayContext);
if (!ctx) {
@@ -97,16 +111,28 @@ export function useCurrentTime(intervalMs = 0): number {
return time;
}
+const EMPTY_ACTIVITY: RecordingActivity = { interactions: [], clicks: [] };
+
export function ReplayProvider({ children }: { children: ReactNode }) {
const playerRef = useRef<ReplayPlayerInstance | null>(null);
const isPlayingRef = useRef(false);
const currentTimeRef = useRef(0);
const listenersRef = useRef<Set<CurrentTimeListener>>(new Set());
+ // Chunks stream in after the player starts; collect what they tell us about
+ // the user's activity here and publish it in one go per batch.
+ const activityRef = useRef<RecordingActivity>({
+ interactions: [],
+ clicks: [],
+ });
const [isPlaying, setIsPlaying] = useState(false);
+ const [isSkipping, setIsSkipping] = useState(false);
const [duration, setDuration] = useState(0);
const [startTime, setStartTime] = useState<number | null>(null);
const [isReady, setIsReady] = useState(false);
+ const [speed, setSpeedState] = useState<ReplaySpeed>(DEFAULT_SPEED);
+ const [skipInactive, setSkipInactive] = useState(DEFAULT_SKIP_INACTIVE);
+ const [activity, setActivity] = useState<RecordingActivity>(EMPTY_ACTIVITY);
const setIsPlayingWithRef = useCallback((playing: boolean) => {
isPlayingRef.current = playing;
@@ -129,15 +155,52 @@ export function ReplayProvider({ children }: { children: ReactNode }) {
}
}, []);
+ const collectActivity = useCallback((event: ReplayRecordEvent) => {
+ if (!isUserInteraction(event)) {
+ return;
+ }
+ activityRef.current.interactions.push(event.timestamp);
+ const click = getClick(event);
+ if (click) {
+ activityRef.current.clicks.push(click);
+ }
+ }, []);
+
+ const publishActivity = useCallback(() => {
+ setActivity({
+ interactions: [...activityRef.current.interactions],
+ clicks: [...activityRef.current.clicks],
+ });
+ }, []);
+
+ // rrweb queues each added event in a microtask; reading the metadata in the
+ // next one sees the whole batch instead of the length before it.
+ const refreshDuration = useCallback(() => {
+ queueMicrotask(() => {
+ const total = playerRef.current?.getMetaData().totalTime ?? 0;
+ if (total > 0) {
+ setDuration(total);
+ }
+ publishActivity();
+ });
+ }, [publishActivity]);
+
const onPlayerReady = useCallback(
- (player: ReplayPlayerInstance, playerStartTime: number) => {
+ (player: ReplayPlayerInstance, initialEvents: ReplayRecordEvent[]) => {
playerRef.current = player;
- setStartTime(playerStartTime);
+ activityRef.current = { interactions: [], clicks: [] };
+ for (const event of initialEvents) {
+ collectActivity(event);
+ }
+ setStartTime(player.getMetaData().startTime);
currentTimeRef.current = 0;
setIsPlayingWithRef(false);
+ setSpeedState(DEFAULT_SPEED);
+ setSkipInactive(DEFAULT_SKIP_INACTIVE);
+ refreshDuration();
setIsReady(true);
},
- [setIsPlayingWithRef]
+ [collectActivity, refreshDuration, setIsPlayingWithRef]
);
const onPlayerDestroy = useCallback(() => {
@@ -147,6 +210,8 @@ export function ReplayProvider({ children }: { children: ReactNode }) {
setDuration(0);
setStartTime(null);
setIsPlayingWithRef(false);
+ setIsSkipping(false);
+ setActivity(EMPTY_ACTIVITY);
}, [setIsPlayingWithRef]);
const play = useCallback(() => {
@@ -162,54 +227,54 @@ export function ReplayProvider({ children }: { children: ReactNode }) {
}, []);
const seek = useCallback((timeMs: number) => {
- playerRef.current?.goto(timeMs, isPlayingRef.current);
+ playerRef.current?.goto(Math.max(0, timeMs), isPlayingRef.current);
}, []);
- const setSpeed = useCallback((s: number) => {
- if (!SPEED_OPTIONS.includes(s as (typeof SPEED_OPTIONS)[number])) {
- return;
- }
- playerRef.current?.setSpeed(s);
+ const setSpeed = useCallback((next: ReplaySpeed) => {
+ playerRef.current?.setSpeed(next);
+ setSpeedState(next);
+ }, []);
+
+ const toggleSkipInactive = useCallback(() => {
+ playerRef.current?.toggleSkipInactive();
+ setSkipInactive((current) => !current);
}, []);
const addEvent = useCallback(
- (event: { type: number; data: unknown; timestamp: number }) => {
+ (event: ReplayRecordEvent) => {
playerRef.current?.addEvent(event);
+ collectActivity(event);
},
- []
+ [collectActivity]
);
- const refreshDuration = useCallback(() => {
- const total = playerRef.current?.getMetaData().totalTime ?? 0;
- if (total > 0) {
- setDuration(total);
- }
- }, []);
-
const value: ReplayContextValue = {
currentTimeRef,
subscribeToCurrentTime,
isPlaying,
+ isSkipping,
duration,
startTime,
isReady,
+ speed,
+ skipInactive,
+ activity,
play,
pause,
toggle,
seek,
setSpeed,
+ toggleSkipInactive,
addEvent,
refreshDuration,
onPlayerReady,
onPlayerDestroy,
setCurrentTime,
setIsPlaying: setIsPlayingWithRef,
- setDuration,
+ setIsSkipping,
};
return (
<ReplayContext.Provider value={value}>{children}</ReplayContext.Provider>
);
}
-
-export { SPEED_OPTIONS };
diff --git a/apps/start/src/components/sessions/replay/replay-controls.tsx b/apps/start/src/components/sessions/replay/replay-controls.tsx
index d3edb07d3..4a0d57644 100644
--- a/apps/start/src/components/sessions/replay/replay-controls.tsx
+++ b/apps/start/src/components/sessions/replay/replay-controls.tsx
@@ -1,38 +1,347 @@
-import { Pause, Play } from 'lucide-react';
-import { formatDuration } from './replay-utils';
import {
+ FastForwardIcon,
+ Maximize2Icon,
+ Minimize2Icon,
+ PauseIcon,
+ PlayIcon,
+ RotateCcwIcon,
+ RotateCwIcon,
+ SkipBackIcon,
+ SkipForwardIcon,
+} from 'lucide-react';
+import { type ReactNode, useCallback, useEffect, useState } from 'react';
+import {
+ SPEED_OPTIONS,
useCurrentTime,
useReplayContext,
-} from '@/components/sessions/replay/replay-context';
-import { Button } from '@/components/ui/button';
+} from './replay-context';
+import { type EventWithOffset, formatDuration } from './replay-utils';
+import { Tooltiper } from '@/components/ui/tooltip';
+import { cn } from '@/utils/cn';
-export function ReplayTime() {
- const { duration } = useReplayContext();
- const currentTime = useCurrentTime(250);
+const JUMP_MS = 10_000;
+// Jumping to "previous event" right after one fired should go to the one before.
+const PREVIOUS_EVENT_GRACE_MS = 1500;
+function ControlButton({
+ label,
+ shortcut,
+ onClick,
+ children,
+ active,
+ className,
+}: {
+ label: string;
+ shortcut?: string;
+ onClick: () => void;
+ children: ReactNode;
+ active?: boolean;
+ className?: string;
+}) {
return (
- <span className="text-muted-foreground text-sm tabular-nums tabular-nums">
- {formatDuration(currentTime)} / {formatDuration(duration)}
- </span>
+ <Tooltiper
+ asChild
+ content={
+ <span>
+ {label}
+ {shortcut && (
+ <kbd className="ml-2 rounded border bg-def-100 px-1 font-mono text-2xs text-muted-foreground">
+ {shortcut}
+ </kbd>
+ )}
+ </span>
+ }
+ >
+ <button
+ aria-label={label}
+ className={cn(
+ 'flex h-8 min-w-8 items-center justify-center rounded-md px-1.5 text-muted-foreground transition-colors hover:bg-def-200 hover:text-foreground',
+ active && 'bg-highlight/10 text-highlight hover:bg-highlight/15',
+ className
+ )}
+ onClick={onClick}
+ type="button"
+ >
+ {children}
+ </button>
+ </Tooltiper>
);
}
-export function ReplayPlayPauseButton() {
+export function ReplayPlayPauseButton({ size = 'md' }: { size?: 'md' | 'lg' }) {
const { isPlaying, isReady, toggle } = useReplayContext();
-
- if (!isReady) {
- return null;
- }
+ const isLarge = size === 'lg';
return (
- <Button
+ <button
aria-label={isPlaying ? 'Pause' : 'Play'}
+ className={cn(
+ 'flex shrink-0 items-center justify-center rounded-full bg-foreground text-background shadow-sm transition-transform hover:scale-105 active:scale-95 disabled:opacity-40',
+ isLarge ? 'size-16 shadow-2xl' : 'size-9'
+ )}
+ disabled={!isReady}
onClick={toggle}
- size="icon"
type="button"
- variant={isPlaying ? 'outline' : 'default'}
>
- {isPlaying ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
- </Button>
+ {isPlaying ? (
+ <PauseIcon
+ className={isLarge ? 'size-6' : 'size-4'}
+ fill="currentColor"
+ />
+ ) : (
+ <PlayIcon
+ className={cn('translate-x-px', isLarge ? 'size-6' : 'size-4')}
+ fill="currentColor"
+ />
+ )}
+ </button>
+ );
+}
+
+function ReplayTime() {
+ const { duration } = useReplayContext();
+ const currentTime = useCurrentTime(250);
+
+ return (
+ <span className="font-mono text-xs tabular-nums">
+ <span className="text-foreground">{formatDuration(currentTime)}</span>
+ <span className="text-muted-foreground">
+ {' '}
+ / {formatDuration(duration)}
+ </span>
+ </span>
+ );
+}
+
+function useEventJumps(events: EventWithOffset[]) {
+ const { currentTimeRef, seek } = useReplayContext();
+ const next = useCallback(() => {
+ const target = events.find(
+ ({ offsetMs }) => offsetMs > currentTimeRef.current + 1
+ );
+ if (target) {
+ seek(target.offsetMs);
+ }
+ }, [events, currentTimeRef, seek]);
+ const previous = useCallback(() => {
+ const target = events
+ .filter(
+ ({ offsetMs }) =>
+ offsetMs < currentTimeRef.current - PREVIOUS_EVENT_GRACE_MS
+ )
+ .at(-1);
+ seek(target ? target.offsetMs : 0);
+ }, [events, currentTimeRef, seek]);
+ return { next, previous };
+}
+
+function useFullscreen(target: React.RefObject<HTMLElement | null>) {
+ const [isFullscreen, setIsFullscreen] = useState(false);
+
+ useEffect(() => {
+ const onChange = () =>
+ setIsFullscreen(document.fullscreenElement === target.current);
+ document.addEventListener('fullscreenchange', onChange);
+ return () => document.removeEventListener('fullscreenchange', onChange);
+ }, [target]);
+
+ const toggle = useCallback(() => {
+ if (document.fullscreenElement) {
+ document.exitFullscreen();
+ } else {
+ target.current?.requestFullscreen();
+ }
+ }, [target]);
+
+ return { isFullscreen, toggle };
+}
+
+function nextSpeed(current: number, direction: 1 | -1) {
+ const index = SPEED_OPTIONS.indexOf(
+ current as (typeof SPEED_OPTIONS)[number]
+ );
+ const nextIndex = Math.max(
+ 0,
+ Math.min(SPEED_OPTIONS.length - 1, index + direction)
+ );
+ return SPEED_OPTIONS[nextIndex] ?? SPEED_OPTIONS[1];
+}
+
+/** Player shortcuts; ignored while the user is typing anywhere on the page. */
+function useReplayHotkeys({
+ events,
+ scope,
+ onFullscreen,
+}: {
+ events: EventWithOffset[];
+ scope: React.RefObject<HTMLElement | null>;
+ onFullscreen: () => void;
+}) {
+ const {
+ isReady,
+ toggle,
+ seek,
+ currentTimeRef,
+ duration,
+ speed,
+ setSpeed,
+ toggleSkipInactive,
+ } = useReplayContext();
+ const jumps = useEventJumps(events);
+
+ useEffect(() => {
+ if (!isReady) {
+ return;
+ }
+ const onKeyDown = (e: KeyboardEvent) => {
+ const hasModifier = e.metaKey || e.ctrlKey || e.altKey;
+ // Only while nothing else on the page has focus, or focus is in the player.
+ const isInScope =
+ e.target === document.body ||
+ (e.target instanceof Node && scope.current?.contains(e.target));
+ if (hasModifier || !isInScope) {
+ return;
+ }
+ const actions: Record<string, () => void> = {
+ ' ': toggle,
+ k: toggle,
+ j: () => seek(currentTimeRef.current - JUMP_MS),
+ l: () => seek(Math.min(duration, currentTimeRef.current + JUMP_MS)),
+ ',': jumps.previous,
+ '.': jumps.next,
+ '<': () => setSpeed(nextSpeed(speed, -1)),
+ '>': () => setSpeed(nextSpeed(speed, 1)),
+ i: toggleSkipInactive,
+ f: onFullscreen,
+ };
+ const action = actions[e.key];
+ if (!action) {
+ return;
+ }
+ // Space on a focused button would also click it.
+ const isButton = e.target instanceof HTMLButtonElement;
+ if (e.key === ' ' && isButton) {
+ return;
+ }
+ e.preventDefault();
+ action();
+ };
+ window.addEventListener('keydown', onKeyDown);
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, [
+ isReady,
+ toggle,
+ seek,
+ currentTimeRef,
+ duration,
+ speed,
+ setSpeed,
+ toggleSkipInactive,
+ jumps,
+ scope,
+ onFullscreen,
+ ]);
+}
+
+export function ReplayControls({
+ events,
+ fullscreenTarget,
+}: {
+ events: EventWithOffset[];
+ fullscreenTarget: React.RefObject<HTMLElement | null>;
+}) {
+ const {
+ isReady,
+ seek,
+ currentTimeRef,
+ duration,
+ speed,
+ setSpeed,
+ skipInactive,
+ toggleSkipInactive,
+ } = useReplayContext();
+ const jumps = useEventJumps(events);
+ const fullscreen = useFullscreen(fullscreenTarget);
+ useReplayHotkeys({
+ events,
+ scope: fullscreenTarget,
+ onFullscreen: fullscreen.toggle,
+ });
+
+ return (
+ <div
+ className={cn(
+ 'row items-center gap-1 transition-opacity',
+ !isReady && 'pointer-events-none opacity-40'
+ )}
+ >
+ <ReplayPlayPauseButton />
+ <div className="row ml-2 items-center">
+ <ControlButton
+ label="Previous event"
+ onClick={jumps.previous}
+ shortcut=","
+ >
+ <SkipBackIcon className="size-4" />
+ </ControlButton>
+ <ControlButton
+ label="Back 10 seconds"
+ onClick={() => seek(currentTimeRef.current - JUMP_MS)}
+ shortcut="J"
+ >
+ <RotateCcwIcon className="size-4" />
+ </ControlButton>
+ <ControlButton
+ label="Forward 10 seconds"
+ onClick={() =>
+ seek(Math.min(duration, currentTimeRef.current + JUMP_MS))
+ }
+ shortcut="L"
+ >
+ <RotateCwIcon className="size-4" />
+ </ControlButton>
+ <ControlButton label="Next event" onClick={jumps.next} shortcut=".">
+ <SkipForwardIcon className="size-4" />
+ </ControlButton>
+ </div>
+ <div className="ml-2">
+ <ReplayTime />
+ </div>
+
+ <div className="row ml-auto items-center gap-1">
+ <ControlButton
+ active={skipInactive}
+ className="gap-1.5 px-2.5 font-medium text-xs"
+ label={skipInactive ? 'Skipping idle time' : 'Skip idle time'}
+ onClick={toggleSkipInactive}
+ shortcut="I"
+ >
+ <FastForwardIcon className="size-3.5" />
+ <span className="hidden sm:inline">Skip idle</span>
+ </ControlButton>
+ <ControlButton
+ className="w-11 font-mono font-semibold text-xs tabular-nums"
+ label="Playback speed"
+ onClick={() => {
+ const index = SPEED_OPTIONS.indexOf(speed);
+ setSpeed(SPEED_OPTIONS[(index + 1) % SPEED_OPTIONS.length]!);
+ }}
+ shortcut="< >"
+ >
+ {speed}×
+ </ControlButton>
+ <ControlButton
+ label={fullscreen.isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}
+ onClick={fullscreen.toggle}
+ shortcut="F"
+ >
+ {fullscreen.isFullscreen ? (
+ <Minimize2Icon className="size-4" />
+ ) : (
+ <Maximize2Icon className="size-4" />
+ )}
+ </ControlButton>
+ </div>
+ </div>
);
}
diff --git a/apps/start/src/components/sessions/replay/replay-event-feed.tsx b/apps/start/src/components/sessions/replay/replay-event-feed.tsx
index d2fbd9958..ea98a4764 100644
--- a/apps/start/src/components/sessions/replay/replay-event-feed.tsx
+++ b/apps/start/src/components/sessions/replay/replay-event-feed.tsx
@@ -1,119 +1,97 @@
-import type { IServiceEvent } from '@openpanel/core';
-import { useEffect, useMemo, useRef } from 'react';
-import { BrowserChrome } from './browser-chrome';
-import { getEventOffsetMs } from './replay-utils';
-import {
- useCurrentTime,
- useReplayContext,
-} from '@/components/sessions/replay/replay-context';
-import { ReplayEventItem } from '@/components/sessions/replay/replay-event-item';
+import { useEffect, useRef } from 'react';
+import { useReplayContext } from './replay-context';
+import { ReplayEventItem, type ReplayItemState } from './replay-event-item';
+import type { EventWithOffset } from './replay-utils';
import { ScrollArea } from '@/components/ui/scroll-area';
-type EventWithOffset = { event: IServiceEvent; offsetMs: number };
+// After the user scrolls the feed by hand, leave it alone for a moment.
+const MANUAL_SCROLL_PAUSE_MS = 4000;
+const SKELETON_ROWS = Array.from({ length: 6 }, (_, index) => ({
+ id: `skeleton-${index}`,
+ width: 40 + ((index * 17) % 45),
+}));
+
+function getState(index: number, currentIndex: number): ReplayItemState {
+ if (index === currentIndex) {
+ return 'current';
+ }
+ return index < currentIndex ? 'past' : 'future';
+}
export function ReplayEventFeed({
events,
- replayLoading,
+ currentIndex,
+ isLoading,
}: {
- events: IServiceEvent[];
- replayLoading: boolean;
+ events: EventWithOffset[];
+ currentIndex: number;
+ isLoading: boolean;
}) {
- const { startTime, isReady, seek } = useReplayContext();
- const currentTime = useCurrentTime(100);
+ const { seek } = useReplayContext();
const viewportRef = useRef<HTMLDivElement | null>(null);
- const prevCountRef = useRef(0);
-
- // Pre-sort events by offset once when events/startTime changes.
- // This is the expensive part — done once, not on every tick.
- const sortedEvents = useMemo<EventWithOffset[]>(() => {
- if (startTime == null || !isReady) {
- return [];
- }
- return events
- .map((ev) => ({ event: ev, offsetMs: getEventOffsetMs(ev, startTime) }))
- .filter(({ offsetMs }) => offsetMs >= -10_000)
- .sort((a, b) => a.offsetMs - b.offsetMs);
- }, [events, startTime, isReady]);
-
- // Binary search to find how many events are visible at currentTime.
- // O(log n) instead of O(n) filter on every tick.
- const visibleCount = useMemo(() => {
- let lo = 0;
- let hi = sortedEvents.length;
- while (lo < hi) {
- const mid = (lo + hi) >>> 1;
- if ((sortedEvents[mid]?.offsetMs ?? 0) <= currentTime) {
- lo = mid + 1;
- } else {
- hi = mid;
- }
- }
- return lo;
- }, [sortedEvents, currentTime]);
-
- const visibleEvents = sortedEvents.slice(0, visibleCount);
- const currentEventId = visibleEvents[visibleCount - 1]?.event.id ?? null;
+ const lastManualScrollRef = useRef(0);
useEffect(() => {
const viewport = viewportRef.current;
- if (!viewport || visibleEvents.length === 0) {
+ const isUserScrolling =
+ performance.now() - lastManualScrollRef.current < MANUAL_SCROLL_PAUSE_MS;
+ if (!viewport || isUserScrolling) {
return;
}
-
- const isNewItem = visibleEvents.length > prevCountRef.current;
- prevCountRef.current = visibleEvents.length;
-
- requestAnimationFrame(() => {
- viewport.scrollTo({
- top: viewport.scrollHeight,
- behavior: isNewItem ? 'smooth' : 'instant',
- });
- });
- }, [visibleEvents.length]);
+ const current = viewport.querySelector<HTMLElement>(
+ '[data-replay-state="current"]'
+ );
+ if (!current) {
+ return;
+ }
+ const top =
+ current.offsetTop - viewport.clientHeight / 2 + current.clientHeight / 2;
+ viewport.scrollTo({ top, behavior: 'smooth' });
+ }, [currentIndex]);
return (
- <BrowserChrome
- className="h-full"
- controls={<span className="font-medium text-lg">Timeline</span>}
- url={false}
- >
- <ScrollArea className="min-h-0 flex-1" ref={viewportRef}>
- <div className="flex w-full flex-col">
- {visibleEvents.map(({ event, offsetMs }) => (
- <div
- className="fade-in-0 slide-in-from-bottom-3 min-w-0 animate-in fill-mode-both duration-300"
- key={event.id}
- >
+ <div className="col h-full min-h-0">
+ <div className="row items-center justify-between border-b px-4 py-3">
+ <span className="font-semibold">Activity</span>
+ <span className="font-mono text-muted-foreground text-xs tabular-nums">
+ {Math.max(0, currentIndex + 1)} / {events.length}
+ </span>
+ </div>
+ <ScrollArea
+ className="min-h-0 flex-1"
+ onWheel={() => {
+ lastManualScrollRef.current = performance.now();
+ }}
+ ref={viewportRef}
+ >
+ <div className="col py-1">
+ {isLoading &&
+ SKELETON_ROWS.map((row) => (
+ <div className="row items-center gap-2.5 px-3 py-2" key={row.id}>
+ <div className="size-6 shrink-0 animate-pulse rounded-full bg-def-200" />
+ <div
+ className="h-3 animate-pulse rounded bg-def-200"
+ style={{ width: `${row.width}%` }}
+ />
+ </div>
+ ))}
+ {!isLoading &&
+ events.map(({ event, offsetMs }, index) => (
<ReplayEventItem
event={event}
- isCurrent={event.id === currentEventId}
- onClick={() => seek(Math.max(0, offsetMs))}
+ key={event.id}
+ offsetMs={offsetMs}
+ onClick={() => seek(offsetMs)}
+ state={getState(index, currentIndex)}
/>
- </div>
- ))}
- {!replayLoading && visibleEvents.length === 0 && (
- <div className="py-8 text-center text-muted-foreground text-sm">
- Events will appear as the replay plays.
+ ))}
+ {!isLoading && events.length === 0 && (
+ <div className="py-10 text-center text-muted-foreground text-sm">
+ No events were tracked during this recording.
</div>
)}
- {replayLoading &&
- Array.from({ length: 5 }).map((_, i) => (
- <div
- className="flex items-center gap-2 border-b px-3 py-2"
- key={i}
- >
- <div className="h-6 w-6 shrink-0 animate-pulse rounded-full bg-muted" />
- <div className="flex-1 space-y-1.5">
- <div
- className="h-3 animate-pulse rounded bg-muted"
- style={{ width: `${50 + (i % 4) * 12}%` }}
- />
- </div>
- <div className="h-3 w-10 shrink-0 animate-pulse rounded bg-muted" />
- </div>
- ))}
</div>
</ScrollArea>
- </BrowserChrome>
+ </div>
);
}
diff --git a/apps/start/src/components/sessions/replay/replay-event-item.tsx b/apps/start/src/components/sessions/replay/replay-event-item.tsx
index cd23da7ef..a25312b33 100644
--- a/apps/start/src/components/sessions/replay/replay-event-item.tsx
+++ b/apps/start/src/components/sessions/replay/replay-event-item.tsx
@@ -1,51 +1,101 @@
import type { IServiceEvent } from '@openpanel/core';
+import { formatDuration, getEventLabel } from './replay-utils';
import { EventIcon } from '@/components/events/event-icon';
-import { cn } from '@/lib/utils';
+import { cn } from '@/utils/cn';
-function formatTime(date: Date | string): string {
- const d = date instanceof Date ? date : new Date(date);
- const h = d.getHours().toString().padStart(2, '0');
- const m = d.getMinutes().toString().padStart(2, '0');
- const s = d.getSeconds().toString().padStart(2, '0');
- return `${h}:${m}:${s}`;
+const MAX_PROPERTY_CHIPS = 2;
+const MAX_CHIP_VALUE_LENGTH = 24;
+
+export type ReplayItemState = 'past' | 'current' | 'future';
+
+function getPropertyChips(event: IServiceEvent): string[] {
+ return Object.entries(event.properties ?? {})
+ .filter(
+ ([key, value]) =>
+ !key.startsWith('__') &&
+ (typeof value === 'string' || typeof value === 'number')
+ )
+ .slice(0, MAX_PROPERTY_CHIPS)
+ .map(([key, value]) => {
+ const text = String(value);
+ const shortened =
+ text.length > MAX_CHIP_VALUE_LENGTH
+ ? `${text.slice(0, MAX_CHIP_VALUE_LENGTH)}…`
+ : text;
+ return `${key}: ${shortened}`;
+ });
}
export function ReplayEventItem({
event,
- isCurrent,
+ offsetMs,
+ state,
onClick,
}: {
event: IServiceEvent;
- isCurrent: boolean;
+ offsetMs: number;
+ state: ReplayItemState;
onClick: () => void;
}) {
- const displayName =
- event.name === 'screen_view' && event.path
- ? event.path
- : event.name.replace(/_/g, ' ');
+ const isPageView = event.name === 'screen_view';
+ const chips = isPageView ? [] : getPropertyChips(event);
return (
<button
className={cn(
- 'col w-full gap-3 border-b px-3 py-2 text-left transition-colors hover:bg-accent',
- isCurrent ? 'bg-accent/10' : 'bg-card'
+ 'group row relative w-full items-start gap-2.5 py-1.5 pr-3 text-left transition-all duration-300',
+ isPageView ? 'pl-3' : 'pl-7',
+ state === 'future' && 'opacity-35 hover:opacity-80',
+ state === 'current' && 'bg-highlight/[0.07]'
)}
+ data-replay-state={state}
onClick={onClick}
type="button"
>
- <div className="row items-center gap-2">
- <div className="flex-shrink-0">
- <EventIcon meta={event.meta} name={event.name} size="sm" />
- </div>
- <div className="min-w-0 flex-1">
- <div className="truncate font-medium text-foreground">
- {displayName}
- </div>
- </div>
- <span className="flex-shrink-0 text-muted-foreground text-xs tabular-nums">
- {formatTime(event.createdAt)}
+ <span
+ className={cn(
+ 'absolute inset-y-0 left-0 w-0.5 rounded-r bg-highlight transition-opacity',
+ state === 'current' ? 'opacity-100' : 'opacity-0'
+ )}
+ />
+ <EventIcon
+ className="mt-px"
+ meta={event.meta}
+ name={event.name}
+ size={isPageView ? 'sm' : 'xs'}
+ />
+ <span className="col min-w-0 flex-1 gap-1">
+ <span
+ className={cn(
+ 'truncate group-hover:text-foreground',
+ isPageView ? 'font-semibold text-sm' : 'text-foreground/80 text-sm',
+ isPageView && 'leading-6'
+ )}
+ >
+ {getEventLabel(event)}
</span>
- </div>
+ {chips.length > 0 && (
+ <span className="row flex-wrap gap-1">
+ {chips.map((chip) => (
+ <span
+ className="max-w-full truncate rounded bg-def-200 px-1.5 py-px font-mono text-2xs text-muted-foreground"
+ key={chip}
+ >
+ {chip}
+ </span>
+ ))}
+ </span>
+ )}
+ </span>
+ <span
+ className={cn(
+ 'shrink-0 font-mono text-2xs tabular-nums',
+ isPageView ? 'leading-6' : 'leading-5',
+ state === 'current' ? 'text-highlight' : 'text-muted-foreground'
+ )}
+ >
+ {formatDuration(Math.max(0, offsetMs))}
+ </span>
</button>
);
}
diff --git a/apps/start/src/components/sessions/replay/replay-player.tsx b/apps/start/src/components/sessions/replay/replay-player.tsx
index 056da91aa..d25405528 100644
--- a/apps/start/src/components/sessions/replay/replay-player.tsx
+++ b/apps/start/src/components/sessions/replay/replay-player.tsx
@@ -1,44 +1,149 @@
-import { useEffect, useMemo, useRef, useState } from 'react';
-import type { ReplayPlayerInstance } from '@/components/sessions/replay/replay-context';
-import { useReplayContext } from '@/components/sessions/replay/replay-context';
+import { LockIcon } from 'lucide-react';
+import {
+ type ReactNode,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import {
+ DEFAULT_SKIP_INACTIVE,
+ type ReplayPlayerInstance,
+ SPEED_OPTIONS,
+ useReplayContext,
+} from './replay-context';
+import { getRecordedDimensions, type ReplayRecordEvent } from './replay-utils';
+import { cn } from '@/utils/cn';
import 'rrweb-player/dist/style.css';
-/** rrweb meta event (type 4) carries the recorded viewport size */
-function getRecordedDimensions(
- events: Array<{ type: number; data: unknown }>
-): { width: number; height: number } | null {
- const meta = events.find((e) => e.type === 4);
- if (
- meta &&
- typeof meta.data === 'object' &&
- meta.data !== null &&
- 'width' in meta.data &&
- 'height' in meta.data
- ) {
- const { width, height } = meta.data as { width: number; height: number };
- if (width > 0 && height > 0) {
- return { width, height };
- }
+const FALLBACK_ASPECT_RATIO = 16 / 9;
+const STAGE_PADDING = 24;
+const BROWSER_BAR_HEIGHT = 36;
+const PHONE_BEZEL = 10;
+const PHONE_URL_HEIGHT = 36;
+const MOUSE_TAIL = {
+ duration: 600,
+ lineCap: 'round',
+ lineWidth: 3,
+ strokeStyle: 'rgba(34, 102, 236, 0.45)',
+};
+
+type FrameKind = 'browser' | 'phone';
+
+interface Size {
+ width: number;
+ height: number;
+}
+
+function fitViewport(area: Size, aspectRatio: number, kind: FrameKind): Size {
+ const chromeWidth = kind === 'phone' ? PHONE_BEZEL * 2 : 0;
+ const chromeHeight =
+ kind === 'phone' ? PHONE_BEZEL * 2 + PHONE_URL_HEIGHT : BROWSER_BAR_HEIGHT;
+ const maxWidth = Math.max(0, area.width - STAGE_PADDING * 2 - chromeWidth);
+ const maxHeight = Math.max(0, area.height - STAGE_PADDING * 2 - chromeHeight);
+ const height = Math.min(maxHeight, maxWidth / aspectRatio);
+ return {
+ width: Math.round(height * aspectRatio),
+ height: Math.round(height),
+ };
+}
+
+/**
+ * Height a stage needs to show a wide recording edge to edge, as CSS against
+ * the stage's container width; tall recordings are bounded by the stage's max.
+ */
+export function getStageFitHeight(events: ReplayRecordEvent[]): string {
+ const recorded = getRecordedDimensions(events);
+ const aspectRatio = recorded
+ ? recorded.width / recorded.height
+ : FALLBACK_ASPECT_RATIO;
+ if (aspectRatio < 1) {
+ return '100vh';
}
- return null;
+ const verticalChrome = STAGE_PADDING * 2 + BROWSER_BAR_HEIGHT;
+ return `calc((100cqw - ${STAGE_PADDING * 2}px) / ${aspectRatio.toFixed(4)} + ${verticalChrome}px)`;
+}
+
+function BrowserFrame({
+ url,
+ viewport,
+ children,
+ width,
+}: {
+ url: ReactNode;
+ viewport: string | null;
+ children: ReactNode;
+ width: number;
+}) {
+ return (
+ <div
+ className="overflow-hidden rounded-xl bg-card shadow-[0_30px_80px_-20px_rgb(0_0_0/0.35),0_0_0_1px_var(--border)]"
+ style={{ width }}
+ >
+ <div
+ className="row items-center gap-3 border-b bg-def-100 px-3"
+ style={{ height: BROWSER_BAR_HEIGHT }}
+ >
+ <div className="row shrink-0 gap-1.5">
+ <span className="size-2.5 rounded-full bg-[#ff5f57]" />
+ <span className="size-2.5 rounded-full bg-[#febc2e]" />
+ <span className="size-2.5 rounded-full bg-[#28c840]" />
+ </div>
+ <div className="row h-6 min-w-0 flex-1 items-center gap-1.5 rounded-md bg-card px-2.5 text-xs shadow-[0_0_0_1px_var(--border)]">
+ <LockIcon className="size-3 shrink-0 text-muted-foreground" />
+ {url}
+ </div>
+ {viewport && (
+ <span className="hidden shrink-0 font-mono text-2xs text-muted-foreground sm:block">
+ {viewport}
+ </span>
+ )}
+ </div>
+ {children}
+ </div>
+ );
}
-function calcDimensions(
- containerWidth: number,
- aspectRatio: number
-): { width: number; height: number } {
- const maxHeight = window.innerHeight * 0.7;
- const height = Math.min(Math.round(containerWidth / aspectRatio), maxHeight);
- const width = Math.min(containerWidth, Math.round(height * aspectRatio));
- return { width, height };
+function PhoneFrame({
+ url,
+ children,
+}: {
+ url: ReactNode;
+ children: ReactNode;
+}) {
+ return (
+ <div className="col items-center">
+ <div
+ className="row max-w-full items-center gap-1.5 self-stretch px-2"
+ style={{ height: PHONE_URL_HEIGHT }}
+ >
+ <div className="row mx-auto h-6 min-w-0 max-w-full items-center gap-1.5 rounded-full bg-card px-3 text-xs shadow-[0_0_0_1px_var(--border)]">
+ <LockIcon className="size-3 shrink-0 text-muted-foreground" />
+ {url}
+ </div>
+ </div>
+ <div
+ className="rounded-[44px] bg-neutral-900 shadow-[0_30px_80px_-20px_rgb(0_0_0/0.45),inset_0_0_0_1px_rgb(255_255_255/0.08)] ring-1 ring-black/40"
+ style={{ padding: PHONE_BEZEL }}
+ >
+ <div className="overflow-hidden rounded-[34px] bg-card">{children}</div>
+ </div>
+ </div>
+ );
}
export function ReplayPlayer({
events,
+ url,
+ overlay,
}: {
- events: Array<{ type: number; data: unknown; timestamp: number }>;
+ events: ReplayRecordEvent[];
+ url: ReactNode;
+ overlay?: ReactNode;
}) {
+ const areaRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const playerRef = useRef<ReplayPlayerInstance | null>(null);
const {
@@ -46,78 +151,84 @@ export function ReplayPlayer({
onPlayerDestroy,
setCurrentTime,
setIsPlaying,
- setDuration,
+ setIsSkipping,
} = useReplayContext();
const [importError, setImportError] = useState(false);
+ const [size, setSize] = useState<Size | null>(null);
+ const sizeRef = useRef<Size | null>(null);
- const recordedDimensions = useMemo(
- () => getRecordedDimensions(events),
- [events]
- );
+ const recorded = useMemo(() => getRecordedDimensions(events), [events]);
+ const aspectRatio = recorded
+ ? recorded.width / recorded.height
+ : FALLBACK_ASPECT_RATIO;
+ const frameKind: FrameKind = aspectRatio < 1 ? 'phone' : 'browser';
- useEffect(() => {
- if (!(events.length && containerRef.current)) {
+ useLayoutEffect(() => {
+ const area = areaRef.current;
+ if (!area) {
return;
}
+ const measure = () => {
+ const next = fitViewport(
+ { width: area.clientWidth, height: area.clientHeight },
+ aspectRatio,
+ frameKind
+ );
+ sizeRef.current = next;
+ setSize(next);
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(area);
+ return () => observer.disconnect();
+ }, [aspectRatio, frameKind]);
- // Clear any previous player DOM
- containerRef.current.innerHTML = '';
+ const hasSize = size !== null && size.width > 0;
+ useEffect(() => {
+ const container = containerRef.current;
+ const initialSize = sizeRef.current;
+ if (!(events.length && container && hasSize && initialSize)) {
+ return;
+ }
+
+ container.innerHTML = '';
let mounted = true;
let player: ReplayPlayerInstance | null = null;
let handleVisibilityChange: (() => void) | null = null;
- const aspectRatio = recordedDimensions
- ? recordedDimensions.width / recordedDimensions.height
- : 16 / 9;
-
- const { width, height } = calcDimensions(
- containerRef.current.offsetWidth,
- aspectRatio
- );
-
import('rrweb-player')
.then((module) => {
- if (!(containerRef.current && mounted)) {
+ if (!mounted) {
return;
}
-
- const PlayerConstructor = module.default;
- player = new PlayerConstructor({
- target: containerRef.current,
+ player = new module.default({
+ target: container,
props: {
events,
- width,
- height,
+ width: initialSize.width,
+ height: initialSize.height,
autoPlay: false,
showController: false,
- speedOption: [0.5, 1, 2, 4, 8],
- skipInactive: false,
+ speedOption: [...SPEED_OPTIONS],
+ skipInactive: DEFAULT_SKIP_INACTIVE,
+ mouseTail: MOUSE_TAIL,
},
- }) as ReplayPlayerInstance;
-
+ }) as unknown as ReplayPlayerInstance;
playerRef.current = player;
- // Track play state from replayer (getMetaData() does not expose isPlaying)
let playingState = false;
-
- // Wire rrweb's built-in event emitter — no RAF loop needed.
- // Note: rrweb-player does NOT emit ui-update-duration; duration is
- // read from getMetaData() on init and after each addEvent batch.
player.addEventListener('ui-update-current-time', (e) => {
- const t = e.payload as number;
- setCurrentTime(t);
+ setCurrentTime(e.payload as number);
});
-
player.addEventListener('ui-update-player-state', (e) => {
- const playing = e.payload === 'playing';
- playingState = playing;
- setIsPlaying(playing);
+ playingState = e.payload === 'playing';
+ setIsPlaying(playingState);
});
+ player.addEventListener('skip-start', () => setIsSkipping(true));
+ player.addEventListener('skip-end', () => setIsSkipping(false));
- // Pause on tab hide; resume on show (prevents timer drift).
- // getMetaData() does not expose isPlaying, so we use playingState
- // kept in sync by ui-update-player-state above.
+ // Pause while the tab is hidden so the replay clock does not drift.
let wasPlaying = false;
handleVisibilityChange = () => {
if (!player) {
@@ -135,12 +246,7 @@ export function ReplayPlayer({
};
document.addEventListener('visibilitychange', handleVisibilityChange);
- // Notify context — marks isReady = true and sets initial duration
- const meta = player.getMetaData();
- if (meta.totalTime > 0) {
- setDuration(meta.totalTime);
- }
- onPlayerReady(player, meta.startTime);
+ onPlayerReady(player, events);
})
.catch(() => {
if (mounted) {
@@ -148,61 +254,76 @@ export function ReplayPlayer({
}
});
- const onWindowResize = () => {
- if (!(containerRef.current && mounted && playerRef.current?.$set)) {
- return;
- }
- const { width: w, height: h } = calcDimensions(
- containerRef.current.offsetWidth,
- aspectRatio
- );
- playerRef.current.$set({ width: w, height: h });
- };
- window.addEventListener('resize', onWindowResize);
-
return () => {
mounted = false;
- window.removeEventListener('resize', onWindowResize);
if (handleVisibilityChange) {
document.removeEventListener(
'visibilitychange',
handleVisibilityChange
);
}
- if (player) {
- player.pause();
- }
- if (containerRef.current) {
- containerRef.current.innerHTML = '';
- }
+ player?.pause();
+ container.innerHTML = '';
playerRef.current = null;
onPlayerDestroy();
};
}, [
events,
- recordedDimensions,
+ hasSize,
onPlayerReady,
onPlayerDestroy,
setCurrentTime,
setIsPlaying,
- setDuration,
+ setIsSkipping,
]);
+ useEffect(() => {
+ if (!(size && playerRef.current?.$set)) {
+ return;
+ }
+ playerRef.current.$set({ width: size.width, height: size.height });
+ playerRef.current.triggerResize();
+ }, [size]);
+
if (importError) {
return (
- <div className="flex h-[320px] items-center justify-center bg-black text-muted-foreground text-sm">
+ <div className="flex h-full items-center justify-center text-muted-foreground text-sm">
Failed to load replay player.
</div>
);
}
+ const viewport = (
+ <div
+ className={cn(
+ 'relative overflow-hidden bg-card',
+ '[&_.rr-player]:!float-none [&_.rr-player]:!rounded-none [&_.rr-player]:!bg-transparent [&_.rr-player]:!shadow-none',
+ '[&_.replayer-mouse]:after:!bg-highlight [&_.replayer-mouse]:after:!opacity-50'
+ )}
+ style={size ?? undefined}
+ >
+ <div ref={containerRef} />
+ {overlay}
+ </div>
+ );
+
+ const viewportLabel = recorded
+ ? `${recorded.width} × ${recorded.height}`
+ : null;
+
return (
- <div className="relative flex w-full justify-center overflow-hidden">
- <div
- className="w-full"
- ref={containerRef}
- style={{ maxHeight: '70vh' }}
- />
+ <div
+ className="absolute inset-0 flex items-center justify-center"
+ ref={areaRef}
+ >
+ {hasSize &&
+ (frameKind === 'phone' ? (
+ <PhoneFrame url={url}>{viewport}</PhoneFrame>
+ ) : (
+ <BrowserFrame url={url} viewport={viewportLabel} width={size.width}>
+ {viewport}
+ </BrowserFrame>
+ ))}
</div>
);
}
diff --git a/apps/start/src/components/sessions/replay/replay-timeline.tsx b/apps/start/src/components/sessions/replay/replay-timeline.tsx
index 3e84a96f5..6132f8637 100644
--- a/apps/start/src/components/sessions/replay/replay-timeline.tsx
+++ b/apps/start/src/components/sessions/replay/replay-timeline.tsx
@@ -1,21 +1,213 @@
-import type { IServiceEvent } from '@openpanel/core';
-import { AnimatePresence, motion } from 'framer-motion';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { ReplayPlayPauseButton } from './replay-controls';
-import { formatDuration, getEventOffsetMs } from './replay-utils';
-import { EventIcon } from '@/components/events/event-icon';
+import { useReplayContext } from './replay-context';
import {
- useCurrentTime,
- useReplayContext,
-} from '@/components/sessions/replay/replay-context';
+ detectRageClicks,
+ type EventWithOffset,
+ formatDuration,
+ getActivityHistogram,
+ getEventLabel,
+ type PageSegment,
+} from './replay-utils';
+import { EventIcon } from '@/components/events/event-icon';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip';
+import { cn } from '@/utils/cn';
+
+const HISTOGRAM_BUCKETS = 140;
+const MARKER_GROUP_PX = 22;
+const MIN_LABEL_WIDTH_PX = 48;
+const FALLBACK_TRACK_WIDTH = 600;
+const MIN_BAR_HEIGHT = 0.08;
+
+function percent(timeMs: number, duration: number): number {
+ return Math.max(0, Math.min(100, (timeMs / duration) * 100));
+}
-export function ReplayTimeline({ events }: { events: IServiceEvent[] }) {
+function groupMarkers(
+ events: EventWithOffset[],
+ duration: number,
+ trackWidth: number
+) {
+ const thresholdMs = (MARKER_GROUP_PX / trackWidth) * duration;
+ const groups: EventWithOffset[][] = [];
+ for (const item of events) {
+ const last = groups.at(-1);
+ // Measured from the group's first event, which is where its marker sits.
+ const anchor = last?.[0];
+ if (last && anchor && item.offsetMs - anchor.offsetMs <= thresholdMs) {
+ last.push(item);
+ } else {
+ groups.push([item]);
+ }
+ }
+ return groups;
+}
+
+function useElementWidth(ref: React.RefObject<HTMLElement | null>) {
+ const [width, setWidth] = useState(FALLBACK_TRACK_WIDTH);
+ useEffect(() => {
+ const element = ref.current;
+ if (!element) {
+ return;
+ }
+ const observer = new ResizeObserver(() => {
+ setWidth(element.clientWidth || FALLBACK_TRACK_WIDTH);
+ });
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [ref]);
+ return width;
+}
+
+function EventMarkers({
+ events,
+ duration,
+ trackWidth,
+}: {
+ events: EventWithOffset[];
+ duration: number;
+ trackWidth: number;
+}) {
+ const { seek } = useReplayContext();
+ // Screen views already have their own band; markers are for what happened on a page.
+ const markers = useMemo(
+ () =>
+ groupMarkers(
+ events.filter(
+ ({ event, offsetMs }) =>
+ event.name !== 'screen_view' &&
+ offsetMs >= 0 &&
+ offsetMs <= duration
+ ),
+ duration,
+ trackWidth
+ ),
+ [events, duration, trackWidth]
+ );
+
+ return (
+ <div className="relative h-6">
+ {markers.map((group) => {
+ const first = group[0]!;
+ return (
+ <Tooltip key={first.event.id}>
+ <TooltipTrigger asChild>
+ <button
+ aria-label={`${getEventLabel(first.event)} at ${formatDuration(first.offsetMs)}`}
+ className="absolute top-0 -ml-2.5 transition-transform hover:z-10 hover:scale-125"
+ onClick={() => seek(first.offsetMs)}
+ style={{ left: `${percent(first.offsetMs, duration)}%` }}
+ type="button"
+ >
+ <EventIcon
+ className="ring-2 ring-card"
+ meta={first.event.meta}
+ name={first.event.name}
+ size="xs"
+ />
+ {group.length > 1 && (
+ <span className="absolute -top-1.5 -right-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-foreground px-0.5 font-semibold text-[9px] text-background tabular-nums">
+ {group.length}
+ </span>
+ )}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent className="col gap-1.5" side="top">
+ {group.map(({ event, offsetMs }) => (
+ <div className="row items-center gap-2" key={event.id}>
+ <EventIcon meta={event.meta} name={event.name} size="xs" />
+ <span className="font-medium">{getEventLabel(event)}</span>
+ <span className="ml-auto pl-3 text-muted-foreground tabular-nums">
+ {formatDuration(offsetMs)}
+ </span>
+ </div>
+ ))}
+ </TooltipContent>
+ </Tooltip>
+ );
+ })}
+ </div>
+ );
+}
+
+function PageBands({
+ segments,
+ duration,
+ trackWidth,
+ currentSegmentId,
+}: {
+ segments: PageSegment[];
+ duration: number;
+ trackWidth: number;
+ currentSegmentId: string | null;
+}) {
+ const { seek } = useReplayContext();
+ return (
+ <div className="relative mt-1.5 h-6">
+ {segments.map((segment) => {
+ const left = percent(segment.startMs, duration);
+ const width = percent(segment.endMs, duration) - left;
+ const isCurrent = segment.id === currentSegmentId;
+ const showLabel = (width / 100) * trackWidth >= MIN_LABEL_WIDTH_PX;
+ return (
+ <Tooltip key={segment.id}>
+ <TooltipTrigger asChild>
+ <button
+ aria-label={`Jump to ${segment.path}`}
+ className={cn(
+ 'absolute inset-y-0 truncate rounded-[5px] border-card border-r-2 px-1.5 text-left font-medium text-2xs transition-colors',
+ isCurrent
+ ? 'bg-highlight/15 text-highlight'
+ : 'bg-def-200 text-muted-foreground hover:bg-def-300 hover:text-foreground'
+ )}
+ onClick={() => seek(segment.startMs)}
+ style={{ left: `${left}%`, width: `${width}%` }}
+ type="button"
+ >
+ {showLabel ? segment.path : null}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ <span className="font-medium">{segment.path}</span>
+ <span className="ml-2 text-muted-foreground tabular-nums">
+ {formatDuration(segment.endMs - segment.startMs)}
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ );
+ })}
+ </div>
+ );
+}
+
+function Waveform({ bars, className }: { bars: number[]; className: string }) {
+ return (
+ <div className="absolute inset-0 flex items-end gap-px">
+ {bars.map((value, index) => (
+ <div
+ className={cn('flex-1 rounded-t-[1px]', className)}
+ // biome-ignore lint/suspicious/noArrayIndexKey: buckets are positional
+ key={index}
+ style={{ height: `${Math.max(MIN_BAR_HEIGHT, value) * 100}%` }}
+ />
+ ))}
+ </div>
+ );
+}
+
+export function ReplayTimeline({
+ events,
+ segments,
+ currentSegmentId,
+}: {
+ events: EventWithOffset[];
+ segments: PageSegment[];
+ currentSegmentId: string | null;
+}) {
const {
currentTimeRef,
duration,
@@ -23,276 +215,203 @@ export function ReplayTimeline({ events }: { events: IServiceEvent[] }) {
isReady,
seek,
subscribeToCurrentTime,
+ activity,
} = useReplayContext();
- // currentTime as React state is only needed for keyboard seeks (low frequency).
- // The progress bar and thumb are updated directly via DOM refs to avoid re-renders.
- const currentTime = useCurrentTime(250);
const trackRef = useRef<HTMLDivElement>(null);
- const progressBarRef = useRef<HTMLDivElement>(null);
- const thumbRef = useRef<HTMLDivElement>(null);
- const [isDragging, setIsDragging] = useState(false);
- const [hoverInfo, setHoverInfo] = useState<{
- pct: number;
- timeMs: number;
- } | null>(null);
- const dragCleanupRef = useRef<(() => void) | null>(null);
- const rafDragRef = useRef<number | null>(null);
+ const scrubPointerRef = useRef<number | null>(null);
+ const playedRef = useRef<HTMLDivElement>(null);
+ const playheadRef = useRef<HTMLDivElement>(null);
+ const [hover, setHover] = useState<{ pct: number; timeMs: number } | null>(
+ null
+ );
+ const trackWidth = useElementWidth(trackRef);
- // Clean up any in-progress drag listeners when the component unmounts
- useEffect(() => {
- return () => {
- dragCleanupRef.current?.();
- };
- }, []);
+ const bars = useMemo(
+ () =>
+ startTime == null
+ ? []
+ : getActivityHistogram(
+ activity.interactions,
+ startTime,
+ duration,
+ HISTOGRAM_BUCKETS
+ ),
+ [activity.interactions, startTime, duration]
+ );
- // Update progress bar and thumb directly via DOM on every tick — no React re-render.
+ const rageClicks = useMemo(
+ () =>
+ startTime == null
+ ? []
+ : detectRageClicks(activity.clicks, startTime).filter(
+ (rage) => rage.offsetMs >= 0 && rage.offsetMs <= duration
+ ),
+ [activity.clicks, startTime, duration]
+ );
+
+ // The playhead moves on every tick; write to the DOM instead of re-rendering.
useEffect(() => {
if (duration <= 0) {
return;
}
- return subscribeToCurrentTime((t) => {
- const pct = Math.max(0, Math.min(100, (t / duration) * 100));
- if (progressBarRef.current) {
- progressBarRef.current.style.width = `${pct}%`;
+ const paint = (t: number) => {
+ const pct = `${percent(t, duration)}%`;
+ if (playedRef.current) {
+ playedRef.current.style.clipPath = `inset(0 calc(100% - ${pct}) 0 0)`;
}
- if (thumbRef.current) {
- thumbRef.current.style.left = `calc(${pct}% - 8px)`;
+ if (playheadRef.current) {
+ playheadRef.current.style.left = pct;
}
- });
- }, [subscribeToCurrentTime, duration]);
+ };
+ paint(currentTimeRef.current);
+ return subscribeToCurrentTime(paint);
+ }, [subscribeToCurrentTime, duration, currentTimeRef]);
const getTimeFromClientX = useCallback(
(clientX: number) => {
- if (!trackRef.current || duration <= 0) {
- return null;
- }
- const rect = trackRef.current.getBoundingClientRect();
- if (rect.width <= 0 || !Number.isFinite(rect.width)) {
+ const rect = trackRef.current?.getBoundingClientRect();
+ if (!rect || rect.width <= 0 || duration <= 0) {
return null;
}
- const x = clientX - rect.left;
- const pct = Math.max(0, Math.min(1, x / rect.width));
+ const pct = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
return { pct, timeMs: pct * duration };
},
[duration]
);
- const handleTrackMouseMove = useCallback(
- (e: React.MouseEvent<HTMLDivElement>) => {
- if ((e.target as HTMLElement).closest('[data-timeline-event]')) {
- setHoverInfo(null);
- return;
- }
- const info = getTimeFromClientX(e.clientX);
- if (info) {
- setHoverInfo(info);
- }
- },
- [getTimeFromClientX]
- );
-
- const handleTrackMouseLeave = useCallback(() => {
- if (!isDragging) {
- setHoverInfo(null);
- }
- }, [isDragging]);
-
- const handleTrackMouseDown = useCallback(
- (e: React.MouseEvent<HTMLDivElement>) => {
- // Only handle direct clicks on the track, not on child elements like the thumb
- if (
- e.target !== trackRef.current &&
- !(e.target as HTMLElement).closest('.replay-track-bg')
- ) {
+ const startScrub = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ // A pen and a finger can both be primary; only one scrub at a time.
+ if (!e.isPrimary || scrubPointerRef.current !== null) {
return;
}
- const info = getTimeFromClientX(e.clientX);
- if (info) {
- seek(info.timeMs);
+ const first = getTimeFromClientX(e.clientX);
+ if (first) {
+ seek(first.timeMs);
}
+ const { pointerId } = e;
+ scrubPointerRef.current = pointerId;
+ const onMove = (move: PointerEvent) => {
+ if (move.pointerId !== pointerId) {
+ return;
+ }
+ const info = getTimeFromClientX(move.clientX);
+ if (info) {
+ setHover(info);
+ seek(info.timeMs);
+ }
+ };
+ const onEnd = (end: PointerEvent) => {
+ if (end.pointerId !== pointerId) {
+ return;
+ }
+ scrubPointerRef.current = null;
+ window.removeEventListener('pointermove', onMove);
+ window.removeEventListener('pointerup', onEnd);
+ window.removeEventListener('pointercancel', onEnd);
+ };
+ window.addEventListener('pointermove', onMove);
+ window.addEventListener('pointerup', onEnd);
+ window.addEventListener('pointercancel', onEnd);
},
[getTimeFromClientX, seek]
);
- const eventsWithOffset = useMemo(
- () =>
- events
- .map((ev) => ({
- event: ev,
- offsetMs: startTime != null ? getEventOffsetMs(ev, startTime) : 0,
- }))
- .filter(({ offsetMs }) => offsetMs >= 0 && offsetMs <= duration),
- [events, startTime, duration]
- );
-
- // Group events that are within 24px of each other on the track.
- // We need the track width for pixel math — use a stable ref-based calculation.
- const groupedEvents = useMemo(() => {
- if (!eventsWithOffset.length || duration <= 0) {
- return [];
- }
-
- // Sort by offsetMs so we sweep left-to-right
- const sorted = [...eventsWithOffset].sort(
- (a, b) => a.offsetMs - b.offsetMs
- );
-
- // 24px in ms — recalculated from container width; fall back to 2% of duration
- const trackWidth = trackRef.current?.offsetWidth ?? 600;
- const thresholdMs = (24 / trackWidth) * duration;
-
- const groups: { items: typeof sorted; pct: number }[] = [];
- for (const item of sorted) {
- const last = groups[groups.length - 1];
- const lastPct = last
- ? (last.items[last.items.length - 1]!.offsetMs / duration) * 100
- : Number.NEGATIVE_INFINITY;
- const thisPct = (item.offsetMs / duration) * 100;
-
- if (
- last &&
- item.offsetMs - last.items[last.items.length - 1]!.offsetMs <=
- thresholdMs
- ) {
- last.items.push(item);
- // Anchor the group at its first item's position
- } else {
- groups.push({ items: [item], pct: thisPct });
- }
- // keep pct pointing at the first item (already set on push)
- void lastPct;
- }
-
- return groups;
- }, [eventsWithOffset, duration]);
-
if (!isReady || duration <= 0) {
- return null;
+ return <div className="h-[86px]" />;
}
- const progressPct = Math.max(
- 0,
- Math.min(100, (currentTimeRef.current / duration) * 100)
- );
+ const hoverSegment = hover
+ ? segments.find(
+ (segment) =>
+ hover.timeMs >= segment.startMs && hover.timeMs < segment.endMs
+ )
+ : undefined;
return (
- <TooltipProvider delayDuration={300}>
- <div className="row items-center gap-4 p-4">
- <ReplayPlayPauseButton />
- <div className="col flex-1 gap-4 px-2">
+ <TooltipProvider delayDuration={150}>
+ <div className="relative select-none">
+ <EventMarkers
+ duration={duration}
+ events={events}
+ trackWidth={trackWidth}
+ />
+ <div
+ aria-label="Seek"
+ aria-valuemax={Math.round(duration / 1000)}
+ aria-valuemin={0}
+ aria-valuenow={Math.round(currentTimeRef.current / 1000)}
+ className="relative h-10 cursor-pointer touch-none"
+ onKeyDown={(e) => {
+ const step = 5000;
+ if (e.key === 'ArrowLeft') {
+ e.preventDefault();
+ seek(currentTimeRef.current - step);
+ } else if (e.key === 'ArrowRight') {
+ e.preventDefault();
+ seek(Math.min(duration, currentTimeRef.current + step));
+ }
+ }}
+ onPointerDown={startScrub}
+ onPointerLeave={() => setHover(null)}
+ onPointerMove={(e) => setHover(getTimeFromClientX(e.clientX))}
+ ref={trackRef}
+ role="slider"
+ tabIndex={0}
+ >
+ <Waveform bars={bars} className="bg-def-300" />
+ <div className="absolute inset-0" ref={playedRef}>
+ <Waveform bars={bars} className="bg-highlight" />
+ </div>
+
+ {rageClicks.map((rage) => (
+ <Tooltip key={rage.offsetMs}>
+ <TooltipTrigger asChild>
+ <div
+ className="absolute -top-1 bottom-0 z-10 w-0.5 -translate-x-1/2 rounded-full bg-destructive"
+ style={{ left: `${percent(rage.offsetMs, duration)}%` }}
+ >
+ <span className="absolute -top-1 left-1/2 size-2 -translate-x-1/2 animate-pulse rounded-full bg-destructive ring-2 ring-card" />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="top">
+ <span className="font-medium text-destructive">Rage click</span>
+ <span className="ml-2 text-muted-foreground">
+ {rage.clicks} clicks at {formatDuration(rage.offsetMs)}
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ ))}
+
+ {hover && (
+ <div
+ className="pointer-events-none absolute inset-y-0 z-20 w-px bg-foreground/40"
+ style={{ left: `${hover.pct * 100}%` }}
+ >
+ <div className="absolute bottom-full left-1/2 mb-8 -translate-x-1/2 whitespace-nowrap rounded-md bg-foreground px-2 py-1 text-2xs text-background shadow-lg">
+ <span className="font-semibold tabular-nums">
+ {formatDuration(hover.timeMs)}
+ </span>
+ {hoverSegment && (
+ <span className="ml-1.5 opacity-70">{hoverSegment.path}</span>
+ )}
+ </div>
+ </div>
+ )}
+
<div
- aria-valuemax={duration}
- aria-valuemin={0}
- aria-valuenow={currentTime}
- className="relative flex h-8 cursor-pointer items-center outline-0"
- onKeyDown={(e) => {
- const step = 5000;
- if (e.key === 'ArrowLeft') {
- e.preventDefault();
- seek(Math.max(0, currentTime - step));
- } else if (e.key === 'ArrowRight') {
- e.preventDefault();
- seek(Math.min(duration, currentTime + step));
- }
- }}
- onMouseDown={handleTrackMouseDown}
- onMouseLeave={handleTrackMouseLeave}
- onMouseMove={handleTrackMouseMove}
- ref={trackRef}
- role="slider"
- tabIndex={0}
+ className="pointer-events-none absolute -top-1 -bottom-1 z-30 w-0.5 -translate-x-1/2 rounded-full bg-foreground"
+ ref={playheadRef}
>
- <div className="replay-track-bg h-1.5 w-full overflow-hidden rounded-full bg-muted">
- <div
- className="h-full rounded-full bg-primary"
- ref={progressBarRef}
- style={{ width: `${progressPct}%` }}
- />
- </div>
- <div
- aria-hidden
- className="absolute top-1/2 left-0 z-10 h-4 w-4 -translate-y-1/2 rounded-full border-2 border-primary bg-background shadow-sm"
- ref={thumbRef}
- style={{ left: `calc(${progressPct}% - 8px)` }}
- />
- <AnimatePresence>
- {hoverInfo && (
- <motion.div
- animate={{ opacity: 1 }}
- className="pointer-events-none absolute z-20"
- exit={{ opacity: 0 }}
- initial={{ opacity: 0 }}
- style={{
- left: `${hoverInfo.pct * 100}%`,
- top: 0,
- bottom: 0,
- }}
- transition={{ duration: 0.15 }}
- >
- <div className="absolute top-1/2 left-0 h-4 w-px -translate-x-1/2 -translate-y-1/2 bg-foreground/30" />
- <motion.div
- animate={{ opacity: 1, y: 0, scale: 1 }}
- className="absolute bottom-6 left-1/2 mb-1.5 -translate-x-1/2 whitespace-nowrap rounded bg-foreground px-1.5 py-0.5 text-2xs text-background tabular-nums shadow"
- exit={{ opacity: 0, y: 16, scale: 0.5 }}
- initial={{ opacity: 0, y: 16, scale: 0.5 }}
- transition={{ duration: 0.2 }}
- >
- {formatDuration(hoverInfo.timeMs)}
- </motion.div>
- </motion.div>
- )}
- </AnimatePresence>
- {groupedEvents.map((group) => {
- const first = group.items[0]!;
- const isGroup = group.items.length > 1;
- return (
- <Tooltip key={first.event.id}>
- <TooltipTrigger asChild>
- <button
- aria-label={
- isGroup
- ? `${group.items.length} events at ${formatDuration(first.offsetMs)}`
- : `${first.event.name} at ${formatDuration(first.offsetMs)}`
- }
- className="absolute top-1/2 z-[5] flex h-6 w-6 -translate-y-1/2 items-center justify-center transition-transform hover:scale-105"
- data-timeline-event
- onClick={(e) => {
- e.stopPropagation();
- seek(first.offsetMs);
- }}
- style={{ left: `${group.pct}%`, marginLeft: -12 }}
- type="button"
- >
- <EventIcon
- meta={first.event.meta}
- name={first.event.name}
- size="sm"
- />
- {isGroup && (
- <span className="absolute -top-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-foreground font-bold text-[9px] text-background leading-none">
- {group.items.length}
- </span>
- )}
- </button>
- </TooltipTrigger>
- <TooltipContent className="col gap-1.5" side="top">
- {group.items.map(({ event: ev, offsetMs }) => (
- <div className="row items-center gap-2" key={ev.id}>
- <EventIcon meta={ev.meta} name={ev.name} size="sm" />
- <span className="font-medium">
- {ev.name === 'screen_view' ? ev.path : ev.name}
- </span>
- <span className="text-muted-foreground tabular-nums">
- {formatDuration(offsetMs)}
- </span>
- </div>
- ))}
- </TooltipContent>
- </Tooltip>
- );
- })}
+ <span className="absolute -top-1 left-1/2 size-3 -translate-x-1/2 rounded-full border-2 border-card bg-foreground shadow" />
</div>
</div>
+ <PageBands
+ currentSegmentId={currentSegmentId}
+ duration={duration}
+ segments={segments}
+ trackWidth={trackWidth}
+ />
</div>
</TooltipProvider>
);
diff --git a/apps/start/src/components/sessions/replay/replay-utils.ts b/apps/start/src/components/sessions/replay/replay-utils.ts
index 9e0edd608..22115b7b6 100644
--- a/apps/start/src/components/sessions/replay/replay-utils.ts
+++ b/apps/start/src/components/sessions/replay/replay-utils.ts
@@ -1,14 +1,235 @@
import type { IServiceEvent } from '@openpanel/core';
+import { sortEventsAscending } from '../details/session-pages';
+
+export interface ReplayRecordEvent {
+ type: number;
+ data: unknown;
+ timestamp: number;
+}
+
+export interface EventWithOffset {
+ event: IServiceEvent;
+ offsetMs: number;
+}
+
+export interface PageSegment {
+ id: string;
+ path: string;
+ origin: string;
+ startMs: number;
+ endMs: number;
+}
+
+export interface RageClick {
+ offsetMs: number;
+ clicks: number;
+}
+
+// rrweb's numeric enums (EventType, IncrementalSource, MouseInteractions).
+const RRWEB_META = 4;
+const RRWEB_INCREMENTAL = 3;
+const SOURCE_MOUSE_MOVE = 1;
+const SOURCE_MOUSE_INTERACTION = 2;
+const SOURCE_SCROLL = 3;
+const SOURCE_INPUT = 5;
+const SOURCE_TOUCH_MOVE = 6;
+const INTERACTION_CLICK = 2;
+const USER_SOURCES = new Set([
+ SOURCE_MOUSE_MOVE,
+ SOURCE_MOUSE_INTERACTION,
+ SOURCE_SCROLL,
+ SOURCE_INPUT,
+ SOURCE_TOUCH_MOVE,
+]);
+
+// Three clicks inside a second on roughly the same spot is the usual
+// definition of a rage click (frustration with something that does not respond).
+const RAGE_CLICK_MIN_CLICKS = 3;
+const RAGE_CLICK_WINDOW_MS = 1000;
+const RAGE_CLICK_RADIUS_PX = 30;
+
+// Server events can land slightly before the recorder's first frame.
+const EARLY_EVENT_TOLERANCE_MS = 10_000;
+
+function toMs(date: Date | string): number {
+ return date instanceof Date ? date.getTime() : new Date(date).getTime();
+}
export function getEventOffsetMs(
event: IServiceEvent,
startTime: number
): number {
- const t =
- typeof event.createdAt === 'object' && event.createdAt instanceof Date
- ? event.createdAt.getTime()
- : new Date(event.createdAt).getTime();
- return t - startTime;
+ return toMs(event.createdAt) - startTime;
+}
+
+export function sortEventsByOffset(
+ events: IServiceEvent[],
+ startTime: number
+): EventWithOffset[] {
+ const withOffsets = sortEventsAscending(events).map((event) => ({
+ event,
+ offsetMs: getEventOffsetMs(event, startTime),
+ }));
+ const isEarly = ({ offsetMs }: EventWithOffset) =>
+ offsetMs < -EARLY_EVENT_TOLERANCE_MS;
+ // The page the recording opened on can be viewed long before the recorder starts.
+ const openingView = withOffsets
+ .filter((item) => isEarly(item) && item.event.name === 'screen_view')
+ .at(-1);
+ return withOffsets.filter((item) => !isEarly(item) || item === openingView);
+}
+
+/** Index of the last item at or before `timeMs`, or -1 when none has happened yet. */
+export function findLastIndexAtTime(
+ sorted: EventWithOffset[],
+ timeMs: number
+): number {
+ let lo = 0;
+ let hi = sorted.length;
+ while (lo < hi) {
+ const mid = Math.floor((lo + hi) / 2);
+ if ((sorted[mid]?.offsetMs ?? 0) <= timeMs) {
+ lo = mid + 1;
+ } else {
+ hi = mid;
+ }
+ }
+ return lo - 1;
+}
+
+/** Each screen view owns the stretch of the recording until the next one. */
+export function getPageSegments(
+ sorted: EventWithOffset[],
+ durationMs: number
+): PageSegment[] {
+ const views = sorted.filter(({ event }) => event.name === 'screen_view');
+ return views.map(({ event, offsetMs }, index) => {
+ const next = views[index + 1];
+ return {
+ id: event.id,
+ path: event.path || '/',
+ origin: event.origin ?? '',
+ startMs: Math.max(0, offsetMs),
+ endMs: Math.min(durationMs, next ? next.offsetMs : durationMs),
+ };
+ });
+}
+
+/** Viewport the recording started with, carried by rrweb's meta event. */
+export function getRecordedDimensions(
+ events: ReplayRecordEvent[]
+): { width: number; height: number } | null {
+ const meta = events.find((event) => event.type === RRWEB_META);
+ if (
+ meta &&
+ typeof meta.data === 'object' &&
+ meta.data !== null &&
+ 'width' in meta.data &&
+ 'height' in meta.data
+ ) {
+ const { width, height } = meta.data as { width: number; height: number };
+ if (width > 0 && height > 0) {
+ return { width, height };
+ }
+ }
+ return null;
+}
+
+interface IncrementalData {
+ source?: number;
+ type?: number;
+ x?: number;
+ y?: number;
+}
+
+function getIncrementalData(event: ReplayRecordEvent): IncrementalData | null {
+ if (event.type !== RRWEB_INCREMENTAL) {
+ return null;
+ }
+ if (typeof event.data !== 'object' || event.data === null) {
+ return null;
+ }
+ return event.data as IncrementalData;
+}
+
+export function isUserInteraction(event: ReplayRecordEvent): boolean {
+ const data = getIncrementalData(event);
+ return data?.source !== undefined && USER_SOURCES.has(data.source);
+}
+
+export function getClick(
+ event: ReplayRecordEvent
+): { timestamp: number; x: number; y: number } | null {
+ const data = getIncrementalData(event);
+ const isClick =
+ data?.source === SOURCE_MOUSE_INTERACTION &&
+ data.type === INTERACTION_CLICK;
+ if (!isClick) {
+ return null;
+ }
+ return { timestamp: event.timestamp, x: data.x ?? 0, y: data.y ?? 0 };
+}
+
+/** Clicks elsewhere in between do not break a burst on one spot. */
+export function detectRageClicks(
+ clicks: { timestamp: number; x: number; y: number }[],
+ startTime: number
+): RageClick[] {
+ const sorted = [...clicks].sort((a, b) => a.timestamp - b.timestamp);
+ const counted = new Set<number>();
+ const rageClicks: RageClick[] = [];
+ for (const [index, first] of sorted.entries()) {
+ if (counted.has(index)) {
+ continue;
+ }
+ const burst = [index];
+ for (let next = index + 1; next < sorted.length; next++) {
+ const click = sorted[next]!;
+ if (click.timestamp - first.timestamp > RAGE_CLICK_WINDOW_MS) {
+ break;
+ }
+ const samePlace =
+ Math.hypot(click.x - first.x, click.y - first.y) <=
+ RAGE_CLICK_RADIUS_PX;
+ if (samePlace && !counted.has(next)) {
+ burst.push(next);
+ }
+ }
+ if (burst.length >= RAGE_CLICK_MIN_CLICKS) {
+ for (const member of burst) {
+ counted.add(member);
+ }
+ rageClicks.push({
+ offsetMs: first.timestamp - startTime,
+ clicks: burst.length,
+ });
+ }
+ }
+ return rageClicks;
+}
+
+/** Interaction counts per bucket, normalised to 0..1 for drawing. */
+export function getActivityHistogram(
+ timestamps: number[],
+ startTime: number,
+ durationMs: number,
+ buckets: number
+): number[] {
+ const counts = new Array<number>(buckets).fill(0);
+ if (durationMs <= 0) {
+ return counts;
+ }
+ for (const timestamp of timestamps) {
+ const ratio = (timestamp - startTime) / durationMs;
+ if (ratio < 0 || ratio > 1) {
+ continue;
+ }
+ const bucket = Math.min(buckets - 1, Math.floor(ratio * buckets));
+ counts[bucket] = (counts[bucket] ?? 0) + 1;
+ }
+ const max = Math.max(...counts, 1);
+ // Square root keeps a single burst of mouse moves from flattening the rest.
+ return counts.map((count) => Math.sqrt(count / max));
}
/** Format a duration in milliseconds as M:SS */
@@ -18,3 +239,10 @@ export function formatDuration(ms: number): string {
const s = totalSeconds % 60;
return `${m}:${s.toString().padStart(2, '0')}`;
}
+
+export function getEventLabel(event: IServiceEvent): string {
+ if (event.name === 'screen_view' && event.path) {
+ return event.path;
+ }
+ return event.name.replace(/_/g, ' ');
+}
diff --git a/apps/start/src/components/sessions/use-session-events.ts b/apps/start/src/components/sessions/use-session-events.ts
new file mode 100644
index 000000000..c0ea62f85
--- /dev/null
+++ b/apps/start/src/components/sessions/use-session-events.ts
@@ -0,0 +1,98 @@
+import type { IServiceEvent } from '@openpanel/core';
+import { useSuspenseInfiniteQuery } from '@tanstack/react-query';
+import { useEffect, useMemo } from 'react';
+import type { useTRPC } from '@/integrations/trpc/react';
+
+// The list endpoint pages 50 events at a time; a session past this many pages
+// is a bot or a tab left open, and the page would not be readable anyway.
+const MAX_SESSION_EVENT_PAGES = 40;
+const EVENT_PAGE_SIZE = 50;
+export const MAX_SESSION_EVENTS = MAX_SESSION_EVENT_PAGES * EVENT_PAGE_SIZE;
+
+type Trpc = ReturnType<typeof useTRPC>;
+
+export function sessionEventsQueryOptions(
+ trpc: Trpc,
+ { projectId, sessionId }: { projectId: string; sessionId: string }
+) {
+ return trpc.event.events.infiniteQueryOptions(
+ { projectId, sessionId, filters: [], columnVisibility: {} },
+ {
+ getNextPageParam: (lastPage, pages) => {
+ const isLastPage =
+ lastPage.data.length === 0 || pages.length >= MAX_SESSION_EVENT_PAGES;
+ return isLastPage ? undefined : lastPage.meta.next;
+ },
+ }
+ );
+}
+
+/**
+ * `loading`: later pages are still coming. `failed`: a page failed and can be
+ * retried. `capped`: the session has more events than the page will load.
+ */
+export type SessionEventsStatus = 'complete' | 'loading' | 'failed' | 'capped';
+
+interface SessionEvents {
+ events: IServiceEvent[];
+ status: SessionEventsStatus;
+ retry: () => void;
+}
+
+function getStatus({
+ isFetchNextPageError,
+ hasNextPage,
+ isCapped,
+}: {
+ isFetchNextPageError: boolean;
+ hasNextPage: boolean;
+ isCapped: boolean;
+}): SessionEventsStatus {
+ if (isFetchNextPageError) {
+ return 'failed';
+ }
+ if (hasNextPage) {
+ return 'loading';
+ }
+ return isCapped ? 'capped' : 'complete';
+}
+
+/** Every event in the session, loading the remaining pages in the background. */
+export function useSessionEvents(
+ trpc: Trpc,
+ params: { projectId: string; sessionId: string }
+): SessionEvents {
+ const query = useSuspenseInfiniteQuery(
+ sessionEventsQueryOptions(trpc, params)
+ );
+ const {
+ hasNextPage,
+ isFetchingNextPage,
+ isFetchNextPageError,
+ fetchNextPage,
+ } = query;
+
+ // A failed page stops the chain; the page shows what loaded rather than retrying forever.
+ useEffect(() => {
+ if (hasNextPage && !(isFetchingNextPage || isFetchNextPageError)) {
+ fetchNextPage();
+ }
+ }, [hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]);
+
+ const events = useMemo(
+ () => query.data.pages.flatMap((page) => page.data),
+ [query.data]
+ );
+ const pageCount = query.data.pages.length;
+ // A short last page means the session ended inside the limit.
+ const isLastPageFull =
+ (query.data.pages.at(-1)?.data.length ?? 0) >= EVENT_PAGE_SIZE;
+ const isCapped =
+ !hasNextPage && pageCount >= MAX_SESSION_EVENT_PAGES && isLastPageFull;
+
+ return {
+ events,
+ status: getStatus({ isFetchNextPageError, hasNextPage, isCapped }),
+ retry: () => fetchNextPage(),
+ };
+}
diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.sessions_.$sessionId.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.sessions_.$sessionId.tsx
index 0f066c4a7..cf5490176 100644
--- a/apps/start/src/routes/_app.$organizationId.$projectId.sessions_.$sessionId.tsx
+++ b/apps/start/src/routes/_app.$organizationId.$projectId.sessions_.$sessionId.tsx
@@ -1,32 +1,52 @@
-import type { IServiceEvent, IServiceSession } from '@openpanel/core';
+import type { IServiceProfile, IServiceSession } from '@openpanel/core';
import { useQuery, useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute, Link } from '@tanstack/react-router';
-import { ZapIcon } from 'lucide-react';
-import { formatCost, formatTokens } from '@/components/ai/ai-format';
+import {
+ ArrowRightIcon,
+ CalendarIcon,
+ ClockIcon,
+ CopyIcon,
+ Loader2Icon,
+ VideoIcon,
+} from 'lucide-react';
+import { useMemo } from 'react';
import { AiUsageWidget } from '@/components/ai/ai-usage-widget';
-import { EmptyState } from '@/components/empty-state';
-import { EventIcon } from '@/components/events/event-icon';
-import { useEventDrawer } from '@/components/events/use-event-drawer';
import FullPageLoadingState from '@/components/full-page-loading-state';
import { PageContainer } from '@/components/page-container';
import { PageHeader } from '@/components/page-header';
+import { MostEvents } from '@/components/profiles/most-events';
import { ProfileAvatar } from '@/components/profiles/profile-avatar';
import { SerieIcon } from '@/components/report-chart/common/serie-icon';
+import { SessionJourney } from '@/components/sessions/details/session-journey';
+import { SessionMetrics } from '@/components/sessions/details/session-metrics';
+import { groupEventsByPage } from '@/components/sessions/details/session-pages';
+import { SessionProperties } from '@/components/sessions/details/session-properties';
+import { SessionTimeline } from '@/components/sessions/details/session-timeline';
import { ReplayShell } from '@/components/sessions/replay';
-import { KeyValueGrid } from '@/components/ui/key-value-grid';
+import {
+ MAX_SESSION_EVENTS,
+ type SessionEventsStatus,
+ sessionEventsQueryOptions,
+ useSessionEvents,
+} from '@/components/sessions/use-session-events';
+import { Alert, AlertDescription } from '@/components/ui/alert';
+import { Button } from '@/components/ui/button';
import {
Widget,
WidgetBody,
WidgetHead,
WidgetTitle,
} from '@/components/widget';
-import { useNumber } from '@/hooks/use-numer-formatter';
+import { fancyMinutes } from '@/hooks/use-numer-formatter';
import { useEntityPageContext } from '@/hooks/use-page-context-helpers';
import { useTRPC } from '@/integrations/trpc/react';
+import { clipboard } from '@/utils/clipboard';
import { formatDateTime } from '@/utils/date';
import { getProfileName } from '@/utils/getters';
import { createProjectTitle } from '@/utils/title';
+const MS_PER_SECOND = 1000;
+
export const Route = createFileRoute(
'/_app/$organizationId/$projectId/sessions_/$sessionId'
)({
@@ -39,12 +59,10 @@ export const Route = createFileRoute(
projectId: params.projectId,
})
),
- context.queryClient.prefetchQuery(
- context.trpc.event.events.queryOptions({
+ context.queryClient.prefetchInfiniteQuery(
+ sessionEventsQueryOptions(context.trpc, {
projectId: params.projectId,
sessionId: params.sessionId,
- filters: [],
- columnVisibility: {},
})
),
]);
@@ -55,100 +73,181 @@ export const Route = createFileRoute(
pendingComponent: FullPageLoadingState,
});
-/** `model · tokens · cost` from the flat `ai_*` properties an AI event carries. */
-function aiEventSummary(properties: Record<string, unknown>): string {
- const parts = [
- properties.ai_name,
- properties.ai_model,
- properties.ai_total_tokens
- ? `${formatTokens(Number(properties.ai_total_tokens))} tokens`
- : null,
- properties.ai_cost ? formatCost(Number(properties.ai_cost)) : null,
- properties.ai_is_error === 'true' ? 'error' : null,
- ].filter((part): part is string => typeof part === 'string' && part !== '');
- return parts.join(' · ');
+function HeaderFact({
+ icon,
+ children,
+}: {
+ icon: React.ReactNode;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="row items-center gap-2 text-muted-foreground">
+ {icon}
+ <span className="text-foreground">{children}</span>
+ </div>
+ );
}
-function sessionToFakeEvent(session: IServiceSession): IServiceEvent {
- return {
- ...session,
- name: 'screen_view',
- sessionId: session.id,
- properties: {},
- path: session.exitPath,
- origin: session.exitOrigin,
- importedAt: undefined,
- meta: undefined,
- sdkName: undefined,
- sdkVersion: undefined,
- profile: undefined,
- };
+function SessionFacts({ session }: { session: IServiceSession }) {
+ const location = [session.city, session.country].filter(Boolean).join(', ');
+ return (
+ <div className="row mb-6 flex-wrap gap-x-5 gap-y-2">
+ <HeaderFact icon={<CalendarIcon className="size-4" />}>
+ {formatDateTime(session.createdAt)}
+ </HeaderFact>
+ <HeaderFact icon={<ClockIcon className="size-4" />}>
+ {fancyMinutes(session.duration / MS_PER_SECOND)}
+ </HeaderFact>
+ {location && (
+ <HeaderFact icon={<SerieIcon name={session.country || session.city} />}>
+ {location}
+ </HeaderFact>
+ )}
+ {session.referrerName && (
+ <HeaderFact icon={<SerieIcon name={session.referrerName} />}>
+ {session.referrerName}
+ </HeaderFact>
+ )}
+ {session.device && (
+ <HeaderFact icon={<SerieIcon name={session.device} />}>
+ <span className="capitalize">{session.device}</span>
+ </HeaderFact>
+ )}
+ {session.os && (
+ <HeaderFact icon={<SerieIcon name={session.os} />}>
+ {session.os}
+ </HeaderFact>
+ )}
+ {session.browser && (
+ <HeaderFact icon={<SerieIcon name={session.browser} />}>
+ {session.browser}
+ </HeaderFact>
+ )}
+ </div>
+ );
}
-function VisitedRoutes({ paths }: { paths: string[] }) {
- const counted = paths.reduce<Record<string, number>>((acc, p) => {
- acc[p] = (acc[p] ?? 0) + 1;
- return acc;
- }, {});
- const sorted = Object.entries(counted).sort((a, b) => b[1] - a[1]);
- const max = sorted[0]?.[1] ?? 1;
+// Everything below is built from the loaded events, except the metric totals.
+const EVENT_DERIVED_SECTIONS =
+ 'the journey, timeline, unique pages, popular events and replay activity';
- if (sorted.length === 0) {
+function SessionEventsNotice({
+ status,
+ onRetry,
+}: {
+ status: SessionEventsStatus;
+ onRetry: () => void;
+}) {
+ if (status === 'complete') {
return null;
}
+ if (status === 'loading') {
+ return (
+ <div className="row items-center gap-2 text-muted-foreground text-sm">
+ <Loader2Icon className="size-4 animate-spin" />
+ Loading the rest of this session's events…
+ </div>
+ );
+ }
+ return (
+ <Alert className="row items-center justify-between gap-4">
+ <AlertDescription>
+ {status === 'failed'
+ ? `Some of this session's events could not be loaded, so ${EVENT_DERIVED_SECTIONS} are incomplete.`
+ : `This session has more than ${MAX_SESSION_EVENTS.toLocaleString()} events. Only the latest ${MAX_SESSION_EVENTS.toLocaleString()} are used for ${EVENT_DERIVED_SECTIONS}.`}
+ </AlertDescription>
+ {status === 'failed' && (
+ <Button onClick={onRetry} size="sm" variant="outline">
+ Retry
+ </Button>
+ )}
+ </Alert>
+ );
+}
+
+function VisitorCard({
+ profile,
+ session,
+ organizationId,
+ projectId,
+}: {
+ profile: IServiceProfile | null | undefined;
+ session: IServiceSession;
+ organizationId: string;
+ projectId: string;
+}) {
+ const isIdentified = session.profileId !== session.deviceId;
+ const name = profile && isIdentified ? getProfileName(profile, false) : null;
return (
- <Widget className="w-full">
+ <Widget className="w-full overflow-hidden">
<WidgetHead>
- <WidgetTitle>Visited pages</WidgetTitle>
+ <WidgetTitle>Visitor</WidgetTitle>
</WidgetHead>
- <div className="flex flex-col gap-1 p-1">
- {sorted.map(([path, count]) => (
- <div className="group relative px-3 py-2" key={path}>
- <div
- className="absolute top-0 bottom-0 left-0 rounded bg-def-200 group-hover:bg-def-300"
- style={{ width: `${(count / max) * 100}%` }}
- />
- <div className="relative flex min-w-0 justify-between gap-2">
- <span className="truncate text-sm">{path}</span>
- <span className="shrink-0 font-medium text-sm">{count}</span>
- </div>
+ <WidgetBody className="p-0">
+ <Link
+ className="group row items-center gap-3 p-4 transition-colors hover:bg-def-100"
+ params={{ organizationId, projectId, profileId: session.profileId }}
+ to="/$organizationId/$projectId/profiles/$profileId"
+ >
+ <ProfileAvatar {...profile} size="lg" />
+ <div className="col min-w-0 flex-1 gap-0.5">
+ <span className="truncate font-medium">
+ {name ?? 'Anonymous visitor'}
+ </span>
+ <span className="truncate text-muted-foreground text-sm">
+ {profile?.email || session.profileId}
+ </span>
</div>
- ))}
- </div>
+ <ArrowRightIcon className="size-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5" />
+ </Link>
+ </WidgetBody>
</Widget>
);
}
-function EventDistribution({ events }: { events: IServiceEvent[] }) {
- const counted = events.reduce<Record<string, number>>((acc, e) => {
- acc[e.name] = (acc[e.name] ?? 0) + 1;
- return acc;
- }, {});
- const sorted = Object.entries(counted).sort((a, b) => b[1] - a[1]);
- const max = sorted[0]?.[1] ?? 1;
+function SessionGroups({
+ groupIds,
+ organizationId,
+ projectId,
+}: {
+ groupIds: string[];
+ organizationId: string;
+ projectId: string;
+}) {
+ const trpc = useTRPC();
+ const { data: groups } = useQuery({
+ ...trpc.group.listByIds.queryOptions({ projectId, ids: groupIds }),
+ enabled: groupIds.length > 0,
+ });
- if (sorted.length === 0) {
+ if (!groups?.length) {
return null;
}
return (
<Widget className="w-full">
<WidgetHead>
- <WidgetTitle>Event distribution</WidgetTitle>
+ <WidgetTitle>Groups</WidgetTitle>
</WidgetHead>
- <div className="flex flex-col gap-1 p-1">
- {sorted.map(([name, count]) => (
- <div className="group relative px-3 py-2" key={name}>
- <div
- className="absolute top-0 bottom-0 left-0 rounded bg-def-200 group-hover:bg-def-300"
- style={{ width: `${(count / max) * 100}%` }}
- />
- <div className="relative flex justify-between gap-2">
- <span className="text-sm">{name.replace(/_/g, ' ')}</span>
- <span className="shrink-0 font-medium text-sm">{count}</span>
+ <div className="divide-y">
+ {groups.map((group) => (
+ <Link
+ className="row items-center gap-3 px-4 py-3 transition-colors hover:bg-def-100"
+ key={group.id}
+ params={{ organizationId, projectId, groupId: group.id }}
+ to="/$organizationId/$projectId/groups/$groupId"
+ >
+ <div className="col min-w-0 flex-1 gap-0.5">
+ <span className="truncate font-medium">{group.name}</span>
+ <span className="truncate text-muted-foreground text-sm tabular-nums">
+ {group.id}
+ </span>
</div>
- </div>
+ <span className="shrink-0 rounded border px-1.5 py-0.5 text-muted-foreground text-xs">
+ {group.type}
+ </span>
+ </Link>
))}
</div>
</Widget>
@@ -158,8 +257,6 @@ function EventDistribution({ events }: { events: IServiceEvent[] }) {
function Component() {
const { projectId, sessionId, organizationId } = Route.useParams();
const trpc = useTRPC();
- const { openEvent } = useEventDrawer();
- const number = useNumber();
const { data: session } = useSuspenseQuery(
trpc.session.byId.queryOptions({ sessionId, projectId })
@@ -167,19 +264,11 @@ function Component() {
useEntityPageContext('session', { sessionId });
- const { data: eventsData } = useSuspenseQuery(
- trpc.event.events.queryOptions({
- projectId,
- sessionId,
- filters: [],
- columnVisibility: {},
- })
- );
-
- const events = eventsData?.data ?? [];
-
- const isIdentified =
- session.profileId && session.profileId !== session.deviceId;
+ const {
+ events,
+ status: eventsStatus,
+ retry: retryEvents,
+ } = useSessionEvents(trpc, { projectId, sessionId });
const { data: profile } = useSuspenseQuery(
trpc.profile.byId.queryOptions({
@@ -188,261 +277,103 @@ function Component() {
})
);
- const { data: sessionGroups } = useQuery({
- ...trpc.group.listByIds.queryOptions({
- projectId,
- ids: session.groups ?? [],
- }),
- enabled: (session.groups?.length ?? 0) > 0,
- });
+ const visits = useMemo(
+ () => groupEventsByPage(events, session.endedAt),
+ [events, session.endedAt]
+ );
+ const eventCounts = useMemo(() => {
+ const counts = new Map<string, number>();
+ for (const event of events) {
+ counts.set(event.name, (counts.get(event.name) ?? 0) + 1);
+ }
+ return [...counts.entries()]
+ .map(([name, count]) => ({ name, count }))
+ .sort((a, b) => b.count - a.count);
+ }, [events]);
- const fakeEvent = sessionToFakeEvent(session);
+ const isIdentified = session.profileId !== session.deviceId;
+ const title =
+ profile && isIdentified
+ ? getProfileName(profile, false)
+ : 'Anonymous visitor';
return (
- <PageContainer className="col gap-8">
- <PageHeader title={`Session: ${session.id}`}>
- <div className="row mb-6 gap-4">
- {session.country && (
- <div className="row items-center gap-2">
- <SerieIcon name={session.country} />
- <span>
- {session.country}
- {session.city && ` / ${session.city}`}
- </span>
- </div>
- )}
- {session.device && (
- <div className="row items-center gap-2">
- <SerieIcon name={session.device} />
- <span className="capitalize">{session.device}</span>
- </div>
- )}
- {session.os && (
- <div className="row items-center gap-2">
- <SerieIcon name={session.os} />
- <span>{session.os}</span>
- </div>
- )}
- {session.model && (
- <div className="row items-center gap-2">
- <SerieIcon name={session.model} />
- <span>{session.model}</span>
- </div>
- )}
- {session.browser && (
- <div className="row items-center gap-2">
- <SerieIcon name={session.browser} />
- <span>{session.browser}</span>
- </div>
- )}
- </div>
+ <PageContainer className="col gap-6">
+ <PageHeader
+ actions={
+ <>
+ {session.hasReplay && (
+ <Button
+ icon={VideoIcon}
+ onClick={() =>
+ document
+ .getElementById('replay')
+ ?.scrollIntoView({ behavior: 'smooth', block: 'start' })
+ }
+ variant="outline"
+ >
+ Watch replay
+ </Button>
+ )}
+ <Button
+ icon={CopyIcon}
+ onClick={() => clipboard(session.id, 'Session id copied')}
+ variant="outline"
+ >
+ Copy id
+ </Button>
+ </>
+ }
+ title={
+ <div className="row min-w-0 items-center gap-4">
+ <ProfileAvatar {...profile} />
+ <span className="truncate">{title}</span>
+ <span className="shrink-0 rounded-md bg-def-200 px-2 py-0.5 font-medium text-muted-foreground text-xs">
+ Session
+ </span>
+ </div>
+ }
+ >
+ <SessionFacts session={session} />
</PageHeader>
- {session.hasReplay && (
- <ReplayShell projectId={projectId} sessionId={sessionId} />
- )}
+ <SessionEventsNotice onRetry={retryEvents} status={eventsStatus} />
- <div className="grid grid-cols-1 gap-6 lg:grid-cols-[340px_minmax(0,1fr)]">
- <div className="col gap-6">
- <Widget className="w-full">
- <WidgetHead>
- <WidgetTitle>Session info</WidgetTitle>
- </WidgetHead>
- <KeyValueGrid
- className="border-0"
- columns={1}
- copyable
- data={[
- {
- name: 'duration',
- value: number.formatWithUnit(session.duration / 1000, 'min'),
- },
- { name: 'createdAt', value: session.createdAt },
- { name: 'endedAt', value: session.endedAt },
- { name: 'screenViews', value: session.screenViewCount },
- { name: 'events', value: session.eventCount },
- { name: 'bounce', value: session.isBounce ? 'Yes' : 'No' },
- ...(session.entryPath
- ? [{ name: 'entryPath', value: session.entryPath }]
- : []),
- ...(session.exitPath
- ? [{ name: 'exitPath', value: session.exitPath }]
- : []),
- ...(session.referrerName
- ? [{ name: 'referrerName', value: session.referrerName }]
- : []),
- ...(session.referrer
- ? [{ name: 'referrer', value: session.referrer }]
- : []),
- ...(session.utmSource
- ? [{ name: 'utmSource', value: session.utmSource }]
- : []),
- ...(session.utmMedium
- ? [{ name: 'utmMedium', value: session.utmMedium }]
- : []),
- ...(session.utmCampaign
- ? [{ name: 'utmCampaign', value: session.utmCampaign }]
- : []),
- ...(session.revenue > 0
- ? [
- {
- name: 'revenue',
- value: number.currency(session.revenue / 100),
- },
- ]
- : []),
- { name: 'country', value: session.country, event: fakeEvent },
- ...(session.city
- ? [{ name: 'city', value: session.city, event: fakeEvent }]
- : []),
- ...(session.os
- ? [{ name: 'os', value: session.os, event: fakeEvent }]
- : []),
- ...(session.browser
- ? [
- {
- name: 'browser',
- value: session.browser,
- event: fakeEvent,
- },
- ]
- : []),
- ...(session.device
- ? [
- {
- name: 'device',
- value: session.device,
- event: fakeEvent,
- },
- ]
- : []),
- ...(session.brand
- ? [{ name: 'brand', value: session.brand, event: fakeEvent }]
- : []),
- ...(session.model
- ? [{ name: 'model', value: session.model, event: fakeEvent }]
- : []),
- ]}
- />
- </Widget>
+ <SessionMetrics events={events} session={session} />
- {isIdentified && profile && (
- <Widget className="w-full">
- <WidgetHead>
- <WidgetTitle>Profile</WidgetTitle>
- </WidgetHead>
- <WidgetBody className="p-0">
- <Link
- className="row items-center gap-3 p-4 transition-colors hover:bg-accent"
- params={{
- organizationId,
- projectId,
- profileId: session.profileId,
- }}
- to="/$organizationId/$projectId/profiles/$profileId"
- >
- <ProfileAvatar {...profile} size="lg" />
- <div className="col min-w-0 gap-0.5">
- <span className="truncate font-medium">
- {getProfileName(profile, false) ?? session.profileId}
- </span>
- {profile.email && (
- <span className="truncate text-muted-foreground text-sm">
- {profile.email}
- </span>
- )}
- </div>
- </Link>
- </WidgetBody>
- </Widget>
- )}
-
- {sessionGroups && sessionGroups.length > 0 && (
- <Widget className="w-full">
- <WidgetHead>
- <WidgetTitle>Groups</WidgetTitle>
- </WidgetHead>
- <WidgetBody className="p-0">
- {sessionGroups.map((group) => (
- <Link
- className="row items-center gap-3 p-4 transition-colors hover:bg-accent"
- key={group.id}
- params={{ organizationId, projectId, groupId: group.id }}
- to="/$organizationId/$projectId/groups/$groupId"
- >
- <div className="col min-w-0 flex-1 gap-0.5">
- <span className="truncate font-medium">{group.name}</span>
- <span className="truncate text-muted-foreground text-sm tabular-nums">
- {group.id}
- </span>
- </div>
- <span className="shrink-0 rounded border px-1.5 py-0.5 text-muted-foreground text-xs">
- {group.type}
- </span>
- </Link>
- ))}
- </WidgetBody>
- </Widget>
- )}
+ {session.hasReplay && (
+ <ReplayShell
+ events={events}
+ projectId={projectId}
+ sessionId={sessionId}
+ />
+ )}
+ <div className="grid grid-cols-1 items-start gap-6 lg:grid-cols-[minmax(0,320px)_minmax(0,1fr)]">
+ <aside className="col gap-6">
+ <VisitorCard
+ organizationId={organizationId}
+ profile={profile}
+ projectId={projectId}
+ session={session}
+ />
+ <SessionProperties session={session} />
+ <SessionGroups
+ groupIds={session.groups ?? []}
+ organizationId={organizationId}
+ projectId={projectId}
+ />
<AiUsageWidget
className="w-full"
entity={{ kind: 'session', sessionId }}
projectId={projectId}
/>
+ {eventCounts.length > 0 && <MostEvents data={eventCounts} />}
+ </aside>
- <VisitedRoutes
- paths={events
- .filter((e) => e.name === 'screen_view' && e.path)
- .map((e) => e.path)}
- />
-
- <EventDistribution events={events} />
- </div>
-
- <div className="col gap-6">
- <Widget className="w-full">
- <WidgetHead>
- <WidgetTitle>Events</WidgetTitle>
- </WidgetHead>
- <div className="divide-y">
- {events.map((event) => (
- <button
- className="row w-full items-center gap-3 px-4 py-2 text-left transition-colors hover:bg-def-100"
- key={event.id}
- onClick={() =>
- openEvent({ id: event.id, createdAt: event.createdAt })
- }
- type="button"
- >
- <EventIcon meta={event.meta} name={event.name} size="sm" />
- <div className="col min-w-0 flex-1">
- <span className="truncate font-medium text-sm">
- {event.name === 'screen_view' && event.path
- ? event.path
- : event.name.replace(/_/g, ' ')}
- </span>
- {event.name.startsWith('ai_') && (
- <span className="truncate text-muted-foreground text-xs">
- {aiEventSummary(event.properties)}
- </span>
- )}
- </div>
- <span className="shrink-0 text-muted-foreground text-xs tabular-nums">
- {formatDateTime(event.createdAt)}
- </span>
- </button>
- ))}
- {events.length === 0 && (
- <EmptyState
- description="This session has no events in it."
- icon={ZapIcon}
- title="No events"
- variant="inline"
- />
- )}
- </div>
- </Widget>
+ <div className="col min-w-0 gap-6">
+ <SessionJourney visits={visits} />
+ <SessionTimeline sessionStart={session.createdAt} visits={visits} />
</div>
</div>
</PageContainer>
diff --git a/apps/start/src/types/rrweb-player.d.ts b/apps/start/src/types/rrweb-player.d.ts
index 1d404666b..eb0eac778 100644
--- a/apps/start/src/types/rrweb-player.d.ts
+++ b/apps/start/src/types/rrweb-player.d.ts
@@ -7,6 +7,14 @@ declare module 'rrweb-player' {
showController?: boolean;
speedOption?: number[];
skipInactive?: boolean;
+ mouseTail?:
+ | boolean
+ | {
+ duration?: number;
+ lineCap?: string;
+ lineWidth?: number;
+ strokeStyle?: string;
+ };
}
interface RrwebPlayerOptions {
@@ -30,6 +38,8 @@ declare module 'rrweb-player' {
toggle: () => void;
goto: (timeOffset: number, play?: boolean) => void;
setSpeed: (speed: number) => void;
+ toggleSkipInactive: () => void;
+ triggerResize: () => void;
getMetaData: () => RrwebPlayerMetaData;
getReplayer: () => RrwebReplayer;
addEvent: (event: {
diff --git a/packages/core/src/modules/event/src/sql.test.ts b/packages/core/src/modules/event/src/sql.test.ts
index 0c3b7738f..081aec704 100644
--- a/packages/core/src/modules/event/src/sql.test.ts
+++ b/packages/core/src/modules/event/src/sql.test.ts
@@ -81,12 +81,14 @@ describe('eventListQuery', () => {
}).toStatement();
expect(query).toContain(
- 'WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < {p3:String} AND project_id = {p4:String}'
+ 'WHERE created_at >= toDateTime64({p1:String}, 3) - INTERVAL {p2:Float64} DAY AND created_at < toDateTime64({p3:String}, 3) AND project_id = {p4:String}'
);
+ // The upper bound keeps the millisecond: a whole-second bound would skip
+ // the unread events that share the last row's second.
expect(query_params).toMatchObject({
p1: '2026-09-01 12:34:56',
p2: 7,
- p3: '2026-09-01 12:34:56',
+ p3: '2026-09-01 12:34:56.789',
p4: PROJECT_ID,
});
});
diff --git a/packages/core/src/modules/event/src/sql.ts b/packages/core/src/modules/event/src/sql.ts
index a6c660523..f112a2a09 100644
--- a/packages/core/src/modules/event/src/sql.ts
+++ b/packages/core/src/modules/event/src/sql.ts
@@ -154,7 +154,7 @@ function eventListConditions(query: EventListQuery): SqlFragment[] {
}
if (query.cursor) {
conditions.push(
- sql`created_at < ${sql.string(formatClickhouseDate(query.cursor))}`
+ sql`created_at < toDateTime64(${sql.string(formatClickhouseDateTime64(query.cursor))}, 3)`
);
}
conditions.push(sql`project_id = ${projectId}`);