Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): watch replay evidence in a modal player (#96091)

Shy Alter36892c18e259
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 75820d6e4b8f..1ddfec31f32a 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -216,6 +216,60 @@ export interface TaskRunSessionLogsResult {
truncatedHeadCount: number;
}
+interface RecordingExportRow {
+ id: number;
+ has_content?: boolean;
+ export_context?: {
+ start_offset_s?: number | null;
+ end_offset_s?: number | null;
+ timestamp?: number | null;
+ duration?: number | null;
+ video_duration_s?: number | null;
+ truncated?: boolean | null;
+ inactivity_periods?: Array<{
+ ts_from_s?: number | null;
+ ts_to_s?: number | null;
+ active?: boolean | null;
+ recording_ts_from_s?: number | null;
+ recording_ts_to_s?: number | null;
+ }> | null;
+ } | null;
+}
+
+/**
+ * One stretch of the session, and where it landed in the rendered clip. An
+ * idle stretch is dropped from the render, so it occupies no clip time and its
+ * two clip values are equal.
+ */
+export interface RecordingClipSegment {
+ /** Session time the stretch covers, in seconds from the session start. */
+ sessionFromSeconds: number;
+ sessionToSeconds: number | null;
+ /** Where the stretch sits in the rendered clip, in seconds. */
+ clipFromSeconds: number;
+ clipToSeconds: number;
+ active: boolean;
+}
+
+/** A rendered mp4 of a session recording. */
+export interface RecordingExport {
+ id: number;
+ /** Where the clip starts in the session, in seconds from the session start. */
+ startOffsetSeconds: number;
+ /** Where the clip ends in the session. Null when the render did not record it. */
+ endOffsetSeconds: number | null;
+ /** Rendered length of the clip. Null on a render that did not record it. */
+ clipDurationSeconds: number | null;
+ /** The render stopped early, so the clip can end before the session does. */
+ truncated: boolean;
+ /**
+ * Session time to clip time, stretch by stretch. The render drops the idle
+ * stretches of a session, so clip time runs behind session time by however
+ * much idle time came before it. Empty on a render that kept every stretch.
+ */
+ segments: RecordingClipSegment[];
+}
+
type SessionLogsPage =
| { ok: true; entries: StoredLogEntry[]; headers: Headers }
| { ok: false; status: number; statusText: string };
@@ -6760,11 +6814,66 @@ export class PostHogAPIClient {
}
}
- /** Find an exported asset by session recording ID. */
- async findExportBySessionRecordingId(
+ /**
+ * Read the clip window and the session-to-clip time map off an export row.
+ * The render drops the idle stretches of a session, so a caller cannot treat
+ * a session offset as a clip time.
+ */
+ private parseRecordingExport(row: RecordingExportRow): RecordingExport {
+ const context = row.export_context ?? {};
+ const startOffsetSeconds = context.start_offset_s ?? context.timestamp ?? 0;
+ const endOffsetSeconds =
+ context.end_offset_s ??
+ (context.duration != null ? startOffsetSeconds + context.duration : null);
+
+ const segments: RecordingClipSegment[] = [];
+ for (const period of context.inactivity_periods ?? []) {
+ if (period.ts_from_s == null || period.recording_ts_from_s == null) {
+ continue;
+ }
+ segments.push({
+ sessionFromSeconds: period.ts_from_s,
+ sessionToSeconds: period.ts_to_s ?? null,
+ clipFromSeconds: period.recording_ts_from_s,
+ clipToSeconds: period.recording_ts_to_s ?? period.recording_ts_from_s,
+ active: period.active !== false,
+ });
+ }
+ segments.sort((a, b) => a.sessionFromSeconds - b.sessionFromSeconds);
+
+ return {
+ id: row.id,
+ startOffsetSeconds,
+ endOffsetSeconds,
+ clipDurationSeconds: context.video_duration_s ?? null,
+ truncated: context.truncated === true,
+ segments,
+ };
+ }
+
+ /** Get one exported recording clip, with the window of the session it covers. */
+ async getRecordingExport(
+ projectId: number,
+ exportId: number,
+ ): Promise<RecordingExport | null> {
+ const urlPath = `/api/projects/${projectId}/exports/${exportId}/`;
+ const url = new URL(`${this.api.baseUrl}${urlPath}`);
+ const response = await this.api.fetcher.fetch({
+ method: "get",
+ url,
+ path: urlPath,
+ });
+ if (!response.ok) return null;
+ const row = (await response.json()) as RecordingExportRow;
+ if (row.has_content === false) return null;
+ return this.parseRecordingExport(row);
+ }
+
+ /** Find the rendered clip for a session recording, with the window it covers. */
+ async findRecordingExport(
projectId: number,
sessionRecordingId: string,
- ): Promise<number | null> {
+ ): Promise<RecordingExport | null> {
const urlPath = `/api/projects/${projectId}/exports/`;
const url = new URL(`${this.api.baseUrl}${urlPath}`);
url.searchParams.set("session_recording_id", sessionRecordingId);
@@ -6776,10 +6885,10 @@ export class PostHogAPIClient {
});
if (!response.ok) return null;
const data = (await response.json()) as {
- results?: Array<{ id: number; has_content: boolean }>;
+ results?: RecordingExportRow[];
};
const match = data.results?.find((e) => e.has_content);
- return match?.id ?? null;
+ return match ? this.parseRecordingExport(match) : null;
}
/** Get the presigned content URL for an exported asset (e.g. rasterized recording). */
diff --git a/products/desktop/packages/ui/src/features/inbox/components/detail/SignalCard.tsx b/products/desktop/packages/ui/src/features/inbox/components/detail/SignalCard.tsx
index 42fd0ce134a2..1a603206cbf2 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/detail/SignalCard.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/detail/SignalCard.tsx
@@ -3,17 +3,34 @@ import {
CaretDownIcon,
CaretRightIcon,
CheckCircleIcon,
+ PlayIcon,
TagIcon,
} from "@phosphor-icons/react";
+import type { RecordingExport } from "@posthog/api-client/posthog-client";
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@posthog/quill";
import type { Signal, SignalFindingContent } from "@posthog/shared/types";
import { useAuthStateValue } from "@posthog/ui/features/auth/store";
import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
import { getSourceProductMeta } from "@posthog/ui/features/inbox/components/utils/source-product-icons";
import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";
-import { errorTrackingIssueUrl } from "@posthog/ui/utils/posthogLinks";
+import {
+ colonOffsetToSeconds,
+ errorTrackingIssueUrl,
+ sessionRecordingUrl,
+} from "@posthog/ui/utils/posthogLinks";
import { Badge, Box, Flex, Text } from "@radix-ui/themes";
-import { useCallback, useMemo, useRef, useState } from "react";
+import { type ReactNode, useCallback, useMemo, useRef, useState } from "react";
+import { clipTimeForMoment } from "./recordingClipTime";
import {
type SignalInteractionAction,
SignalInteractionContext,
@@ -154,6 +171,20 @@ interface ErrorTrackingExtra {
fingerprint?: string;
}
+interface ScannerFindingExtra {
+ scanner_name?: string;
+ session_id?: string;
+ problem_type?: string;
+ start_time?: number;
+ end_time?: number;
+ exported_asset_id?: number;
+ distinct_id?: string;
+ recording_start_time?: string;
+ recording_end_time?: string;
+ recording_duration?: number;
+ recording_active_seconds?: number;
+}
+
function resolveLabels(
raw: GitHubIssueExtra["labels"],
): { name: string; color?: string }[] {
@@ -241,12 +272,16 @@ function isLlmEvalExtra(
return "evaluation_id" in extra && "trace_id" in extra;
}
-function isSessionProblemExtra(
+function isSessionExtra(
extra: Record<string, unknown>,
): extra is Record<string, unknown> & SessionProblemExtra {
- return (
- "session_id" in extra && "problem_type" in extra && "segment_title" in extra
- );
+ return "session_id" in extra && "segment_title" in extra;
+}
+
+function isScannerFindingExtra(
+ extra: Record<string, unknown>,
+): extra is Record<string, unknown> & ScannerFindingExtra {
+ return "session_id" in extra && "scanner_name" in extra;
}
function isErrorTrackingExtra(
@@ -539,6 +574,17 @@ function formatSessionDuration(seconds: number): string {
return remainMins > 0 ? `${hrs}h ${remainMins}m` : `${hrs}h`;
}
+function colonOffset(seconds: number): string {
+ const total = Math.round(seconds);
+ const mins = Math.floor(total / 60);
+ const secs = total % 60;
+ const hrs = Math.floor(mins / 60);
+ const pad = (n: number) => String(n).padStart(2, "0");
+ return hrs > 0
+ ? `${pad(hrs)}:${pad(mins % 60)}:${pad(secs)}`
+ : `${pad(mins)}:${pad(secs)}`;
+}
+
function SessionProblemSignalCard({
signal,
extra,
@@ -570,9 +616,14 @@ function SessionProblemSignalCard({
<CollapsibleBody body={signal.content} />
{extra.session_id && (
- <SessionRecordingVideo
+ <SessionRecordingPreview
exportedAssetId={extra.exported_asset_id}
sessionId={extra.session_id}
+ seekSeconds={
+ extra.start_time
+ ? colonOffsetToSeconds(extra.start_time)
+ : undefined
+ }
/>
)}
@@ -632,62 +683,279 @@ function SessionProblemSignalCard({
);
}
-function SessionRecordingVideo({
+/**
+ * A compact action on an evidence card: a glyph and a label in a pill, sized to
+ * sit beside the card's metadata. Every evidence type puts its affordance in
+ * this one shape, so a card gains an action without gaining a block.
+ */
+function EvidenceActionPill({
+ glyph,
+ label,
+ href,
+ onClick,
+}: {
+ glyph: ReactNode;
+ label: string;
+ href?: string;
+ onClick?: () => void;
+}) {
+ const className =
+ "group inline-flex items-center gap-1.5 rounded-full border border-(--gray-5) bg-(--gray-2) py-1 pr-2.5 pl-1.5 font-medium text-[12px] text-gray-11 no-underline transition-colors hover:border-(--gray-7) hover:bg-(--gray-3) hover:text-gray-12";
+ const body = (
+ <>
+ <span className="flex size-4 items-center justify-center rounded-full bg-(--accent-9) text-white transition-transform duration-150 group-hover:scale-110">
+ {glyph}
+ </span>
+ {label}
+ </>
+ );
+
+ if (href) {
+ return (
+ <a href={href} target="_blank" rel="noreferrer" className={className}>
+ {body}
+ </a>
+ );
+ }
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={`${className} cursor-pointer`}
+ >
+ {body}
+ </button>
+ );
+}
+
+/**
+ * The recording affordance on an evidence card: a pill that opens the rendered
+ * clip in a modal player, at the moment the finding describes. The clip
+ * downloads only once that modal opens, so a report full of evidence costs one
+ * cheap lookup per card rather than one mp4 per card.
+ */
+function SessionRecordingPreview({
exportedAssetId,
sessionId,
+ seekSeconds,
}: {
exportedAssetId?: number;
sessionId: string;
+ seekSeconds?: number | null;
}) {
const projectId = useAuthStateValue((state) => state.currentProjectId);
const videoRef = useRef<HTMLVideoElement>(null);
const hasFiredPlayRef = useRef(false);
const interaction = useSignalInteraction();
- const videoQuery = useAuthenticatedQuery<string | null>(
- ["export-video", projectId, exportedAssetId, sessionId],
+ const [open, setOpen] = useState(false);
+ // Null until the clip reports its length, since only then can the player say
+ // whether the moment is in it.
+ const [momentReachable, setMomentReachable] = useState<boolean | null>(null);
+
+ const exportQuery = useAuthenticatedQuery<RecordingExport | null>(
+ ["recording-export", projectId, exportedAssetId, sessionId],
async (client) => {
if (!projectId) return null;
- let assetId: number | null = exportedAssetId ?? null;
- // If no asset ID in the signal, look up the export by session_id
- if (assetId == null) {
- assetId = await client.findExportBySessionRecordingId(
- projectId,
- sessionId,
- );
- if (assetId == null) return null;
- }
- return client.getExportContentUrl(projectId, assetId);
+ return exportedAssetId != null
+ ? await client.getRecordingExport(projectId, exportedAssetId)
+ : await client.findRecordingExport(projectId, sessionId);
},
{ enabled: !!projectId, staleTime: Infinity },
);
+ const clip = exportQuery.data ?? null;
+
+ const clipQuery = useAuthenticatedQuery<string | null>(
+ ["recording-clip", projectId, clip?.id],
+ async (client) => {
+ if (!projectId || clip == null) return null;
+ return await client.getExportContentUrl(projectId, clip.id);
+ },
+ { enabled: open && !!projectId && clip != null, staleTime: Infinity },
+ );
+
+ const playerUrl = sessionRecordingUrl(sessionId, {
+ secondsOffsetFromStart: seekSeconds,
+ });
+ const momentLabel = seekSeconds != null ? colonOffset(seekSeconds) : null;
+ const pillLabel = momentLabel
+ ? `Watch at ${momentLabel}`
+ : "Watch the recording";
- if (videoQuery.isError || videoQuery.data === null) return null;
- if (videoQuery.isLoading || videoQuery.data === undefined) {
+ const seekToMoment = useCallback(() => {
+ const video = videoRef.current;
+ if (!video || seekSeconds == null || clip == null) return;
+ const target = clipTimeForMoment(clip, seekSeconds);
+ if (target == null) return;
+ video.currentTime = Math.min(target, video.duration);
+ }, [clip, seekSeconds]);
+
+ const handleLoadedMetadata = useCallback(() => {
+ if (seekSeconds == null || clip == null) return;
+ setMomentReachable(clipTimeForMoment(clip, seekSeconds) != null);
+ seekToMoment();
+ }, [clip, seekSeconds, seekToMoment]);
+
+ // No clip was rendered for this session, so the web player is the only route
+ // to the recording.
+ if (exportQuery.isError || (exportQuery.isFetched && clip == null)) {
+ if (!playerUrl) return null;
return (
- <Box
- mt="2"
- className="flex h-24 items-center justify-center rounded bg-gray-3 text-[12px] text-gray-9"
- >
- Loading recording…
- </Box>
+ <div className="mt-2 flex">
+ <EvidenceActionPill
+ glyph={<ArrowSquareOutIcon size={9} weight="bold" />}
+ label={pillLabel}
+ href={playerUrl}
+ />
+ </div>
);
}
+ const clipUnavailable = clipQuery.isError || clipQuery.data === null;
+ const clipPending = !clipUnavailable && clipQuery.data == null;
+
return (
- <Box mt="2" className="overflow-hidden rounded">
- <video
- ref={videoRef}
- src={videoQuery.data}
- controls
- muted
- preload="metadata"
- className="max-h-[300px] w-full rounded"
- onPlay={() => {
- if (hasFiredPlayRef.current) return;
- hasFiredPlayRef.current = true;
- interaction?.onInteraction({ type: "play_session_recording" });
- }}
- />
+ <>
+ <div className="mt-2 flex">
+ <EvidenceActionPill
+ glyph={
+ <PlayIcon size={9} weight="fill" className="translate-x-[0.5px]" />
+ }
+ label={pillLabel}
+ onClick={() => setOpen(true)}
+ />
+ </div>
+
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent size="wide">
+ <DialogHeader>
+ <DialogTitle>Session recording</DialogTitle>
+ <DialogDescription>
+ {momentLabel == null
+ ? "The rendered clip from this session."
+ : momentReachable === false
+ ? `The clip stops before ${momentLabel}. Open the session in PostHog to reach that moment.`
+ : `The rendered clip, at ${momentLabel} in the session.`}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody>
+ <div className="overflow-hidden rounded-(--radius-2) bg-black">
+ {clipUnavailable ? (
+ <div className="flex aspect-video items-center justify-center px-6 text-center text-[13px] text-gray-10">
+ This clip is no longer available.
+ </div>
+ ) : clipPending ? (
+ <div className="flex aspect-video items-center justify-center text-[13px] text-gray-10">
+ Loading the recording…
+ </div>
+ ) : (
+ <video
+ ref={videoRef}
+ src={clipQuery.data ?? undefined}
+ controls
+ autoPlay
+ muted
+ playsInline
+ className="aspect-video w-full"
+ onLoadedMetadata={handleLoadedMetadata}
+ onPlay={() => {
+ if (hasFiredPlayRef.current) return;
+ hasFiredPlayRef.current = true;
+ interaction?.onInteraction({
+ type: "play_session_recording",
+ });
+ }}
+ />
+ )}
+ </div>
+ </DialogBody>
+ <DialogFooter className="sm:items-center sm:justify-between">
+ {momentLabel && momentReachable === true ? (
+ <Button variant="outline" size="sm" onClick={seekToMoment}>
+ Back to {momentLabel}
+ </Button>
+ ) : (
+ <span />
+ )}
+ {playerUrl && (
+ <a
+ href={playerUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex items-center gap-1 text-[12px] text-gray-10 no-underline hover:text-gray-12"
+ >
+ Open in PostHog
+ <ArrowSquareOutIcon size={12} />
+ </a>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
+
+function ScannerFindingSignalCard({
+ signal,
+ extra,
+ verified,
+ codePaths,
+ dataQueried,
+}: {
+ signal: Signal;
+ extra: ScannerFindingExtra;
+ verified?: boolean;
+ codePaths?: string[];
+ dataQueried?: string;
+}) {
+ return (
+ <Box className="min-w-0 overflow-hidden rounded-(--radius-2) border border-(--gray-6) bg-gray-1 p-3">
+ <SignalCardHeader signal={signal} verified={verified} />
+ {extra.scanner_name && (
+ <Text mt="1" className="font-medium text-[14px] text-gray-11" as="p">
+ {extra.scanner_name}
+ </Text>
+ )}
+ <CollapsibleBody body={signal.content} />
+
+ {extra.session_id && (
+ <SessionRecordingPreview
+ exportedAssetId={extra.exported_asset_id}
+ sessionId={extra.session_id}
+ seekSeconds={extra.start_time}
+ />
+ )}
+
+ <Flex
+ align="center"
+ gap="2"
+ wrap="wrap"
+ mt="2"
+ className="text-[12px] text-gray-10"
+ >
+ {extra.distinct_id && (
+ <Text className="font-mono text-[12px]">
+ {extra.distinct_id.slice(0, 10)}…
+ </Text>
+ )}
+ {extra.start_time != null && extra.end_time != null && (
+ <>
+ <span>·</span>
+ <span>
+ {colonOffset(extra.start_time)} – {colonOffset(extra.end_time)}
+ </span>
+ </>
+ )}
+ {extra.recording_duration != null && (
+ <>
+ <span>·</span>
+ <span>
+ {formatSessionDuration(extra.recording_duration)} session
+ </span>
+ </>
+ )}
+ </Flex>
+ <CodePathsCollapsible paths={codePaths ?? []} />
+ <DataQueriedCollapsible text={dataQueried ?? ""} />
</Box>
);
}
@@ -895,11 +1163,7 @@ export function SignalCard({
);
let content: React.ReactNode;
- if (
- signal.source_product === "session_replay" &&
- signal.source_type === "session_problem" &&
- isSessionProblemExtra(extra)
- ) {
+ if (signal.source_product === "session_replay" && isSessionExtra(extra)) {
content = (
<SessionProblemSignalCard
signal={signal}
@@ -909,6 +1173,19 @@ export function SignalCard({
dataQueried={dataQueried}
/>
);
+ } else if (
+ signal.source_product === "replay_vision" &&
+ isScannerFindingExtra(extra)
+ ) {
+ content = (
+ <ScannerFindingSignalCard
+ signal={signal}
+ extra={extra}
+ verified={verified}
+ codePaths={codePaths}
+ dataQueried={dataQueried}
+ />
+ );
} else if (
signal.source_product === "error_tracking" &&
isErrorTrackingExtra(extra)
diff --git a/products/desktop/packages/ui/src/features/inbox/components/detail/recordingClipTime.test.ts b/products/desktop/packages/ui/src/features/inbox/components/detail/recordingClipTime.test.ts
new file mode 100644
index 000000000000..a6e49956a808
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/detail/recordingClipTime.test.ts
@@ -0,0 +1,105 @@
+import type {
+ RecordingClipSegment,
+ RecordingExport,
+} from "@posthog/api-client/posthog-client";
+import { describe, expect, it } from "vitest";
+import { clipTimeForMoment } from "./recordingClipTime";
+
+function makeClip(overrides: Partial<RecordingExport> = {}): RecordingExport {
+ return {
+ id: 1,
+ startOffsetSeconds: 0,
+ endOffsetSeconds: null,
+ clipDurationSeconds: null,
+ truncated: false,
+ segments: [],
+ ...overrides,
+ };
+}
+
+function segment(
+ sessionFrom: number,
+ sessionTo: number,
+ clipFrom: number,
+ clipTo: number,
+ active = true,
+): RecordingClipSegment {
+ return {
+ sessionFromSeconds: sessionFrom,
+ sessionToSeconds: sessionTo,
+ clipFromSeconds: clipFrom,
+ clipToSeconds: clipTo,
+ active,
+ };
+}
+
+describe("clipTimeForMoment", () => {
+ describe("a render that kept every stretch", () => {
+ it.each([
+ ["a whole-session clip", 0, 120, 120],
+ ["a clip whose window opens late", 100, 160, 60],
+ ])("maps %s", (_label, startOffset, sessionOffset, expected) => {
+ const clip = makeClip({
+ startOffsetSeconds: startOffset,
+ clipDurationSeconds: 300,
+ });
+ expect(clipTimeForMoment(clip, sessionOffset)).toBe(expected);
+ });
+
+ it.each([
+ ["the moment sits before the window", 100, 40],
+ ["the moment sits past the clip's end", 0, 400],
+ ])("returns null when %s", (_label, startOffset, sessionOffset) => {
+ const clip = makeClip({
+ startOffsetSeconds: startOffset,
+ clipDurationSeconds: 300,
+ });
+ expect(clipTimeForMoment(clip, sessionOffset)).toBeNull();
+ });
+ });
+
+ describe("a render that dropped idle stretches", () => {
+ // 0-60s active, 60-300s idle and dropped, 300-360s active. A 5:00 session
+ // renders as a 2:00 clip.
+ const clip = makeClip({
+ clipDurationSeconds: 120,
+ segments: [
+ segment(0, 60, 0, 60),
+ segment(60, 300, 60, 60, false),
+ segment(300, 360, 60, 120),
+ ],
+ });
+
+ it.each([
+ ["inside the first active stretch", 30, 30],
+ ["at the boundary into the dropped stretch", 60, 60],
+ ["inside the second active stretch", 330, 90],
+ ["at the very end of the clip", 360, 120],
+ ])("maps a moment %s", (_label, sessionOffset, expected) => {
+ expect(clipTimeForMoment(clip, sessionOffset)).toBe(expected);
+ });
+
+ it("resolves a moment inside a dropped stretch to the next frame", () => {
+ expect(clipTimeForMoment(clip, 200)).toBe(60);
+ });
+
+ it("maps a moment past the clip's length, which a subtraction would reject", () => {
+ // The bug this replaced: 330s in the session is only 90s into the clip,
+ // but a session-minus-start subtraction reads 330 > 120 and gives up.
+ const target = clipTimeForMoment(clip, 330);
+ expect(target).not.toBeNull();
+ expect(target).toBeLessThan(clip.clipDurationSeconds ?? 0);
+ });
+
+ it("returns null for a moment the render never reached", () => {
+ expect(clipTimeForMoment(clip, 420)).toBeNull();
+ });
+
+ it("returns the clip start for a moment before the first stretch", () => {
+ const late = makeClip({
+ segments: [segment(100, 160, 0, 60)],
+ });
+ expect(clipTimeForMoment(late, 40)).toBe(0);
+ });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/inbox/components/detail/recordingClipTime.ts b/products/desktop/packages/ui/src/features/inbox/components/detail/recordingClipTime.ts
new file mode 100644
index 000000000000..9d7cb83bf5c7
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/detail/recordingClipTime.ts
@@ -0,0 +1,48 @@
+import type { RecordingExport } from "@posthog/api-client/posthog-client";
+
+/**
+ * Map a moment in the session onto a time in the rendered clip.
+ *
+ * A render drops the idle stretches of a session, so clip time runs behind
+ * session time by however much idle time came before the moment: a moment 7
+ * minutes into a session can sit 4 minutes into the clip. The render records
+ * where each stretch landed, so walk those rather than subtracting offsets.
+ *
+ * A moment that fell inside a dropped stretch has no frame of its own and
+ * resolves to the first frame after it. Null means the clip does not reach the
+ * moment, which happens when the render stopped early.
+ */
+export function clipTimeForMoment(
+ clip: RecordingExport,
+ sessionOffsetSeconds: number,
+): number | null {
+ if (clip.segments.length === 0) {
+ // The render kept every stretch, so the clip runs in session order from
+ // wherever its window opens.
+ const clipTime = sessionOffsetSeconds - clip.startOffsetSeconds;
+ if (clipTime < 0) return null;
+ if (
+ clip.clipDurationSeconds != null &&
+ clipTime > clip.clipDurationSeconds
+ ) {
+ return null;
+ }
+ return clipTime;
+ }
+
+ for (const segment of clip.segments) {
+ if (sessionOffsetSeconds < segment.sessionFromSeconds) {
+ return segment.clipFromSeconds;
+ }
+ const sessionTo = segment.sessionToSeconds ?? segment.sessionFromSeconds;
+ if (sessionOffsetSeconds <= sessionTo) {
+ if (!segment.active) return segment.clipFromSeconds;
+ const intoSegment = sessionOffsetSeconds - segment.sessionFromSeconds;
+ return Math.min(
+ segment.clipFromSeconds + intoSegment,
+ segment.clipToSeconds,
+ );
+ }
+ }
+ return null;
+}
diff --git a/products/desktop/packages/ui/src/utils/posthogLinks.test.ts b/products/desktop/packages/ui/src/utils/posthogLinks.test.ts
index 7ae5bb226c30..39512ff5d190 100644
--- a/products/desktop/packages/ui/src/utils/posthogLinks.test.ts
+++ b/products/desktop/packages/ui/src/utils/posthogLinks.test.ts
@@ -1,8 +1,10 @@
import {
canvasShareUrl,
+ colonOffsetToSeconds,
errorTrackingIssueUrl,
inboxReportUrl,
parseShareLink,
+ sessionRecordingUrl,
} from "@posthog/ui/utils/posthogLinks";
import { describe, expect, it, vi } from "vitest";
@@ -96,3 +98,59 @@ describe("errorTrackingIssueUrl", () => {
);
});
});
+
+describe("colonOffsetToSeconds", () => {
+ it.each([
+ ["MM:SS", "01:47", 107],
+ ["HH:MM:SS", "1:02:03", 3723],
+ ["zero-padded minutes", "10:00", 600],
+ ])("parses %s", (_label, offset, expected) => {
+ expect(colonOffsetToSeconds(offset)).toBe(expected);
+ });
+
+ it.each([
+ ["a bare number", "47"],
+ ["too many parts", "1:2:3:4"],
+ ["a non-numeric part", "ab:cd"],
+ ["a negative part", "-1:00"],
+ ["an empty segment", "1::2"],
+ ["a hex literal", "0x10:00"],
+ ["scientific notation", "1e308:00"],
+ ["padded whitespace", " 1 : 2 "],
+ ["seconds of 60", "1:60"],
+ ["minutes of 60 in HH:MM:SS", "1:60:00"],
+ ])("returns null for %s", (_label, offset) => {
+ expect(colonOffsetToSeconds(offset)).toBeNull();
+ });
+});
+
+describe("sessionRecordingUrl", () => {
+ it("links to the recording without a seek offset", () => {
+ expect(
+ sessionRecordingUrl("session-id-1", undefined, {
+ projectId: 123,
+ cloudRegion: "us",
+ }),
+ ).toBe("https://us.posthog.com/project/123/replay/session-id-1");
+ });
+
+ it("includes a ?t= seek offset when provided", () => {
+ expect(
+ sessionRecordingUrl(
+ "session-id-1",
+ { secondsOffsetFromStart: 107 },
+ { projectId: 123, cloudRegion: "us" },
+ ),
+ ).toBe("https://us.posthog.com/project/123/replay/session-id-1?t=107");
+ });
+
+ it("omits the offset when it is explicitly null", () => {
+ expect(
+ sessionRecordingUrl(
+ "session-id-1",
+ { secondsOffsetFromStart: null },
+ { projectId: 123, cloudRegion: "us" },
+ ),
+ ).toBe("https://us.posthog.com/project/123/replay/session-id-1");
+ });
+});
diff --git a/products/desktop/packages/ui/src/utils/posthogLinks.ts b/products/desktop/packages/ui/src/utils/posthogLinks.ts
index 134ffed43833..a70ddaca93c2 100644
--- a/products/desktop/packages/ui/src/utils/posthogLinks.ts
+++ b/products/desktop/packages/ui/src/utils/posthogLinks.ts
@@ -240,3 +240,27 @@ export function errorTrackingIssueUrl(
: path;
}, overrides);
}
+
+export function colonOffsetToSeconds(offset: string): number | null {
+ const parts = offset.split(":");
+ if (parts.length < 2 || parts.length > 3) return null;
+ if (parts.some((p) => !/^\d+$/.test(p))) return null;
+ const nums = parts.map(Number);
+ const [h, m, s] = parts.length === 3 ? nums : [0, nums[0], nums[1]];
+ if (m >= 60 || s >= 60) return null;
+ const total = h * 3600 + m * 60 + s;
+ return Number.isSafeInteger(total) ? total : null;
+}
+
+export function sessionRecordingUrl(
+ sessionId: string,
+ options?: { secondsOffsetFromStart?: number | null },
+ overrides?: LinkOverrides,
+): string | null {
+ return withProjectId((pid) => {
+ const path = `/project/${pid}/replay/${encodeURIComponent(sessionId)}`;
+ return options?.secondsOffsetFromStart != null
+ ? `${path}?t=${options.secondsOffsetFromStart}`
+ : path;
+ }, overrides);
+}