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(replay): break summaries down into chapters with frames (#109243)

Tue Haulunde6e398c1916b
diff --git a/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts b/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts
index a4c560ce14f5..a995c31b6d2f 100644
--- a/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts
+++ b/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts
@@ -112,6 +112,26 @@ describe('recording cleanup (integration)', () => {
[randomUUID(), alertId, targetObservationId, teamId],
'fixtureMatch'
)
+ const thumbnail = await postgres.query(
+ PostgresUse.COMMON_WRITE,
+ `INSERT INTO posthog_exportedasset
+ (team_id, export_format, created_at, export_context, is_system, expires_after)
+ VALUES ($1, 'image/png', now(), $2::jsonb, true, now() + interval '90 days')
+ RETURNING id`,
+ [
+ teamId,
+ JSON.stringify({ session_recording_id: 'session-to-delete', observation_id: targetObservationId }),
+ ],
+ 'fixtureThumbnailAsset'
+ )
+ await postgres.query(
+ PostgresUse.COMMON_WRITE,
+ `INSERT INTO replay_vision_replayobservationmedia
+ (id, observation_id, asset_id, team_id, kind, position, video_start_ms, created_at)
+ VALUES ($1, $2, $3, $4, 'thumbnail', 0, 0, now())`,
+ [randomUUID(), targetObservationId, thumbnail.rows[0].id, teamId],
+ 'fixtureMedia'
+ )
// Of the deleted recording: a system render, a person's own gif export, and an event screenshot frame.
// Of a kept recording: one export, which must stay.
for (const [format, isSystem, sessionId] of [
@@ -161,6 +181,11 @@ describe('recording cleanup (integration)', () => {
targetObservationId,
])
).toBe(0)
+ expect(
+ await count(`SELECT count(*) FROM replay_vision_replayobservationmedia WHERE observation_id = $1`, [
+ targetObservationId,
+ ])
+ ).toBe(0)
// An observation of a different recording is untouched.
expect(
diff --git a/nodejs/src/session-replay/recording-api/recording-service.ts b/nodejs/src/session-replay/recording-api/recording-service.ts
index 2ff11fde49c3..a801afa0c51e 100644
--- a/nodejs/src/session-replay/recording-api/recording-service.ts
+++ b/nodejs/src/session-replay/recording-api/recording-service.ts
@@ -457,6 +457,9 @@ export class RecordingService {
), deleted_matches AS (
DELETE FROM replay_vision_visionalertmatch
WHERE observation_id IN (SELECT id FROM observations)
+ ), deleted_media AS (
+ DELETE FROM replay_vision_replayobservationmedia
+ WHERE observation_id IN (SELECT id FROM observations)
)
DELETE FROM replay_vision_replayobservation
WHERE id IN (SELECT id FROM observations)`,
diff --git a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts
index 79121338c31d..a5cca72a13ab 100644
--- a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts
@@ -14,10 +14,11 @@ import { createLogger } from '~/session-replay/recording-rasterizer/logger'
import { RasterizationMetrics } from '~/session-replay/recording-rasterizer/metrics'
import { renderOutputFields } from '~/session-replay/recording-rasterizer/postprocess'
import { uploadToS3 } from '~/session-replay/recording-rasterizer/storage'
-import { extractThumbnail } from '~/session-replay/recording-rasterizer/thumbnail'
+import { extractThumbnail, extractThumbnails } from '~/session-replay/recording-rasterizer/thumbnail'
import {
ActivityTimings,
ExtractThumbnailInput,
+ ExtractThumbnailsInput,
RasterizationProgress,
RasterizeRecordingInput,
RasterizeRecordingOutput,
@@ -224,25 +225,28 @@ async function rasterizeRecordingActivity(
}
}
+async function runMediaActivity<T>(run: () => Promise<T>): Promise<T> {
+ // The media path is fail-soft, so these counters are the only sign that the fleet is failing.
+ RasterizationMetrics.activityStarted()
+ try {
+ return await run()
+ } catch (err) {
+ const rasterizationError = asRasterizationError(err)
+ RasterizationMetrics.incrementError(
+ rasterizationError?.code ?? 'UNKNOWN',
+ rasterizationError?.retryable ?? true
+ )
+ throw toActivityError(rasterizationError ?? err)
+ } finally {
+ RasterizationMetrics.activityFinished()
+ }
+}
+
export function createActivities(pool: BrowserPool, playerHtml: string) {
return {
'rasterize-recording': (input: RasterizeRecordingInput) => rasterizeRecordingActivity(pool, playerHtml, input),
// No browser and no pool: this one reads an MP4 the rasterizer already produced.
- 'extract-thumbnail': async (input: ExtractThumbnailInput) => {
- // The media path is fail-soft, so these counters are the only sign that the fleet is failing.
- RasterizationMetrics.activityStarted()
- try {
- return await extractThumbnail(input)
- } catch (err) {
- const rasterizationError = asRasterizationError(err)
- RasterizationMetrics.incrementError(
- rasterizationError?.code ?? 'UNKNOWN',
- rasterizationError?.retryable ?? true
- )
- throw toActivityError(rasterizationError ?? err)
- } finally {
- RasterizationMetrics.activityFinished()
- }
- },
+ 'extract-thumbnail': (input: ExtractThumbnailInput) => runMediaActivity(() => extractThumbnail(input)),
+ 'extract-thumbnails': (input: ExtractThumbnailsInput) => runMediaActivity(() => extractThumbnails(input)),
}
}
diff --git a/nodejs/src/session-replay/recording-rasterizer/thumbnail.ts b/nodejs/src/session-replay/recording-rasterizer/thumbnail.ts
index b1c7c0ce941d..3b3a0a4fea21 100644
--- a/nodejs/src/session-replay/recording-rasterizer/thumbnail.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/thumbnail.ts
@@ -8,7 +8,12 @@ import { toFiniteNumber } from './capture/config'
import { RasterizationError } from './errors'
import { createLogger } from './logger'
import { downloadFromS3, parseS3Uri, uploadToS3 } from './storage'
-import type { ExtractThumbnailInput, ExtractThumbnailOutput } from './types'
+import type {
+ ExtractThumbnailInput,
+ ExtractThumbnailOutput,
+ ExtractThumbnailsInput,
+ ExtractThumbnailsOutput,
+} from './types'
const execFileAsync = promisify(execFile)
const log = createLogger()
@@ -160,88 +165,137 @@ async function detectBorder(
}
}
-/**
- * Cut one frame from an already-rendered analysis MP4 and store it as a PNG.
- *
- * No browser, so this costs seconds of CPU rather than a recording load. The crop removes the
- * burned-in metadata footer, which is an artifact of the analysis render and not part of the page.
- */
-export async function extractThumbnail(input: ExtractThumbnailInput): Promise<ExtractThumbnailOutput> {
- const source = parseS3Uri(input.source_s3_uri)
- // Before the download: `-ss NaN` burns both attempts, each pulling the whole MP4 first.
- const videoTimeS = Math.max(0, toFiniteNumber(input.video_time_s, 'video_time_s'))
- const workDir = await fs.mkdtemp(path.join(process.env.VIDEO_WORK_DIR || os.tmpdir(), 'thumb-'))
- const sourcePath = path.join(workDir, 'source.mp4')
- const outputPath = path.join(workDir, 'thumbnail.png')
- const rawPath = path.join(workDir, 'frame.rgb')
+interface FrameSource {
+ workDir: string
+ sourcePath: string
+ footerCrop: string
+ size: { width: number; height: number } | null
+ footer: number
+ width: number
+}
+async function withFrameSource<T>(
+ input: { source_s3_uri: string; footer_crop_px?: number; width?: number },
+ run: (source: FrameSource) => Promise<T>
+): Promise<T> {
+ const location = parseS3Uri(input.source_s3_uri)
+ const workDir = await fs.mkdtemp(path.join(process.env.VIDEO_WORK_DIR || os.tmpdir(), 'thumb-'))
try {
- await downloadFromS3(source.bucket, source.key, sourcePath)
-
+ const sourcePath = path.join(workDir, 'source.mp4')
+ await downloadFromS3(location.bucket, location.key, sourcePath)
const footer = Math.max(0, Math.floor(input.footer_crop_px ?? 0))
- const width = Math.max(1, Math.floor(input.width ?? 1280))
- // crop before scale: the footer is measured in source pixels.
- const footerCrop = `crop=iw:ih-${footer}:0:0`
-
- const size = await frameSize(sourcePath)
- const letterbox = size
- ? await detectBorder(sourcePath, rawPath, videoTimeS, footerCrop, size.width, size.height - footer)
- : null
- if (letterbox) {
- log.info({ ...letterbox, frame: size }, 'cropping the letterbox around the page')
- }
-
- const crops = letterbox
- ? [footerCrop, `crop=${letterbox.w}:${letterbox.h}:${letterbox.x}:${letterbox.y}`]
- : [footerCrop]
- // Never upscale: a phone-sized page stretched to 1280 is a blurrier, heavier poster.
- const sourceWidth = letterbox?.w ?? size?.width ?? width
- const filters = [...crops, `scale=${Math.min(width, sourceWidth)}:-2`].join(',')
-
- // -ss before -i seeks by keyframe index rather than decoding to the timestamp, which is what
- // keeps this cheap. -frames:v 1 stops after the first frame it lands on.
- const args = [
- '-nostdin',
- '-loglevel',
- 'error',
- '-ss',
- String(videoTimeS),
- '-i',
+ return await run({
+ workDir,
sourcePath,
- '-frames:v',
- '1',
- '-vf',
- filters,
- '-y',
- outputPath,
- ]
-
- try {
- await execFileAsync('ffmpeg', args, { timeout: FFMPEG_TIMEOUT_MS })
- } catch (err) {
- const stderr = (err as { stderr?: string })?.stderr?.slice(0, 500) ?? ''
- log.warn({ err: (err as Error)?.message, stderr }, 'thumbnail extraction failed')
- throw new RasterizationError(
- `ffmpeg could not extract a frame: ${(err as Error)?.message ?? String(err)}`,
- true,
- 'THUMBNAIL_EXTRACT_FAILED',
- err
- )
- }
-
- const stat = await fs.stat(outputPath).catch(() => null)
- if (!stat || stat.size === 0) {
- // A seek past the end of the video exits 0 and writes nothing, so size is the real check.
- throw new RasterizationError(
- `ffmpeg wrote no frame at ${input.video_time_s}s`,
- false,
- 'THUMBNAIL_EMPTY_OUTPUT'
- )
- }
-
- const s3Uri = await uploadToS3(outputPath, input.s3_bucket, input.s3_key_prefix, input.id, 'png')
- return { s3_uri: s3Uri, file_size_bytes: stat.size }
+ // crop before scale: the footer is measured in source pixels.
+ footerCrop: `crop=iw:ih-${footer}:0:0`,
+ size: await frameSize(sourcePath),
+ footer,
+ width: Math.max(1, Math.floor(input.width ?? 1280)),
+ })
} finally {
await fs.rm(workDir, { recursive: true, force: true })
}
}
+
+async function cutFrame(source: FrameSource, videoTimeS: number, outputPath: string): Promise<number> {
+ const { size, footer, footerCrop, width } = source
+ const rawPath = path.join(source.workDir, 'frame.rgb')
+ const letterbox = size
+ ? await detectBorder(source.sourcePath, rawPath, videoTimeS, footerCrop, size.width, size.height - footer)
+ : null
+ if (letterbox) {
+ log.info({ ...letterbox, frame: size }, 'cropping the letterbox around the page')
+ }
+
+ const crops = letterbox
+ ? [footerCrop, `crop=${letterbox.w}:${letterbox.h}:${letterbox.x}:${letterbox.y}`]
+ : [footerCrop]
+ // Never upscale: a phone-sized page stretched to 1280 is a blurrier, heavier poster.
+ const sourceWidth = letterbox?.w ?? size?.width ?? width
+ const filters = [...crops, `scale=${Math.min(width, sourceWidth)}:-2`].join(',')
+
+ // -ss before -i seeks by keyframe index rather than decoding to the timestamp, which is what
+ // keeps this cheap. -frames:v 1 stops after the first frame it lands on.
+ const args = [
+ '-nostdin',
+ '-loglevel',
+ 'error',
+ '-ss',
+ String(videoTimeS),
+ '-i',
+ source.sourcePath,
+ '-frames:v',
+ '1',
+ '-vf',
+ filters,
+ '-y',
+ outputPath,
+ ]
+
+ try {
+ await execFileAsync('ffmpeg', args, { timeout: FFMPEG_TIMEOUT_MS })
+ } catch (err) {
+ const stderr = (err as { stderr?: string })?.stderr?.slice(0, 500) ?? ''
+ log.warn({ err: (err as Error)?.message, stderr }, 'thumbnail extraction failed')
+ throw new RasterizationError(
+ `ffmpeg could not extract a frame: ${(err as Error)?.message ?? String(err)}`,
+ true,
+ 'THUMBNAIL_EXTRACT_FAILED',
+ err
+ )
+ }
+
+ const stat = await fs.stat(outputPath).catch(() => null)
+ if (!stat || stat.size === 0) {
+ // A seek past the end of the video exits 0 and writes nothing, so size is the real check.
+ throw new RasterizationError(`ffmpeg wrote no frame at ${videoTimeS}s`, false, 'THUMBNAIL_EMPTY_OUTPUT')
+ }
+ return stat.size
+}
+
+/**
+ * Cut frames from an already-rendered analysis MP4 and store each as a PNG, downloading the video once.
+ *
+ * No browser, so this costs seconds of CPU rather than a recording load. The crop removes the
+ * burned-in metadata footer, which is an artifact of the analysis render and not part of the page.
+ * A frame past the video's end is left out of the output rather than failing the batch.
+ */
+export async function extractThumbnails(input: ExtractThumbnailsInput): Promise<ExtractThumbnailsOutput> {
+ // Before the download: `-ss NaN` burns every attempt, each pulling the whole MP4 first.
+ const frames = input.frames.map((frame) => ({
+ id: frame.id,
+ videoTimeS: Math.max(0, toFiniteNumber(frame.video_time_s, 'video_time_s')),
+ required: frame.required ?? false,
+ }))
+ return withFrameSource(input, async (source) => {
+ const extracted: ExtractThumbnailsOutput['frames'] = []
+ for (const frame of frames) {
+ const outputPath = path.join(source.workDir, `${frame.id}.png`)
+ let fileSizeBytes: number
+ try {
+ fileSizeBytes = await cutFrame(source, frame.videoTimeS, outputPath)
+ } catch (err) {
+ // A local cut fails the same way on a retry, so an optional frame is skipped rather than retried.
+ if (!frame.required && err instanceof RasterizationError) {
+ log.warn({ id: frame.id, video_time_s: frame.videoTimeS, code: err.code }, 'skipping a frame')
+ continue
+ }
+ throw err
+ }
+ const s3Uri = await uploadToS3(outputPath, input.s3_bucket, input.s3_key_prefix, frame.id, 'png')
+ extracted.push({ id: frame.id, s3_uri: s3Uri, file_size_bytes: fileSizeBytes })
+ await fs.rm(outputPath, { force: true })
+ }
+ return { frames: extracted }
+ })
+}
+
+/** The single-frame shape of media workflows started before the batch path. Delete once they drain. */
+export async function extractThumbnail(input: ExtractThumbnailInput): Promise<ExtractThumbnailOutput> {
+ const { frames } = await extractThumbnails({
+ ...input,
+ frames: [{ video_time_s: input.video_time_s, id: input.id, required: true }],
+ })
+ return { s3_uri: frames[0].s3_uri, file_size_bytes: frames[0].file_size_bytes }
+}
diff --git a/nodejs/src/session-replay/recording-rasterizer/types.ts b/nodejs/src/session-replay/recording-rasterizer/types.ts
index 11ea3bc9b3d6..d4574e6188a0 100644
--- a/nodejs/src/session-replay/recording-rasterizer/types.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/types.ts
@@ -47,6 +47,25 @@ export interface ExtractThumbnailOutput {
file_size_bytes: number
}
+export interface ExtractThumbnailsInput {
+ /** The rendered analysis MP4 to cut the frames from. */
+ source_s3_uri: string
+ /** Each frame's seconds into the analysis video, and the object name it uploads under. A frame that is not
+ * `required` is left out of the output when it cannot be cut, instead of failing the batch. */
+ frames: { video_time_s: number; id: string; required?: boolean }[]
+ /** Pixels of burned-in metadata footer to crop off the bottom before scaling. */
+ footer_crop_px?: number
+ /** Output width; height follows the source aspect ratio. Defaults to 1280. */
+ width?: number
+ s3_bucket: string
+ s3_key_prefix: string
+}
+
+export interface ExtractThumbnailsOutput {
+ /** One entry per frame the video has, in input order. */
+ frames: { id: string; s3_uri: string; file_size_bytes: number }[]
+}
+
/**
* Extends the base InactivityPeriod from the shared protocol with
* recording_ts fields that map segment boundaries to post-processed video
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 499c76e9b70b..b893124299c2 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -203,7 +203,14 @@ class ReplayObservationMediaSerializer(serializers.Serializer):
kind = serializers.ChoiceField(
choices=ReplayObservationMedia.Kind.choices,
read_only=True,
- help_text="`thumbnail` for the single frame that illustrates the observation, `clip` for a short video.",
+ help_text=(
+ "`thumbnail` for the single frame that illustrates the observation, `chapter` for the frame of one "
+ "summary chapter, `clip` for a short video."
+ ),
+ )
+ position = serializers.IntegerField(
+ read_only=True,
+ help_text="Order among media of the same kind. For a `chapter` frame, the index into `model_output.chapters`.",
)
asset_id = serializers.IntegerField(
read_only=True,
@@ -225,6 +232,17 @@ class ReplayObservationMediaSerializer(serializers.Serializer):
)
+class ObservationThumbnailQuerySerializer(serializers.Serializer):
+ chapter = serializers.IntegerField(
+ required=False,
+ min_value=0,
+ help_text=(
+ "Index into the summary's `model_output.chapters`. Serves that chapter's frame instead of the "
+ "observation's thumbnail."
+ ),
+ )
+
+
class ReplayObservationSerializer(serializers.ModelSerializer):
scanner_id = serializers.UUIDField(read_only=True, help_text="The scanner that produced this observation.")
scanner_origin = serializers.ChoiceField(
@@ -349,6 +367,7 @@ class ReplayObservationSerializer(serializers.ModelSerializer):
{
"id": media.id,
"kind": media.kind,
+ "position": media.position,
"asset_id": media.asset_id,
"description": media.description,
"video_start_ms": media.video_start_ms,
@@ -1156,11 +1175,12 @@ class ReplayObservationViewSet(
@extend_schema(
request=None,
+ parameters=[ObservationThumbnailQuerySerializer],
responses={
302: OpenApiResponse(description="Redirect to the image."),
404: OpenApiResponse(
response=ReplayVisionErrorSerializer,
- description="The observation has no thumbnail, or its render has not landed yet.",
+ description="The observation has no such frame, or its render has not landed yet.",
),
},
)
@@ -1172,13 +1192,22 @@ class ReplayObservationViewSet(
)
def thumbnail(self, request: Request, **kwargs: Any) -> HttpResponseBase:
"""Redirect to the frame that illustrates this observation, so a caller with only the observation id can show it."""
+ query = ObservationThumbnailQuerySerializer(data=request.query_params)
+ query.is_valid(raise_exception=True)
+ chapter = query.validated_data.get("chapter")
+ kind, position = (
+ (ReplayObservationMedia.Kind.THUMBNAIL, 0)
+ if chapter is None
+ else (ReplayObservationMedia.Kind.CHAPTER, chapter)
+ )
observation = self.get_object()
# `get_object` already prefetched the observation's media with their assets, so this reads no rows.
media = next(
(
entry
for entry in observation.media.all()
- if entry.kind == ReplayObservationMedia.Kind.THUMBNAIL
+ if entry.kind == kind
+ and entry.position == position
and entry.asset.content_location
# The prefetch joins the asset row directly, so the manager's TTL filter does not apply
# and an expired frame would serve until the sweep deletes it.
@@ -1187,7 +1216,7 @@ class ReplayObservationViewSet(
None,
)
if media is None:
- raise NotFound("This observation has no thumbnail.")
+ raise NotFound("This observation has no thumbnail." if chapter is None else "This chapter has no frame.")
# Object-level access to the recording itself, which the export content endpoint used to apply to
# these bytes before they moved here. A missing row falls back to the resource-level check
# `_scanner_for_url` already ran.
diff --git a/products/replay_vision/backend/migrations/0103_alter_replayobservationmedia_kind.py b/products/replay_vision/backend/migrations/0103_alter_replayobservationmedia_kind.py
new file mode 100644
index 000000000000..04b87ebe3978
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0103_alter_replayobservationmedia_kind.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.17 on 2026-09-30 12:16
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0102_replayscanner_goal"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="replayobservationmedia",
+ name="kind",
+ field=models.CharField(
+ choices=[
+ ("thumbnail", "Thumbnail"),
+ ("clip", "Clip"),
+ ("chapter", "Chapter"),
+ ],
+ max_length=16,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index c53178338ca3..3fb73949e8b6 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0102_replayscanner_goal
+0103_alter_replayobservationmedia_kind
diff --git a/products/replay_vision/backend/models/replay_observation_media.py b/products/replay_vision/backend/models/replay_observation_media.py
index 16238265c2de..5b18e8dbc291 100644
--- a/products/replay_vision/backend/models/replay_observation_media.py
+++ b/products/replay_vision/backend/models/replay_observation_media.py
@@ -13,6 +13,8 @@ class ReplayObservationMedia(TeamScopedRootMixin, UUIDModel):
class Kind(models.TextChoices):
THUMBNAIL = "thumbnail", "Thumbnail"
CLIP = "clip", "Clip"
+ # One frame per summary chapter, at the chapter's index in `position`.
+ CHAPTER = "chapter", "Chapter"
observation = models.ForeignKey("replay_vision.ReplayObservation", on_delete=models.CASCADE, related_name="media")
# CASCADE so the expiry sweep's asset delete takes this row with it, leaving no link to a gone object.
diff --git a/products/replay_vision/backend/scanner_config.py b/products/replay_vision/backend/scanner_config.py
index a8742f467cfc..9451f6154e2b 100644
--- a/products/replay_vision/backend/scanner_config.py
+++ b/products/replay_vision/backend/scanner_config.py
@@ -59,7 +59,7 @@ def scanner_config_error(scanner_type: ScannerType, scanner_config: Any) -> str
except (ValueError, PydanticValidationError):
return "Scanner configuration is invalid."
# The pydantic models ignore extra keys — reject here so typos and junk don't snapshot onto every observation.
- unknown = set(scanner_config) - set(type(scanner).model_fields)
+ unknown = set(scanner_config) - (set(type(scanner).model_fields) - type(scanner).session_fields)
if unknown:
return f"Unknown scanner configuration keys: {', '.join(sorted(unknown))}."
return None
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index f7b308bc4bd1..5f810df61067 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -22,6 +22,7 @@ from products.replay_vision.backend.temporal.activities import (
fetch_session_events_activity,
fetch_session_network_activity,
finalize_evaluation_activity,
+ finalize_observation_media_activity,
finalize_observation_thumbnail_activity,
find_backfill_candidates_activity,
find_scanner_candidates_activity,
@@ -35,6 +36,7 @@ from products.replay_vision.backend.temporal.activities import (
meter_scanner_read_bytes_activity,
pause_backfill_schedule_activity,
prepare_backfill_tick_activity,
+ prepare_observation_media_activity,
prepare_observation_thumbnail_activity,
reap_backfill_schedules_activity,
reap_childless_inline_scanners_activity,
@@ -121,7 +123,9 @@ ACTIVITIES: list[Callable[..., Any]] = [
emit_observation_signals_activity,
cleanup_gemini_file_activity,
prepare_observation_thumbnail_activity,
+ prepare_observation_media_activity,
finalize_observation_thumbnail_activity,
+ finalize_observation_media_activity,
find_scanner_candidates_activity,
count_in_flight_applies_activity,
count_in_flight_by_team_activity,
diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.py
index 23f266e627d3..ec909859fb6a 100644
--- a/products/replay_vision/backend/temporal/activities/__init__.py
+++ b/products/replay_vision/backend/temporal/activities/__init__.py
@@ -39,7 +39,9 @@ from products.replay_vision.backend.temporal.activities.list_stale_scanner_estim
)
from products.replay_vision.backend.temporal.activities.meter_scanner_reads import meter_scanner_read_bytes_activity
from products.replay_vision.backend.temporal.activities.observation_media import (
+ finalize_observation_media_activity,
finalize_observation_thumbnail_activity,
+ prepare_observation_media_activity,
prepare_observation_thumbnail_activity,
)
from products.replay_vision.backend.temporal.activities.observation_state import (
@@ -90,6 +92,7 @@ __all__ = [
"fetch_session_network_activity",
"finalize_evaluation_activity",
"finalize_observation_thumbnail_activity",
+ "finalize_observation_media_activity",
"find_backfill_candidates_activity",
"find_scanner_candidates_activity",
"list_enabled_scanners_activity",
@@ -103,6 +106,7 @@ __all__ = [
"pause_backfill_schedule_activity",
"prepare_backfill_tick_activity",
"prepare_observation_thumbnail_activity",
+ "prepare_observation_media_activity",
"reap_backfill_schedules_activity",
"reap_childless_inline_scanners_activity",
"reap_orphaned_observations_activity",
diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
index 2a72308a970b..acb5636f4969 100644
--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
@@ -145,6 +145,8 @@ class _MissionOutcome:
verification: VerificationRecord | None = None
thumbnail_video_s: int | None = None
key_moment_video_s: int | None = None
+ # The core turn's raw answer, for fields the scanner still has to move onto the session clock.
+ core_response: BaseModel | None = None
@activity.defn
@@ -295,6 +297,8 @@ async def run_scan(
# Built before the preamble so one object decides both the wording and the tool list, which keeps the
# prompt from describing a tool the conversation does not carry.
network_index = build_network_index(network_payload, llm_inputs.metadata.start_time, video_clock)
+ duration_ms = int(llm_inputs.metadata.duration_seconds * 1000)
+ scanner = scanner.bind_session(video_clock, duration_ms)
preamble_text = scanner.preamble(
team_name=team_name,
@@ -321,11 +325,11 @@ async def run_scan(
network_index=network_index,
trace_id=trace_id if trace_id is not None else str(uuid4()),
)
- duration_ms = int(llm_inputs.metadata.duration_seconds * 1000)
finalized = _resolve_citations(outcome.finalized, scanner, duration_ms, video_clock)
finalized = finalized.model_copy(
update={"key_moment_ms": _key_moment_session_ms(outcome.key_moment_video_s, duration_ms, video_clock)}
)
+ finalized = scanner.resolve_session_clock(finalized, outcome.core_response, video_clock, duration_ms)
signals = [_signal_on_session_clock(signal, video_clock) for signal in outcome.signals]
return ScannerCallOutput(
model_output=finalized,
@@ -398,7 +402,7 @@ def _extract_segments(text: str, duration_ms: int, clock: VideoClock) -> tuple[s
# Drop citations past the video's end (a time the model invented) before converting, because the
# clock clamps past its last span and would turn any such value into the recording endpoint. No
# slack: a moment the model can see has a video second inside the video. The marker is stripped either way.
- longest_citable_s = duration_ms / 1000 if clock.is_identity else clock.video_duration_s
+ longest_citable_s = clock.citable_duration_s(duration_ms / 1000)
if longest_citable_s is not None and video_s <= longest_citable_s:
segments.append(ChipSegment(timestamp_ms=clock.video_s_to_session_ms(video_s)))
last_end = match.end()
@@ -600,9 +604,7 @@ async def _run_mission(
step,
validate=functools.partial(
_validate_signal_timestamps,
- duration_seconds=llm_inputs.metadata.duration_seconds
- if video_clock.is_identity
- else video_clock.video_duration_s,
+ duration_seconds=video_clock.citable_duration_s(llm_inputs.metadata.duration_seconds),
),
)
if step.name == STEP_SIGNALS
@@ -659,6 +661,7 @@ async def _run_mission(
verification=verification,
thumbnail_video_s=getattr(step_outputs.get(STEP_CORE), "thumbnail_t", None),
key_moment_video_s=getattr(step_outputs.get(STEP_CORE), "key_moment_t", None),
+ core_response=step_outputs.get(STEP_CORE),
)
diff --git a/products/replay_vision/backend/temporal/activities/observation_media.py b/products/replay_vision/backend/temporal/activities/observation_media.py
index 7ac47845134a..dd2241458f7e 100644
--- a/products/replay_vision/backend/temporal/activities/observation_media.py
+++ b/products/replay_vision/backend/temporal/activities/observation_media.py
@@ -1,6 +1,6 @@
from datetime import timedelta
from typing import Any
-from uuid import uuid4
+from uuid import UUID, uuid4
from django.conf import settings
from django.db import IntegrityError, transaction
@@ -11,6 +11,7 @@ from asgiref.sync import sync_to_async
from temporalio import activity
from temporalio.exceptions import ApplicationError
+from posthog.dataclasses import frozen
from posthog.temporal.session_replay.rasterize_recording.storage_keys import content_location_from_s3_uri
from products.exports.backend.models.exported_asset import ExportedAsset
@@ -22,8 +23,13 @@ from products.replay_vision.backend.temporal.media_types import (
LEGACY_ANALYSIS_FOOTER_HEIGHT_PX,
THUMBNAIL_WIDTH_PX,
ExtractThumbnailActivityInput,
+ ExtractThumbnailsActivityInput,
+ ExtractThumbnailsFrame,
+ FinalizeObservationMediaInputs,
FinalizeObservationThumbnailInputs,
ObservationMediaInputs,
+ PreparedFrame,
+ PrepareObservationMediaOutput,
PrepareObservationThumbnailOutput,
)
from products.replay_vision.backend.temporal.video_clock import VideoClock, video_clock_from_export_context
@@ -33,6 +39,7 @@ logger = structlog.get_logger(__name__)
_MEDIA_EXPIRY = timedelta(days=90)
# The first and last seconds of an analysis video show the page before its CSS applies or while it unloads.
_EDGE_MARGIN_S = 3.0
+_END_MARGIN_S = 1.0
def _footer_crop_px(context: dict[str, Any]) -> int:
@@ -47,6 +54,10 @@ def _media_key_prefix(team_id: int, observation_id: Any) -> str:
return f"replay-vision/media/team-{team_id}/{observation_id}"
+def _session_ms_to_video_s(clock: VideoClock | None, session_ms: int) -> float:
+ return clock.session_ms_to_video_s(session_ms) if clock else session_ms / 1000
+
+
def _first_citation_video_s(model_output: dict[str, Any] | None, clock: VideoClock | None) -> float | None:
"""The first moment the model pointed at, mapped from session time back onto the video the thumbnail is cut from."""
if not model_output:
@@ -55,10 +66,16 @@ def _first_citation_video_s(model_output: dict[str, Any] | None, clock: VideoClo
for segment in model_output.get(field) or []:
if isinstance(segment, dict) and segment.get("kind") == "chip":
session_ms = int(segment.get("timestamp_ms") or 0)
- return clock.session_ms_to_video_s(session_ms) if clock else session_ms / 1000
+ return _session_ms_to_video_s(clock, session_ms)
return None
+def _clamp_to_video(picked_s: float, duration_s: float) -> float:
+ if duration_s <= 2 * _EDGE_MARGIN_S:
+ return duration_s / 2
+ return min(max(picked_s, _EDGE_MARGIN_S), duration_s - _EDGE_MARGIN_S)
+
+
def _pick_video_time_s(
inputs: ObservationMediaInputs, model_output: dict[str, Any] | None, clock: VideoClock | None, duration_s: float
) -> float:
@@ -70,22 +87,42 @@ def _pick_video_time_s(
picked = (start + end) / 2
if picked is None:
picked = duration_s * FALLBACK_THUMBNAIL_FRACTION
- if duration_s <= 2 * _EDGE_MARGIN_S:
- return duration_s / 2
- return min(max(picked, _EDGE_MARGIN_S), duration_s - _EDGE_MARGIN_S)
+ return _clamp_to_video(picked, duration_s)
-@track_activity()
-async def prepare_observation_thumbnail_activity(inputs: ObservationMediaInputs) -> PrepareObservationThumbnailOutput:
- """Pick the frame to cut and create the `is_system` PNG asset the Node activity uploads into."""
- media_inputs = inputs
+def _chapter_frame_times_s(
+ model_output: dict[str, Any] | None, clock: VideoClock | None, duration_s: float
+) -> list[tuple[int, float]]:
+ """Each chapter's thumbnail moment as (chapter index, video seconds), mapped back from the session clock."""
+ chapters = (model_output or {}).get("chapters") or []
+ times: list[tuple[int, float]] = []
+ for position, chapter in enumerate(chapters):
+ if not isinstance(chapter, dict) or not isinstance(chapter.get("thumbnail_ms"), int):
+ continue
+ session_ms = chapter["thumbnail_ms"]
+ # No start margin, which would move a short first chapter's frame into the next one. The end keeps a second,
+ # because a moment in trailing idle maps to the video's last instant and a seek there cuts no frame.
+ video_s = _session_ms_to_video_s(clock, session_ms)
+ times.append((position, min(max(video_s, 0.0), max(0.0, duration_s - _END_MARGIN_S))))
+ return times
+
+
+@frozen
+class _RenderSource:
+ """The analysis video a frame is cut from, and the observation that frame illustrates."""
+
+ source_s3_uri: str
+ context: dict[str, Any]
+ duration_s: float
+ clock: VideoClock | None
+ model_output: dict[str, Any] | None
+
+
+async def _load_render_source(inputs: ObservationMediaInputs) -> _RenderSource:
try:
- asset = await ExportedAsset.objects.aget(pk=media_inputs.analysis_asset_id, team_id=media_inputs.team_id)
+ asset = await ExportedAsset.objects.aget(pk=inputs.analysis_asset_id, team_id=inputs.team_id)
except ExportedAsset.DoesNotExist as error:
- raise ApplicationError(
- f"Analysis asset {media_inputs.analysis_asset_id} is gone", non_retryable=True
- ) from error
+ raise ApplicationError(f"Analysis asset {inputs.analysis_asset_id} is gone", non_retryable=True) from error
if not asset.content_location:
# The analysis render is long finished by now, so an empty location is a lost object, not a race.
raise ApplicationError(f"Analysis asset {asset.id} has no rendered object", non_retryable=True)
@@ -95,110 +132,233 @@ async def prepare_observation_thumbnail_activity(inputs: ObservationMediaInputs)
if duration_s <= 0:
raise ApplicationError(f"Analysis asset {asset.id} has no video duration", non_retryable=True)
- # Read before the asset is created, so a deleted observation leaves no asset behind.
+ # Read before any media asset is created, so a deleted observation leaves no asset behind.
observation = (
- await ReplayObservation.objects.filter(pk=media_inputs.observation_id, team_id=media_inputs.team_id)
+ await ReplayObservation.objects.filter(pk=inputs.observation_id, team_id=inputs.team_id)
.values_list("scanner_result", flat=True)
.afirst()
)
if observation is None:
- raise ApplicationError(f"Observation {media_inputs.observation_id} is gone", non_retryable=True)
+ raise ApplicationError(f"Observation {inputs.observation_id} is gone", non_retryable=True)
scanner_result = observation or {}
- clock = video_clock_from_export_context(context)
- video_time_s = _pick_video_time_s(media_inputs, scanner_result.get("model_output"), clock, duration_s)
- rec_start_ms = clock.video_s_to_session_ms(video_time_s) if clock else None
+ return _RenderSource(
+ source_s3_uri=f"s3://{settings.OBJECT_STORAGE_BUCKET}/{asset.content_location}",
+ context=context,
+ duration_s=duration_s,
+ clock=video_clock_from_export_context(context),
+ model_output=scanner_result.get("model_output"),
+ )
+
- export_context = {
+async def _media_asset(
+ inputs: ObservationMediaInputs, kind: ReplayObservationMedia.Kind, position: int
+) -> ExportedAsset:
+ """Get or create the `is_system` PNG asset for one media slot, so a retried activity leaves no second asset."""
+ export_context: dict[str, Any] = {
# The recording id serves the recording-delete cascade, the observation id every other expiry.
- "session_recording_id": media_inputs.session_id,
- "observation_id": str(media_inputs.observation_id),
- "media_kind": ReplayObservationMedia.Kind.THUMBNAIL.value,
+ "session_recording_id": inputs.session_id,
+ "observation_id": str(inputs.observation_id),
+ "media_kind": kind.value,
}
- # Get-or-create: a retried activity would otherwise leave a second asset and object behind.
+ lookup: dict[str, Any] = {
+ "export_context__session_recording_id": inputs.session_id,
+ "export_context__observation_id": str(inputs.observation_id),
+ "export_context__media_kind": kind.value,
+ }
+ # The observation has one thumbnail, and its assets predate the position key, so only other kinds carry one.
+ if kind != ReplayObservationMedia.Kind.THUMBNAIL:
+ export_context["media_position"] = position
+ lookup["export_context__media_position"] = position
media_asset = (
await ExportedAsset.objects.filter(
- team_id=media_inputs.team_id,
- export_format=ExportedAsset.ExportFormat.PNG,
- export_context__session_recording_id=media_inputs.session_id,
- export_context__observation_id=str(media_inputs.observation_id),
- export_context__media_kind=ReplayObservationMedia.Kind.THUMBNAIL.value,
- is_system=True,
+ team_id=inputs.team_id, export_format=ExportedAsset.ExportFormat.PNG, is_system=True, **lookup
)
.order_by("id")
.afirst()
)
if media_asset is None:
media_asset = await ExportedAsset.objects.acreate(
- team_id=media_inputs.team_id,
+ team_id=inputs.team_id,
export_format=ExportedAsset.ExportFormat.PNG,
export_context=export_context,
# Explicit because the PNG default is six months.
expires_after=now() + _MEDIA_EXPIRY,
is_system=True,
)
+ return media_asset
+
+
+@track_activity()
+async def prepare_observation_media_activity(inputs: ObservationMediaInputs) -> PrepareObservationMediaOutput:
+ """Pick every frame to cut, the thumbnail and one per summary chapter, and create the PNG asset each uploads into."""
+ source = await _load_render_source(inputs)
+ slots = [
+ (
+ ReplayObservationMedia.Kind.THUMBNAIL,
+ 0,
+ _pick_video_time_s(inputs, source.model_output, source.clock, source.duration_s),
+ ),
+ *(
+ (ReplayObservationMedia.Kind.CHAPTER, position, video_time_s)
+ for position, video_time_s in _chapter_frame_times_s(source.model_output, source.clock, source.duration_s)
+ ),
+ ]
+ frames: list[PreparedFrame] = []
+ extract_frames: list[ExtractThumbnailsFrame] = []
+ for kind, position, video_time_s in slots:
+ media_asset = await _media_asset(inputs, kind, position)
+ object_id = str(uuid4())
+ extract_frames.append(
+ ExtractThumbnailsFrame(
+ video_time_s=video_time_s, id=object_id, required=kind == ReplayObservationMedia.Kind.THUMBNAIL
+ )
+ )
+ frames.append(
+ PreparedFrame(
+ kind=kind.value,
+ position=position,
+ media_asset_id=media_asset.id,
+ object_id=object_id,
+ video_start_ms=int(video_time_s * 1000),
+ rec_start_ms=source.clock.video_s_to_session_ms(video_time_s) if source.clock else None,
+ )
+ )
+
+ return PrepareObservationMediaOutput(
+ frames=frames,
+ activity_input=ExtractThumbnailsActivityInput(
+ source_s3_uri=source.source_s3_uri,
+ frames=extract_frames,
+ footer_crop_px=_footer_crop_px(source.context),
+ width=THUMBNAIL_WIDTH_PX,
+ s3_bucket=settings.OBJECT_STORAGE_BUCKET,
+ s3_key_prefix=_media_key_prefix(inputs.team_id, inputs.observation_id),
+ ),
+ )
+
+
+@track_activity()
+async def prepare_observation_thumbnail_activity(inputs: ObservationMediaInputs) -> PrepareObservationThumbnailOutput:
+ """Legacy single-frame prepare, kept for media workflows started before the batch path. Delete once they drain."""
+ source = await _load_render_source(inputs)
+ video_time_s = _pick_video_time_s(inputs, source.model_output, source.clock, source.duration_s)
+ media_asset = await _media_asset(inputs, ReplayObservationMedia.Kind.THUMBNAIL, 0)
return PrepareObservationThumbnailOutput(
media_asset_id=media_asset.id,
activity_input=ExtractThumbnailActivityInput(
- source_s3_uri=f"s3://{settings.OBJECT_STORAGE_BUCKET}/{asset.content_location}",
+ source_s3_uri=source.source_s3_uri,
video_time_s=video_time_s,
- footer_crop_px=_footer_crop_px(context),
+ footer_crop_px=_footer_crop_px(source.context),
width=THUMBNAIL_WIDTH_PX,
s3_bucket=settings.OBJECT_STORAGE_BUCKET,
- s3_key_prefix=_media_key_prefix(media_inputs.team_id, media_inputs.observation_id),
+ s3_key_prefix=_media_key_prefix(inputs.team_id, inputs.observation_id),
id=str(uuid4()),
),
video_start_ms=int(video_time_s * 1000),
- rec_start_ms=rec_start_ms,
+ rec_start_ms=source.clock.video_s_to_session_ms(video_time_s) if source.clock else None,
)
-def _link_media(inputs: FinalizeObservationThumbnailInputs, content_location: str) -> None:
- """Point the asset at the rendered object and link it, as one write.
+@frozen
+class _MediaLink:
+ kind: ReplayObservationMedia.Kind
+ position: int
+ asset_id: int
+ video_start_ms: int
+ rec_start_ms: int | None
+ content_location: str
+
- One transaction, media row first: an observation deleted before the row exists would leave the asset
- with nothing pointing at it, and one deleted after cascades the row away, which expires the asset.
+def _link_media(team_id: int, observation_id: UUID, links: list[_MediaLink]) -> None:
+ """Point each asset at its rendered object and link it, as one write.
+
+ One transaction, media rows first: an observation deleted before the rows exist would leave the assets
+ with nothing pointing at them, and one deleted after cascades the rows away, which expires the assets.
"""
with transaction.atomic():
- media, _ = ReplayObservationMedia.objects.for_team(inputs.team_id, canonical=True).update_or_create(
- observation_id=inputs.observation_id,
- kind=ReplayObservationMedia.Kind.THUMBNAIL,
- position=0,
- defaults={
- "team_id": inputs.team_id,
- "asset_id": inputs.media_asset_id,
- "video_start_ms": inputs.video_start_ms,
- "rec_start_ms": inputs.rec_start_ms,
- },
- )
- ExportedAsset.objects.filter(pk=media.asset_id, team_id=inputs.team_id).update(
- content_location=content_location
- )
-
+ for link in links:
+ media, _ = ReplayObservationMedia.objects.for_team(team_id, canonical=True).update_or_create(
+ observation_id=observation_id,
+ kind=link.kind,
+ position=link.position,
+ defaults={
+ "team_id": team_id,
+ "asset_id": link.asset_id,
+ "video_start_ms": link.video_start_ms,
+ "rec_start_ms": link.rec_start_ms,
+ },
+ )
+ ExportedAsset.objects.filter(pk=media.asset_id, team_id=team_id).update(
+ content_location=link.content_location
+ )
-@track_activity()
-async def finalize_observation_thumbnail_activity(inputs: FinalizeObservationThumbnailInputs) -> None:
- """Point the asset at the uploaded PNG and link it to the observation."""
- try:
- content_location = content_location_from_s3_uri(inputs.result.s3_uri)
- except ValueError as error:
- raise ApplicationError(str(error), non_retryable=True) from error
+async def _link_or_expire(team_id: int, observation_id: UUID, links: list[_MediaLink]) -> bool:
+ """Link the rendered media, or expire it when its observation is gone. Returns whether it was linked."""
try:
# `for_team` resolves the canonical team with a synchronous query of its own.
- await sync_to_async(_link_media)(inputs, content_location)
+ await sync_to_async(_link_media)(team_id, observation_id, links)
except (IntegrityError, ReplayObservation.DoesNotExist):
- # The observation went away between the render and this write, so nothing will point at the object.
+ # The observation went away between the render and this write, so nothing will point at the objects.
# The sweep deletes the stored object only for a row that carries a location.
- await ExportedAsset.objects.filter(pk=inputs.media_asset_id, team_id=inputs.team_id).aupdate(
- content_location=content_location, expires_after=now()
+ for link in links:
+ await ExportedAsset.objects.filter(pk=link.asset_id, team_id=team_id).aupdate(
+ content_location=link.content_location, expires_after=now()
+ )
+ return False
+ return True
+
+
+def _content_location(s3_uri: str) -> str:
+ try:
+ return content_location_from_s3_uri(s3_uri)
+ except ValueError as error:
+ raise ApplicationError(str(error), non_retryable=True) from error
+
+
+@track_activity()
+async def finalize_observation_media_activity(inputs: FinalizeObservationMediaInputs) -> None:
+ """Link every frame the video had to its slot, and expire the assets of the frames it did not have."""
+ extracted = {frame.id: frame for frame in inputs.result.frames}
+ links = [
+ _MediaLink(
+ kind=ReplayObservationMedia.Kind(frame.kind),
+ position=frame.position,
+ asset_id=frame.media_asset_id,
+ video_start_ms=frame.video_start_ms,
+ rec_start_ms=frame.rec_start_ms,
+ content_location=_content_location(extracted[frame.object_id].s3_uri),
+ )
+ for frame in inputs.frames
+ if frame.object_id in extracted
+ ]
+ missing = [frame.media_asset_id for frame in inputs.frames if frame.object_id not in extracted]
+ if missing:
+ await ExportedAsset.objects.filter(pk__in=missing, team_id=inputs.team_id).aupdate(expires_after=now())
+ if links and await _link_or_expire(inputs.team_id, inputs.observation_id, links):
+ logger.info(
+ "replay_vision.media_ready",
+ observation_id=str(inputs.observation_id),
+ frames=len(links),
+ missing=len(missing),
+ file_size_bytes=sum(frame.file_size_bytes for frame in inputs.result.frames),
)
- return
- logger.info(
- "replay_vision.thumbnail_ready",
- observation_id=str(inputs.observation_id),
+
+@track_activity()
+async def finalize_observation_thumbnail_activity(inputs: FinalizeObservationThumbnailInputs) -> None:
+ """Legacy single-frame finalize, kept for media workflows started before the batch path. Delete once they drain."""
+ link = _MediaLink(
+ kind=ReplayObservationMedia.Kind.THUMBNAIL,
+ position=0,
asset_id=inputs.media_asset_id,
- file_size_bytes=inputs.result.file_size_bytes,
+ video_start_ms=inputs.video_start_ms,
+ rec_start_ms=inputs.rec_start_ms,
+ content_location=_content_location(inputs.result.s3_uri),
)
+ await _link_or_expire(inputs.team_id, inputs.observation_id, [link])
diff --git a/products/replay_vision/backend/temporal/media_types.py b/products/replay_vision/backend/temporal/media_types.py
index e359cf1737f3..2f491149a3c7 100644
--- a/products/replay_vision/backend/temporal/media_types.py
+++ b/products/replay_vision/backend/temporal/media_types.py
@@ -1,4 +1,4 @@
-"""Types for the observation media workflow: one thumbnail per succeeded observation."""
+"""Types for the observation media workflow: a thumbnail per succeeded observation, plus a frame per summary chapter."""
import datetime as dt
from uuid import UUID
@@ -16,7 +16,7 @@ FALLBACK_THUMBNAIL_FRACTION = 0.25
MEDIA_WORKFLOW_NAME = "replay-vision-media"
-# Bounds the thumbnail's retry chain, queue wait included.
+# Bounds the frame render's retry chain, queue wait included.
THUMBNAIL_SCHEDULE_TO_CLOSE = dt.timedelta(hours=6)
# Past the retry chain, so a stuck render fails its own activity rather than the whole child.
MEDIA_WORKFLOW_EXECUTION_TIMEOUT = THUMBNAIL_SCHEDULE_TO_CLOSE + dt.timedelta(minutes=30)
@@ -40,7 +40,8 @@ class ObservationMediaInputs(BaseModel, frozen=True):
class ExtractThumbnailActivityInput(BaseModel, frozen=True):
- """Input sent to the Node.js `extract-thumbnail` activity; field names match its TypeScript interface."""
+ """Input to the legacy single-frame `extract-thumbnail` activity, kept for media workflows started before the
+ batch path; field names match its TypeScript interface."""
source_s3_uri: str
video_time_s: float
@@ -70,3 +71,54 @@ class FinalizeObservationThumbnailInputs(BaseModel, frozen=True):
video_start_ms: int
rec_start_ms: int | None
result: ExtractThumbnailActivityOutput
+
+
+class ExtractThumbnailsFrame(BaseModel, frozen=True):
+ video_time_s: float
+ id: str
+ # A required frame fails the batch when it cannot be cut; any other frame is left out instead.
+ required: bool
+
+
+class ExtractThumbnailsActivityInput(BaseModel, frozen=True):
+ """Input sent to the Node.js `extract-thumbnails` activity; field names match its TypeScript interface."""
+
+ source_s3_uri: str
+ frames: list[ExtractThumbnailsFrame]
+ footer_crop_px: int
+ width: int
+ s3_bucket: str
+ s3_key_prefix: str
+
+
+class ExtractedFrame(BaseModel, frozen=True):
+ id: str
+ s3_uri: str
+ file_size_bytes: int
+
+
+class ExtractThumbnailsActivityOutput(BaseModel, frozen=True):
+ frames: list[ExtractedFrame] = Field(default_factory=list)
+
+
+class PreparedFrame(BaseModel, frozen=True):
+ """One media slot the render fills: the observation's thumbnail, or one summary chapter's frame."""
+
+ kind: str
+ position: int
+ media_asset_id: int
+ object_id: str
+ video_start_ms: int
+ rec_start_ms: int | None
+
+
+class PrepareObservationMediaOutput(BaseModel, frozen=True):
+ frames: list[PreparedFrame]
+ activity_input: ExtractThumbnailsActivityInput
+
+
+class FinalizeObservationMediaInputs(BaseModel, frozen=True):
+ team_id: int
+ observation_id: UUID
+ frames: list[PreparedFrame]
+ result: ExtractThumbnailsActivityOutput
diff --git a/products/replay_vision/backend/temporal/media_workflow.py b/products/replay_vision/backend/temporal/media_workflow.py
index 5239f6941e27..1f5d4653d5fd 100644
--- a/products/replay_vision/backend/temporal/media_workflow.py
+++ b/products/replay_vision/backend/temporal/media_workflow.py
@@ -9,7 +9,9 @@ with wf.unsafe.imports_passed_through():
from django.conf import settings
from products.replay_vision.backend.temporal.activities.observation_media import (
+ finalize_observation_media_activity,
finalize_observation_thumbnail_activity,
+ prepare_observation_media_activity,
prepare_observation_thumbnail_activity,
)
from products.replay_vision.backend.temporal.constants import STATE_ACTIVITY_RETRY, STATE_ACTIVITY_SCHEDULE_TO_CLOSE
@@ -17,8 +19,11 @@ with wf.unsafe.imports_passed_through():
MEDIA_WORKFLOW_NAME,
THUMBNAIL_SCHEDULE_TO_CLOSE,
ExtractThumbnailActivityOutput,
+ ExtractThumbnailsActivityOutput,
+ FinalizeObservationMediaInputs,
FinalizeObservationThumbnailInputs,
ObservationMediaInputs,
+ PrepareObservationMediaOutput,
PrepareObservationThumbnailOutput,
)
@@ -33,12 +38,48 @@ _THUMBNAIL_RETRY = common.RetryPolicy(
@wf.defn(name=MEDIA_WORKFLOW_NAME)
class ObservationMediaWorkflow(PostHogWorkflow):
- """Render the media that illustrates one succeeded observation. Today that is a single thumbnail."""
+ """Render the media that illustrates one succeeded observation: its thumbnail and one frame per summary chapter."""
inputs_cls = ObservationMediaInputs
@wf.run
async def run(self, inputs: ObservationMediaInputs) -> None:
+ if not wf.patched("replay-vision-media-batch-2026-10"):
+ await self._render_thumbnail_only(inputs)
+ return
+
+ prepared: PrepareObservationMediaOutput = await wf.execute_activity(
+ prepare_observation_media_activity,
+ inputs,
+ start_to_close_timeout=dt.timedelta(seconds=30),
+ schedule_to_close_timeout=STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
+ retry_policy=STATE_ACTIVITY_RETRY,
+ )
+
+ raw_result = await wf.execute_activity(
+ "extract-thumbnails",
+ prepared.activity_input.model_dump(exclude_none=True),
+ task_queue=settings.RASTERIZATION_TASK_QUEUE,
+ start_to_close_timeout=_THUMBNAIL_TIMEOUT,
+ schedule_to_close_timeout=THUMBNAIL_SCHEDULE_TO_CLOSE,
+ retry_policy=_THUMBNAIL_RETRY,
+ )
+
+ await wf.execute_activity(
+ finalize_observation_media_activity,
+ FinalizeObservationMediaInputs(
+ team_id=inputs.team_id,
+ observation_id=inputs.observation_id,
+ frames=prepared.frames,
+ result=ExtractThumbnailsActivityOutput.model_validate(raw_result),
+ ),
+ start_to_close_timeout=dt.timedelta(seconds=30),
+ schedule_to_close_timeout=STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
+ retry_policy=STATE_ACTIVITY_RETRY,
+ )
+
+ async def _render_thumbnail_only(self, inputs: ObservationMediaInputs) -> None:
+ """The command sequence of media workflows started before the batch path. Delete once they drain."""
prepared: PrepareObservationThumbnailOutput = await wf.execute_activity(
prepare_observation_thumbnail_activity,
inputs,
diff --git a/products/replay_vision/backend/temporal/scanners/base.py b/products/replay_vision/backend/temporal/scanners/base.py
index 520e54d3f402..785b9ed43cd4 100644
--- a/products/replay_vision/backend/temporal/scanners/base.py
+++ b/products/replay_vision/backend/temporal/scanners/base.py
@@ -3,7 +3,7 @@
import re
from collections.abc import Callable
from dataclasses import dataclass, field
-from typing import Annotated, Any, ClassVar, Literal
+from typing import TYPE_CHECKING, Annotated, Any, ClassVar, Literal, Self
from pydantic import BaseModel, Field, field_validator, model_validator
@@ -12,6 +12,9 @@ from posthog.dataclasses import frozen
from products.replay_vision.backend.temporal.conversation import DEFAULT_MAX_TOOL_ITERATIONS
from products.replay_vision.backend.temporal.scanners.prompt_env import render_prompt
+if TYPE_CHECKING:
+ from products.replay_vision.backend.temporal.video_clock import VideoClock
+
# `(t 123)` / `(t 123, 456)` / `(t 12, t 34)` citation markers. The prompt asks for one moment per parens, but the
# model leaks comma-joined variants too, so match leniently (whitespace, comma-joined times, optional repeated `t`).
# Shared by the signal-description stripper below and the chip extractor in `call_scanner_provider` so the two
@@ -19,6 +22,11 @@ from products.replay_vision.backend.temporal.scanners.prompt_env import render_p
TIMESTAMP_CITATION_RE = re.compile(r"\s*\(\s*t\s*(\d+(?:\s*,\s*t?\s*\d+)*)\s*\)")
+def strip_citation_markers(value: str) -> str:
+ """Remove leaked `(t …)` markers, and the double spaces they leave, from a field meant to carry none."""
+ return re.sub(r"\s{2,}", " ", TIMESTAMP_CITATION_RE.sub("", value)).strip()
+
+
# Sited here rather than `temporal/types.py`: `types.py` imports from this module, so siting Segment in types.py would close the cycle.
class TextSegment(BaseModel, frozen=True):
kind: Literal["text"] = "text"
@@ -105,15 +113,14 @@ class SignalFinding(BaseModel, frozen=True):
# The model leaks `(t 123)` markers into this embedded, free-text-searchable field despite the prompt — strip
# them so the timing stays only in start_time/end_time and the prose reads cleanly. Collapse any double space
# the removal (or the model) leaves so the prose stays clean.
- return re.sub(r"\s{2,}", " ", TIMESTAMP_CITATION_RE.sub("", value)).strip()
+ return strip_citation_markers(value)
@field_validator("headline", mode="after")
@classmethod
def _shorten_headline(cls, value: str) -> str:
# Same timestamp-marker leak as the description, plus a hard length bound — the prompt asks for 8 words
# and the model sometimes answers with a sentence, which would reflow the card it lands on.
- cleaned = re.sub(r"\s{2,}", " ", TIMESTAMP_CITATION_RE.sub("", value)).strip()
- return cleaned[:SIGNAL_HEADLINE_MAX_LENGTH].rstrip()
+ return strip_citation_markers(value)[:SIGNAL_HEADLINE_MAX_LENGTH].rstrip()
class SignalsResponse(BaseModel, frozen=True):
@@ -271,6 +278,8 @@ class BaseScanner(BaseModel, frozen=True):
core_step_template: ClassVar[str] = ""
# Names of free-text output fields that may contain `(t <sec>)` citations.
citation_fields: ClassVar[tuple[str, ...]] = ()
+ # Fields `bind_session` sets per scan, which a saved scanner config must never carry.
+ session_fields: ClassVar[frozenset[str]] = frozenset()
# Persisted output class — subclasses override to stamp their `scanner_type` discriminator.
output_cls: ClassVar[type["BaseScannerOutput"] | None] = None
@@ -361,6 +370,16 @@ class BaseScanner(BaseModel, frozen=True):
raise NotImplementedError(f"{type(self).__name__} must set `output_cls`")
return self.output_cls(**llm_response.model_dump())
+ def bind_session(self, clock: "VideoClock", duration_ms: int) -> Self:
+ """This scanner with the facts of one session the prompt needs. Default: none."""
+ return self
+
+ def resolve_session_clock(
+ self, output: "BaseScannerOutput", core_response: BaseModel | None, clock: "VideoClock", duration_ms: int
+ ) -> "BaseScannerOutput":
+ """Move the output's video-clock fields onto the session clock. Default: the output has none."""
+ return output
+
def validate_semantics(self, output: "BaseScannerOutput") -> str | None:
"""Scanner-specific checks beyond Pydantic schema validation; return `None` when valid, otherwise an error string suitable to feed back into a re-prompt."""
return None
diff --git a/products/replay_vision/backend/temporal/scanners/prompts/summarizer_summary_step.jinja b/products/replay_vision/backend/temporal/scanners/prompts/summarizer_summary_step.jinja
index cc93c9493c13..5cfeeda61042 100644
--- a/products/replay_vision/backend/temporal/scanners/prompts/summarizer_summary_step.jinja
+++ b/products/replay_vision/backend/temporal/scanners/prompts/summarizer_summary_step.jinja
@@ -7,6 +7,12 @@ Additional context from the team operating the product being recorded:
{{ cite_in('summary') }}
+Then break the whole recording down into `chapters`: the distinct parts of what the user did, in order, from the start of the video to its end. A new chapter starts where the user moves on to something else: a new page, a new task, a change of approach, or a different section or feature of the same page. Aim for about {{ chapter_target }} chapters when the session has that many distinct parts, and never split where nothing changes on screen. A long stretch on one page still splits by what the user reads or does there, and no chapter should cover several minutes of varied activity with a generic heading like "Browses page". Each chapter gives the video second it starts at, a heading of a few words, and the frame that best shows it. The chapters describe the recording as it happened, even when the context above asks the summary to focus on one area.{% if long_idle_breaks %}
+
+The user was idle for a long time at these points, and the idle time is cut from the video, so the video jumps straight past it. Start a new chapter at each of these video seconds:
+{% for idle_break in long_idle_breaks %}{% set minutes = (idle_break.idle_s / 60) | round | int %}- video second {{ idle_break.video_s }}, after about {{ minutes }} minute{{ "" if minutes == 1 else "s" }} idle
+{% endfor %}{% endif %}
+
{{ rate_notability() }}
{{ mark_key_moment() }}
diff --git a/products/replay_vision/backend/temporal/scanners/summarizer.py b/products/replay_vision/backend/temporal/scanners/summarizer.py
index 854f56664c1f..d99982bbfb6e 100644
--- a/products/replay_vision/backend/temporal/scanners/summarizer.py
+++ b/products/replay_vision/backend/temporal/scanners/summarizer.py
@@ -1,8 +1,11 @@
"""Summarizer scanner: one core turn producing a title + body, embedded whole for free-text search."""
-from typing import Any, ClassVar, Literal
+from collections.abc import Sequence
+from typing import Any, ClassVar, Literal, Self
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, field_validator
+
+from posthog.dataclasses import frozen
from products.replay_vision.backend.models.replay_scanner import ScannerType
from products.replay_vision.backend.temporal.scanners.base import (
@@ -14,8 +17,10 @@ from products.replay_vision.backend.temporal.scanners.base import (
key_moment_field,
notability_field,
notability_reason_field,
+ strip_citation_markers,
thumbnail_field,
)
+from products.replay_vision.backend.temporal.video_clock import IdleStretch, VideoClock
SummaryLength = Literal["short", "medium", "long"]
@@ -26,6 +31,79 @@ _LENGTH_GUIDANCE: dict[SummaryLength, str] = {
}
+CHAPTER_TITLE_MAX_LENGTH = 50
+# Past this many, a breakdown stops being a summary, and every chapter costs a rendered thumbnail frame.
+MAX_CHAPTERS = 20
+MIN_CHAPTER_TARGET = 3
+# Seconds of video per chapter the prompt aims for. Without a target scaled to the length, the model gives a
+# 20-minute session the same two chapters it gives a 1-minute one.
+VIDEO_S_PER_CHAPTER = 90
+
+
+def chapter_target(video_duration_s: float) -> int:
+ return max(MIN_CHAPTER_TARGET, min(MAX_CHAPTERS, round(video_duration_s / VIDEO_S_PER_CHAPTER)))
+
+
+class SummaryChapterResponse(BaseModel, frozen=True):
+ """One part of the recording as the model sees it; the chapter ends where the next one starts."""
+
+ # No bounds or required fields here: one malformed chapter would fail the whole summary, so `resolve_chapters`
+ # repairs or drops it instead.
+ start_t: int | None = Field(
+ default=None,
+ description=(
+ "When this part starts, in whole seconds of video time counted from the start of the video file, the "
+ "same scale you cite moments in, not the footer's `REC_T`. The first chapter starts at 0."
+ ),
+ )
+ title: str = Field(
+ default="",
+ description=(
+ "What the user does in this part, in 2 to 6 words, used as a heading. Name the specific page, section, "
+ "feature or content involved, so two chapters on the same page read differently (e.g. 'Reads surveys "
+ "pricing table', 'Opens install with AI prompt', 'Checkout fails on payment', not 'Browses page'). "
+ "Describe what happened neutrally, whatever the summary focuses on. Never copy text the user typed and "
+ "never name a person. Sentence case, no final period."
+ ),
+ )
+ thumbnail_t: int | None = Field(
+ default=None,
+ description=(
+ "The frame that best shows this part, in whole seconds of video time, inside this chapter. Pick a "
+ "frame where the screen shows the thing itself, not a blank page or a full-page spinner."
+ ),
+ )
+
+ @field_validator("title", mode="after")
+ @classmethod
+ def _shorten_title(cls, value: str) -> str:
+ cleaned = strip_citation_markers(value).rstrip(".")
+ if len(cleaned) <= CHAPTER_TITLE_MAX_LENGTH:
+ return cleaned
+ # Cut at a word boundary so the heading never ends in half a word.
+ return cleaned[: CHAPTER_TITLE_MAX_LENGTH + 1].rsplit(" ", 1)[0].rstrip(" ,;:-")
+
+
+IDLE_CHAPTER_TITLE = "Idle"
+# A shorter pause is part of whatever the user was doing around it, so it stays inside that chapter.
+LONG_IDLE_MS = 60_000
+MAX_IDLE_CHAPTERS = 10
+
+
+class SummaryChapter(BaseModel, frozen=True):
+ """One persisted chapter, on the session clock the player seeks to; chapters tile the recording in order.
+
+ An `idle` chapter is a stretch of at least `LONG_IDLE_MS` the player marked inactive. It comes from the render,
+ never from the model, and has no thumbnail because the analysis video cut it out.
+ """
+
+ kind: Literal["activity", "idle"] = "activity"
+ start_ms: int = Field(ge=0)
+ end_ms: int = Field(ge=0)
+ title: str
+ thumbnail_ms: int | None = Field(default=None, ge=0)
+
+
class SummarizerSummaryResponse(BaseModel, frozen=True):
"""The core turn: title + body summary. Field order is load-bearing — `confidence` last, after the content."""
@@ -37,6 +115,15 @@ class SummarizerSummaryResponse(BaseModel, frozen=True):
),
)
summary: str = Field(description="Body text whose length follows the scanner's configured length.")
+ # Optional so that a model that skips the breakdown still produces a paid-for summary.
+ chapters: list[SummaryChapterResponse] = Field(
+ default_factory=list,
+ description=(
+ "The recording broken down into its distinct parts, in order, covering the whole video, one chapter per "
+ "thing the user did, as many as the instruction asks for. Give a notable moment (an error, a blocker, a "
+ "burst of rage clicks) its own short chapter so it can be jumped to directly."
+ ),
+ )
notability_reason: str | None = notability_reason_field()
notability: float | None = notability_field()
confidence: float = confidence_field()
@@ -51,27 +138,218 @@ class SummarizerOutput(BaseScannerOutput, frozen=True):
title: str = ""
summary: str = ""
summary_segments: list[Segment] = Field(default_factory=list)
+ chapters: list[SummaryChapter] = Field(default_factory=list)
def embedding_document(self) -> EmbeddingDocument | None:
text = summary_embedding_text(self)
return EmbeddingDocument(rendering="summary", text=text) if text else None
+ def to_event_properties(self) -> dict[str, Any]:
+ # A count is enough to chart adoption, and the full list would make every event carry the whole breakdown.
+ properties = super().to_event_properties()
+ del properties["scanner_output_chapters"]
+ properties["scanner_output_chapter_count"] = len(self.chapters)
+ return properties
+
def summary_embedding_text(output: SummarizerOutput) -> str:
"""The single document embedded for search: title and body together, so a query can match either."""
return "\n\n".join(part for part in (output.title.strip(), output.summary.strip()) if part)
+def resolve_chapters(
+ chapters: Sequence[SummaryChapterResponse], duration_ms: int, clock: VideoClock
+) -> list[SummaryChapter]:
+ """Repair the model's chapters into an ordered list that tiles the recording, on the session clock.
+
+ A malformed breakdown is repaired rather than re-prompted, because a re-prompt bills the whole conversation
+ again for a field the scan does not depend on. Each chapter ends where the next one starts, so the list can
+ have neither gaps nor overlaps. The stretches the player marked inactive are then cut out into idle chapters.
+ """
+ video_end_s = clock.citable_duration_s(duration_ms / 1000)
+ if not video_end_s:
+ return []
+ starts: dict[int, SummaryChapterResponse] = {}
+ # A negative start clamps to 0, and a start at or past the video's end is a time the model invented, which
+ # would make an empty chapter.
+ for chapter in chapters:
+ if chapter.start_t is not None and chapter.title and chapter.start_t < video_end_s:
+ starts.setdefault(max(0, chapter.start_t), chapter)
+ kept = sorted(starts.items())[:MAX_CHAPTERS]
+ if not kept:
+ return []
+
+ resolved: list[SummaryChapter] = []
+ for index, (start_t, chapter) in enumerate(kept):
+ start_s = 0.0 if index == 0 else float(start_t)
+ end_s = float(kept[index + 1][0]) if index + 1 < len(kept) else video_end_s
+ thumbnail_t = chapter.thumbnail_t
+ # A pick outside its chapter is dropped here, and `_split_out_idle` falls back to the midpoint.
+ thumbnail_ms = (
+ clock.video_s_to_session_ms(thumbnail_t)
+ if thumbnail_t is not None and start_s <= thumbnail_t < end_s
+ else None
+ )
+ resolved.append(
+ SummaryChapter(
+ # Pinned, because the render's first kept stretch can start after the session does.
+ start_ms=0 if index == 0 else clock.video_s_to_session_ms(start_s),
+ # The last chapter runs to the end of the session, which can be past the video's end when the render cut trailing inactivity.
+ end_ms=clock.video_s_to_session_ms(end_s) if index + 1 < len(kept) else duration_ms,
+ title=chapter.title,
+ thumbnail_ms=thumbnail_ms,
+ )
+ )
+ return _split_out_idle(resolved, _long_idle(clock, duration_ms))
+
+
+@frozen
+class IdleBreak:
+ """A long idle stretch as the prompt names it: where the video resumes, and how long the user was away."""
+
+ video_s: int
+ idle_s: int
+
+
+def long_idle_breaks(clock: VideoClock, duration_ms: int) -> tuple[IdleBreak, ...]:
+ """One break per long idle between two stretches of activity.
+
+ Idle at the very start or end of the session has no activity on one side, so it cannot split a chapter.
+ """
+ return tuple(
+ IdleBreak(
+ video_s=int(clock.session_ms_to_video_s(stretch.end_ms)),
+ idle_s=(stretch.end_ms - stretch.start_ms) // 1000,
+ )
+ for stretch in _long_idle(clock, duration_ms)
+ if stretch.start_ms > 0 and stretch.end_ms < duration_ms
+ )
+
+
+def _long_idle(clock: VideoClock, duration_ms: int) -> list[IdleStretch]:
+ """The long idle stretches, at most the `MAX_IDLE_CHAPTERS` longest, in order.
+
+ Each one adds an idle chapter and can split another, so the bound keeps the timeline and its frames bounded.
+ """
+ long_idle = [s for s in clock.inactive_session_ms(duration_ms) if s.end_ms - s.start_ms >= LONG_IDLE_MS]
+ longest = sorted(long_idle, key=lambda s: s.start_ms - s.end_ms)[:MAX_IDLE_CHAPTERS]
+ return sorted(longest, key=lambda s: s.start_ms)
+
+
+# The model cites whole video seconds, so a boundary it meant to put at a cut can land a second or two past it.
+_MIN_ACTIVITY_FRAGMENT_MS = 3_000
+
+
+@frozen(frozen=False)
+class _Piece:
+ """A stretch of the session while idle stretches are cut out; `source` is None for an idle one."""
+
+ start_ms: int
+ end_ms: int
+ source: SummaryChapter | None
+ # True for a piece an idle stretch cut off a chapter; a whole chapter is never merged away, however short.
+ fragment: bool = False
+
+
+def _split_out_idle(chapters: list[SummaryChapter], idle: list[IdleStretch]) -> list[SummaryChapter]:
+ """Cut each inactive stretch out of the chapters it overlaps and put an idle chapter in its place.
+
+ A chapter that an idle stretch splits keeps its title on both sides. A fragment too short to be a real
+ part of the session joins the neighbouring activity chapter, or the idle stretch when it has none.
+ """
+ pieces: list[_Piece] = []
+ for chapter in chapters:
+ cursor = chapter.start_ms
+ cut = False
+ for stretch in idle:
+ start, end = max(stretch.start_ms, chapter.start_ms), min(stretch.end_ms, chapter.end_ms)
+ if end <= start:
+ continue
+ if start > cursor:
+ pieces.append(_Piece(start_ms=cursor, end_ms=start, source=chapter, fragment=True))
+ pieces.append(_Piece(start_ms=start, end_ms=end, source=None))
+ cursor, cut = end, True
+ if cursor < chapter.end_ms:
+ pieces.append(_Piece(start_ms=cursor, end_ms=chapter.end_ms, source=chapter, fragment=cut))
+
+ index = 0
+ while index < len(pieces):
+ piece = pieces[index]
+ if not piece.fragment or piece.end_ms - piece.start_ms >= _MIN_ACTIVITY_FRAGMENT_MS:
+ index += 1
+ continue
+ before = pieces[index - 1] if index > 0 else None
+ after = pieces[index + 1] if index + 1 < len(pieces) else None
+ if after is not None and after.source is not None:
+ after.start_ms = piece.start_ms
+ elif before is not None and before.source is not None:
+ before.end_ms = piece.end_ms
+ else:
+ piece.source = None
+ index += 1
+ continue
+ pieces.pop(index)
+
+ resolved: list[SummaryChapter] = []
+ for piece in pieces:
+ if piece.source is None:
+ if resolved and resolved[-1].kind == "idle":
+ resolved[-1] = resolved[-1].model_copy(update={"end_ms": piece.end_ms})
+ else:
+ resolved.append(
+ SummaryChapter(kind="idle", start_ms=piece.start_ms, end_ms=piece.end_ms, title=IDLE_CHAPTER_TITLE)
+ )
+ continue
+ thumbnail_ms = piece.source.thumbnail_ms
+ if thumbnail_ms is None or not piece.start_ms <= thumbnail_ms < piece.end_ms:
+ thumbnail_ms = (piece.start_ms + piece.end_ms) // 2
+ resolved.append(
+ SummaryChapter(
+ start_ms=piece.start_ms, end_ms=piece.end_ms, title=piece.source.title, thumbnail_ms=thumbnail_ms
+ )
+ )
+ return resolved
+
+
class SummarizerScanner(BaseScanner, frozen=True):
scanner_type: Literal[ScannerType.SUMMARIZER] = ScannerType.SUMMARIZER
core_step_template: ClassVar[str] = "summarizer_summary_step.jinja"
citation_fields: ClassVar[tuple[str, ...]] = ("summary",)
output_cls: ClassVar[type[BaseScannerOutput]] = SummarizerOutput
length: SummaryLength = "medium"
+ # (video second the video resumes at, idle seconds) per long idle stretch, set per session before the scan runs.
+ long_idle_breaks: tuple[IdleBreak, ...] = ()
+ chapter_target: int = MIN_CHAPTER_TARGET
+ session_fields: ClassVar[frozenset[str]] = frozenset({"long_idle_breaks", "chapter_target"})
@property
def llm_response_schema(self) -> type[BaseModel]:
return SummarizerSummaryResponse
def prompt_context(self) -> dict[str, Any]:
- return {"length_guidance": _LENGTH_GUIDANCE[self.length]}
+ return {
+ "length_guidance": _LENGTH_GUIDANCE[self.length],
+ "long_idle_breaks": self.long_idle_breaks,
+ "chapter_target": self.chapter_target,
+ }
+
+ def bind_session(self, clock: VideoClock, duration_ms: int) -> Self:
+ # The video has the idle time cut out, so the model cannot see a long break unless the prompt names it.
+ return self.model_copy(
+ update={
+ "long_idle_breaks": long_idle_breaks(clock, duration_ms),
+ "chapter_target": chapter_target(clock.citable_duration_s(duration_ms / 1000) or 0),
+ }
+ )
+
+ def resolve_session_clock(
+ self, output: BaseScannerOutput, core_response: BaseModel | None, clock: VideoClock, duration_ms: int
+ ) -> BaseScannerOutput:
+ if not isinstance(output, SummarizerOutput):
+ return output
+ chapters = getattr(core_response, "chapters", ())
+ return output.model_copy(update={"chapters": resolve_chapters(chapters, duration_ms, clock)})
+
+ def finalize(self, llm_response: BaseModel) -> BaseScannerOutput:
+ # Chapters join the output in the provider activity, which holds the clock that moves them onto session time.
+ return SummarizerOutput(**llm_response.model_dump(exclude={"chapters"}))
diff --git a/products/replay_vision/backend/temporal/video_clock.py b/products/replay_vision/backend/temporal/video_clock.py
index 6fc9ad4ae0aa..a8c289f765af 100644
--- a/products/replay_vision/backend/temporal/video_clock.py
+++ b/products/replay_vision/backend/temporal/video_clock.py
@@ -10,6 +10,7 @@ clock. `clipTimeForMoment` in products/desktop/packages/ui/src/features/inbox/co
is the TypeScript sibling of this mapping. The two have to change together.
"""
+from dataclasses import replace
from typing import Any
from posthog.dataclasses import frozen
@@ -26,6 +27,14 @@ class ActiveSpan:
video_to_s: float
+@frozen
+class IdleStretch:
+ """One stretch the player marked inactive, in session milliseconds."""
+
+ start_ms: int
+ end_ms: int
+
+
@frozen
class VideoClock:
"""Maps session seconds to video seconds and back, across the cuts the rasterizer made.
@@ -34,6 +43,8 @@ class VideoClock:
"""
spans: tuple[ActiveSpan, ...]
+ # The stretches the player marked inactive, as (from, to) session seconds. The render cut them from the video.
+ inactive: tuple[tuple[float, float], ...] = ()
@property
def is_identity(self) -> bool:
@@ -44,12 +55,29 @@ class VideoClock:
"""Length of the rendered video, which bounds any position the model can cite."""
return self.spans[-1].video_to_s if self.spans else None
+ def citable_duration_s(self, session_duration_s: float | None) -> float | None:
+ """The last second the model can cite: the video's length, or the session's when nothing was cut."""
+ return session_duration_s if self.is_identity else self.video_duration_s
+
def session_ms_to_video_s(self, session_ms: int) -> float:
return self._project(session_ms / 1000, to_video=True)
def video_s_to_session_ms(self, video_s: float) -> int:
return int(self._project(video_s, to_video=False) * 1000)
+ def inactive_session_ms(self, duration_ms: int) -> list[IdleStretch]:
+ """The inactive stretches, clipped to the session, in order and merged where they touch."""
+ merged: list[IdleStretch] = []
+ for from_s, to_s in sorted(self.inactive):
+ stretch = IdleStretch(start_ms=max(0, int(from_s * 1000)), end_ms=min(duration_ms, int(to_s * 1000)))
+ if stretch.end_ms <= stretch.start_ms:
+ continue
+ if merged and stretch.start_ms <= merged[-1].end_ms:
+ merged[-1] = replace(merged[-1], end_ms=max(merged[-1].end_ms, stretch.end_ms))
+ else:
+ merged.append(stretch)
+ return merged
+
def video_s_to_session_s(self, video_s: float) -> int:
return int(self._project(video_s, to_video=False))
@@ -107,4 +135,5 @@ def video_clock_from_export_context(export_context: dict[str, Any] | None) -> Vi
if p.active and p.ts_to_s is not None and p.recording_ts_from_s is not None and p.recording_ts_to_s is not None
]
spans.sort(key=lambda span: span.video_from_s)
- return VideoClock(spans=tuple(spans))
+ inactive = tuple((p.ts_from_s, p.ts_to_s) for p in periods if not p.active and p.ts_to_s is not None)
+ return VideoClock(spans=tuple(spans), inactive=inactive)
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 928d4f5a8cd0..87e8bc092ba0 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -455,6 +455,12 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
{"prompt": "p", "alow_inconclusive": True},
"Unknown scanner configuration keys: alow_inconclusive.",
),
+ (
+ "per_scan_field_in_config",
+ ScannerType.SUMMARIZER,
+ {"prompt": "p", "chapter_target": 50},
+ "Unknown scanner configuration keys: chapter_target.",
+ ),
]
)
def test_validation_returns_specific_message_per_invalid_config(
diff --git a/products/replay_vision/backend/tests/test_observation_media.py b/products/replay_vision/backend/tests/test_observation_media.py
index 4380ea6361fd..676401fd0198 100644
--- a/products/replay_vision/backend/tests/test_observation_media.py
+++ b/products/replay_vision/backend/tests/test_observation_media.py
@@ -1,5 +1,6 @@
from datetime import datetime, timedelta
from typing import Any
+from uuid import UUID
import pytest
from posthog.test.base import BaseTest
@@ -26,13 +27,16 @@ from products.replay_vision.backend.models.replay_scanner import ReplayScanner,
from products.replay_vision.backend.temporal.activities.observation_media import (
_footer_crop_px,
_pick_video_time_s,
- finalize_observation_thumbnail_activity,
- prepare_observation_thumbnail_activity,
+ finalize_observation_media_activity,
+ prepare_observation_media_activity,
)
from products.replay_vision.backend.temporal.media_types import (
- ExtractThumbnailActivityOutput,
- FinalizeObservationThumbnailInputs,
+ ExtractedFrame,
+ ExtractThumbnailsActivityOutput,
+ FinalizeObservationMediaInputs,
ObservationMediaInputs,
+ PreparedFrame,
+ PrepareObservationMediaOutput,
)
from products.replay_vision.backend.tests.helpers import snapshot_for
@@ -79,8 +83,26 @@ class TestObservationMedia(BaseTest):
fields.update(overrides)
return ObservationMediaInputs(**fields)
- def _prepare(self, **overrides: Any) -> Any:
- return async_to_sync(prepare_observation_thumbnail_activity)(self._inputs(**overrides))
+ def _prepare(self, **overrides: Any) -> PrepareObservationMediaOutput:
+ return async_to_sync(prepare_observation_media_activity)(self._inputs(**overrides))
+
+ def _finalize(
+ self, prepared: PrepareObservationMediaOutput, rendered: list[PreparedFrame], observation_id: UUID
+ ) -> None:
+ prefix = f"s3://{settings.OBJECT_STORAGE_BUCKET}/replay-vision/media/team-{self.team.id}/{observation_id}"
+ async_to_sync(finalize_observation_media_activity)(
+ FinalizeObservationMediaInputs(
+ team_id=self.team.id,
+ observation_id=observation_id,
+ frames=prepared.frames,
+ result=ExtractThumbnailsActivityOutput(
+ frames=[
+ ExtractedFrame(id=f.object_id, s3_uri=f"{prefix}/{f.object_id}.png", file_size_bytes=4096)
+ for f in rendered
+ ]
+ ),
+ )
+ )
def test_media_object_is_written_outside_the_exports_prefix(self) -> None:
prepared = self._prepare()
@@ -88,7 +110,7 @@ class TestObservationMedia(BaseTest):
assert prepared.activity_input.s3_key_prefix == (
f"replay-vision/media/team-{self.team.id}/{self.observation.id}"
)
- asset = ExportedAsset.objects.get(pk=prepared.media_asset_id)
+ asset = ExportedAsset.objects.get(pk=prepared.frames[0].media_asset_id)
assert asset.is_system is True
assert (asset.export_context or {})["observation_id"] == str(self.observation.id)
assert (asset.export_context or {})["session_recording_id"] == self.session_id
@@ -103,7 +125,7 @@ class TestObservationMedia(BaseTest):
prepared = self._prepare(thumbnail_video_s=70, signal_video_times=[(40, 60)])
- assert prepared.activity_input.video_time_s == 70.0
+ assert prepared.activity_input.frames[0].video_time_s == 70.0
@parameterized.expand(
[
@@ -120,8 +142,8 @@ class TestObservationMedia(BaseTest):
prepared = self._prepare(signal_video_times=signals)
- assert prepared.activity_input.video_time_s == expected_s
- assert prepared.video_start_ms == int(expected_s * 1000)
+ assert prepared.activity_input.frames[0].video_time_s == expected_s
+ assert prepared.frames[0].video_start_ms == int(expected_s * 1000)
def test_a_missing_analysis_asset_fails_without_retrying(self) -> None:
analysis_asset_id = self.analysis_asset.id
@@ -132,48 +154,56 @@ class TestObservationMedia(BaseTest):
assert caught.value.non_retryable is True
- def test_finalize_links_the_rendered_object_to_the_observation(self) -> None:
- prepared = self._prepare()
+ def test_one_render_links_the_thumbnail_and_each_chapter_frame_the_video_had(self) -> None:
+ chapters = [
+ {"start_ms": 0, "end_ms": 2_000, "title": "Opens the app", "thumbnail_ms": 1_000},
+ {"start_ms": 30_000, "end_ms": 70_000, "title": "Edits a form", "thumbnail_ms": 50_000},
+ {"start_ms": 70_000, "end_ms": 100_000, "title": "Leaves", "thumbnail_ms": 100_000},
+ ]
+ self.observation.scanner_result = {"model_output": {"scanner_type": "summarizer", "chapters": chapters}}
+ self.observation.save()
- async_to_sync(finalize_observation_thumbnail_activity)(
- FinalizeObservationThumbnailInputs(
- team_id=self.team.id,
- observation_id=self.observation.id,
- media_asset_id=prepared.media_asset_id,
- video_start_ms=prepared.video_start_ms,
- rec_start_ms=prepared.rec_start_ms,
- result=ExtractThumbnailActivityOutput(
- s3_uri=f"s3://{settings.OBJECT_STORAGE_BUCKET}/replay-vision/media/team-{self.team.id}/{self.observation.id}/x.png",
- file_size_bytes=4096,
- ),
- )
+ prepared = self._prepare()
+ assert [(f.kind, f.position) for f in prepared.frames] == [
+ ("thumbnail", 0),
+ ("chapter", 0),
+ ("chapter", 1),
+ ("chapter", 2),
+ ]
+ # The thumbnail keeps the video-wide edge margin; a chapter frame stays inside its own chapter instead.
+ assert [f.video_time_s for f in prepared.activity_input.frames] == [25.0, 1.0, 50.0, 99.0]
+ assert [f.required for f in prepared.activity_input.frames] == [True, False, False, False]
+ assert len({f.media_asset_id for f in prepared.frames}) == 4
+ # A retried prepare reuses each slot's asset rather than leaving a second one behind.
+ again = self._prepare()
+ assert [f.media_asset_id for f in again.frames] == [f.media_asset_id for f in prepared.frames]
+
+ self._finalize(prepared, rendered=prepared.frames[:3], observation_id=self.observation.id)
+
+ linked = ReplayObservationMedia.objects.for_team(self.team.id).filter(observation_id=self.observation.id)
+ assert sorted((m.kind, m.position, m.asset_id) for m in linked) == sorted(
+ (f.kind, f.position, f.media_asset_id) for f in prepared.frames[:3]
)
+ assert all((m.asset.content_location or "").startswith("replay-vision/media/") for m in linked)
+ missing_asset = ExportedAsset.objects_including_ttl_deleted.get(pk=prepared.frames[3].media_asset_id)
+ assert missing_asset.expires_after is not None and missing_asset.expires_after <= timezone.now()
+
+ def test_an_observation_without_chapters_renders_only_its_thumbnail(self) -> None:
+ self.observation.scanner_result = {"model_output": {"scanner_type": "monitor", "verdict": "yes"}}
+ self.observation.save()
+
+ prepared = self._prepare()
- media = ReplayObservationMedia.objects.for_team(self.team.id).get(observation_id=self.observation.id)
- assert media.kind == ReplayObservationMedia.Kind.THUMBNAIL
- assert media.asset_id == prepared.media_asset_id
- assert (media.asset.content_location or "").startswith("replay-vision/media/")
+ assert [(f.kind, f.position) for f in prepared.frames] == [("thumbnail", 0)]
def test_an_observation_deleted_mid_render_expires_the_asset_with_its_location(self) -> None:
prepared = self._prepare()
observation_id = self.observation.id
self.observation.delete()
- async_to_sync(finalize_observation_thumbnail_activity)(
- FinalizeObservationThumbnailInputs(
- team_id=self.team.id,
- observation_id=observation_id,
- media_asset_id=prepared.media_asset_id,
- video_start_ms=prepared.video_start_ms,
- rec_start_ms=prepared.rec_start_ms,
- result=ExtractThumbnailActivityOutput(
- s3_uri=f"s3://{settings.OBJECT_STORAGE_BUCKET}/replay-vision/media/team-{self.team.id}/{observation_id}/x.png",
- file_size_bytes=4096,
- ),
- )
- )
+ self._finalize(prepared, rendered=prepared.frames, observation_id=observation_id)
- asset = ExportedAsset.objects_including_ttl_deleted.get(pk=prepared.media_asset_id)
+ asset = ExportedAsset.objects_including_ttl_deleted.get(pk=prepared.frames[0].media_asset_id)
assert asset.expires_after is not None
assert (asset.content_location or "").startswith("replay-vision/media/")
diff --git a/products/replay_vision/backend/tests/test_observation_thumbnail_api.py b/products/replay_vision/backend/tests/test_observation_thumbnail_api.py
index 8fb395dc6be7..b48ffca13cdb 100644
--- a/products/replay_vision/backend/tests/test_observation_thumbnail_api.py
+++ b/products/replay_vision/backend/tests/test_observation_thumbnail_api.py
@@ -28,7 +28,13 @@ class TestObservationThumbnail(_VisionAPITestCase):
def _url(self) -> str:
return f"{self.observations_url(self.scanner.id)}{self.observation.id}/thumbnail/"
- def _add_thumbnail(self, *, rendered: bool) -> ExportedAsset:
+ def _add_thumbnail(
+ self,
+ *,
+ rendered: bool,
+ kind: ReplayObservationMedia.Kind = ReplayObservationMedia.Kind.THUMBNAIL,
+ position: int = 0,
+ ) -> ExportedAsset:
asset = ExportedAsset.objects.create(
team=self.team,
export_format=ExportedAsset.ExportFormat.PNG,
@@ -42,8 +48,8 @@ class TestObservationThumbnail(_VisionAPITestCase):
team_id=self.team.id,
observation=self.observation,
asset=asset,
- kind=ReplayObservationMedia.Kind.THUMBNAIL,
- position=0,
+ kind=kind,
+ position=position,
video_start_ms=1000,
)
return asset
@@ -57,6 +63,13 @@ class TestObservationThumbnail(_VisionAPITestCase):
# The response redirects to a signed, expiring URL, so a cached one would outlive its target.
assert response.headers["Cache-Control"] == "no-store"
+ def test_a_chapter_frame_is_served_only_for_its_chapter(self) -> None:
+ self._add_thumbnail(rendered=True, kind=ReplayObservationMedia.Kind.CHAPTER, position=1)
+
+ assert self.client.get(self._url(), {"chapter": 1}).status_code in (200, 302)
+ assert self.client.get(self._url(), {"chapter": 2}).status_code == 404
+ assert self.client.get(self._url()).status_code == 404
+
def test_the_export_endpoint_will_not_serve_an_observations_media(self) -> None:
# That endpoint authorizes a recording export by the recording alone, which is weaker than the
# scanner and experiment checks this observation's own endpoint applies.
diff --git a/products/replay_vision/backend/tests/test_scanners.py b/products/replay_vision/backend/tests/test_scanners.py
index b6f0c81ccbe4..e7443d36a075 100644
--- a/products/replay_vision/backend/tests/test_scanners.py
+++ b/products/replay_vision/backend/tests/test_scanners.py
@@ -26,7 +26,13 @@ from products.replay_vision.backend.temporal.scanners.base import (
SignalFinding,
SignalsResponse,
)
-from products.replay_vision.backend.temporal.scanners.summarizer import summary_embedding_text
+from products.replay_vision.backend.temporal.scanners.summarizer import (
+ IdleBreak,
+ SummaryChapter,
+ SummaryChapterResponse,
+ chapter_target,
+ summary_embedding_text,
+)
from products.replay_vision.backend.temporal.types import EventTable, ScannerCallOutput
@@ -734,7 +740,12 @@ class TestSummarizerScanner:
assert "3-5 paragraphs" in long.core_steps()[0].instruction
def test_output_round_trip(self) -> None:
- out = SummarizerOutput(title="User onboarded", summary="They walked through the demo.", confidence=0.9)
+ out = SummarizerOutput(
+ title="User onboarded",
+ summary="They walked through the demo.",
+ confidence=0.9,
+ chapters=[SummaryChapter(start_ms=0, end_ms=12_000, title="Opens the demo", thumbnail_ms=6_000)],
+ )
round_tripped = SummarizerOutput.model_validate_json(out.model_dump_json())
assert round_tripped == out
@@ -764,6 +775,23 @@ class TestSummarizerScannerSteps:
)
assert "naming convention" in scanner.core_steps()[0].instruction
+ @pytest.mark.parametrize("video_s,expected", [(60, 3), (864, 10), (7200, 20)])
+ def test_chapter_target_scales_with_the_video_length(self, video_s: float, expected: int) -> None:
+ assert chapter_target(video_s) == expected
+ scanner = SummarizerScanner(prompt="p", chapter_target=chapter_target(video_s))
+ assert f"Aim for about {expected} chapters" in scanner.core_steps()[0].instruction
+
+ def test_summary_step_names_the_long_idle_breaks_the_video_cut(self) -> None:
+ scanner = SummarizerScanner(prompt="p")
+ assert "idle for a long time" not in scanner.core_steps()[0].instruction
+
+ with_breaks = scanner.model_copy(
+ update={"long_idle_breaks": (IdleBreak(video_s=92, idle_s=240), IdleBreak(video_s=300, idle_s=70))}
+ )
+ instruction = with_breaks.core_steps()[0].instruction
+ assert "video second 92, after about 4 minutes idle" in instruction
+ assert "video second 300, after about 1 minute idle" in instruction
+
def test_summary_step_opts_into_citations(self) -> None:
scanner = scanner_from_db(
_build_replay_scanner(scanner_type=ScannerType.SUMMARIZER, scanner_config={"prompt": "p"})
@@ -775,12 +803,32 @@ class TestSummarizerScannerSteps:
scanner = scanner_from_db(
_build_replay_scanner(scanner_type=ScannerType.SUMMARIZER, scanner_config={"prompt": "p"})
)
- summary = SummarizerSummaryResponse(title="Onboarding", summary="Walked through demo", confidence=0.8)
+ summary = SummarizerSummaryResponse(
+ title="Onboarding",
+ summary="Walked through demo",
+ confidence=0.8,
+ chapters=[SummaryChapterResponse(start_t=0, title="Opens the demo", thumbnail_t=3)],
+ )
out, signals = scanner.assemble({"core": summary})
assert isinstance(out, SummarizerOutput)
assert (out.title, out.summary, out.confidence) == ("Onboarding", "Walked through demo", 0.8)
+ assert out.chapters == []
assert signals == []
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ ("Checkout fails (t 42)", "Checkout fails"),
+ ("Browses the pricing page.", "Browses the pricing page"),
+ (
+ "Walks through every single step of the onboarding flow today",
+ "Walks through every single step of the onboarding",
+ ),
+ ],
+ )
+ def test_chapter_title_is_a_short_plain_heading(self, raw: str, expected: str) -> None:
+ assert SummaryChapterResponse(start_t=0, title=raw).title == expected
+
def test_output_round_trip_ignores_legacy_facet_fields(self) -> None:
# Rows written by the old facet turn still load; the extra keys are dropped rather than rejected.
stored = {
@@ -835,6 +883,20 @@ class TestToEventProperties:
assert props["scanner_output_notability"] is None
assert props["scanner_output_notability_reason"] is None
+ def test_summary_chapters_flatten_to_a_count(self) -> None:
+ out = SummarizerOutput(
+ title="t",
+ summary="s",
+ confidence=0.9,
+ chapters=[
+ SummaryChapter(start_ms=0, end_ms=5_000, title="Opens app", thumbnail_ms=2_000),
+ SummaryChapter(start_ms=5_000, end_ms=9_000, title="Leaves", thumbnail_ms=7_000),
+ ],
+ )
+ props = out.to_event_properties()
+ assert props["scanner_output_chapter_count"] == 2
+ assert "scanner_output_chapters" not in props
+
def test_excludes_scanner_type_discriminator(self) -> None:
# `scanner_type` lives at the top-level event property; flattening it would duplicate.
out = MonitorOutput(verdict="no", reasoning="nope", confidence=0.5)
diff --git a/products/replay_vision/backend/tests/test_video_clock.py b/products/replay_vision/backend/tests/test_video_clock.py
index ba036b33454f..98769c4aed77 100644
--- a/products/replay_vision/backend/tests/test_video_clock.py
+++ b/products/replay_vision/backend/tests/test_video_clock.py
@@ -1,3 +1,4 @@
+from dataclasses import replace
from types import SimpleNamespace
import pytest
@@ -12,7 +13,18 @@ from products.replay_vision.backend.temporal.activities.call_scanner_provider im
)
from products.replay_vision.backend.temporal.errors import ScannerFailureError
from products.replay_vision.backend.temporal.scanners.base import ChipSegment
-from products.replay_vision.backend.temporal.video_clock import VideoClock, video_clock_from_export_context
+from products.replay_vision.backend.temporal.scanners.summarizer import (
+ IdleBreak,
+ SummaryChapterResponse,
+ long_idle_breaks,
+ resolve_chapters,
+)
+from products.replay_vision.backend.temporal.video_clock import (
+ ActiveSpan,
+ IdleStretch,
+ VideoClock,
+ video_clock_from_export_context,
+)
# 0-58s kept, 58-62s cut, 62-80s kept: the second stretch starts 4s behind the session clock.
_PERIODS = [
@@ -100,6 +112,28 @@ class TestMissingCutMapIsRefusedUnlessProvablyUncut:
self._load(export_context, session_duration_s)
+def test_the_first_chapter_starts_with_the_session_when_the_render_starts_later() -> None:
+ clock = VideoClock(
+ spans=(ActiveSpan(session_from_s=0.333, session_to_s=60.0, video_from_s=0.0, video_to_s=59.667),)
+ )
+ resolved = resolve_chapters([_chapter(0, "Browses")], 60_000, clock)
+ assert (resolved[0].start_ms, resolved[0].end_ms) == (0, 60_000)
+
+
+def test_only_long_idle_between_activity_is_named_to_the_model() -> None:
+ clock = VideoClock(spans=(), inactive=((0, 90), (100, 130), (200, 300), (320, 400)))
+ assert long_idle_breaks(clock, 400_000) == (IdleBreak(video_s=300, idle_s=100),)
+ # Only the longest stretches count, so a session of many long idles keeps a bounded timeline.
+ many = VideoClock(spans=(), inactive=tuple((i * 200 + 10, i * 200 + 70 + i) for i in range(15)))
+ assert [b.video_s for b in long_idle_breaks(many, 3_100_000)] == [i * 200 + 70 + i for i in range(5, 15)]
+
+
+def test_the_players_inactive_periods_are_the_idle_stretches() -> None:
+ clock = video_clock_from_export_context({"inactivity_periods": _PERIODS})
+ assert clock is not None
+ assert clock.inactive_session_ms(80_000) == [IdleStretch(start_ms=58_000, end_ms=62_000)]
+
+
class TestCitationsPastTheVideoEnd:
def test_an_invented_time_is_dropped_rather_than_clamped_to_the_end(self) -> None:
# The clock clamps past its last span, so without an explicit bound this lands on the recording end.
@@ -119,3 +153,140 @@ class TestCitationsPastTheVideoEnd:
assert clock is not None
_, segments = _extract_segments("ends here (t 76)", 80_000, clock)
assert [s.timestamp_ms for s in segments if isinstance(s, ChipSegment)] == [80_000]
+
+
+def _chapter(start_t: int, title: str = "Part", thumbnail_t: int | None = None) -> SummaryChapterResponse:
+ return SummaryChapterResponse(start_t=start_t, title=title, thumbnail_t=thumbnail_t)
+
+
+class TestResolveChapters:
+ @parameterized.expand(
+ [
+ (
+ "chapters tile the session, and a start after the cut moves onto the session clock",
+ [_chapter(0, "Opens the app", 10), _chapter(30, "Edits a form", 40), _chapter(60, "Saves", 70)],
+ [
+ (0, 30_000, "Opens the app", 10_000),
+ (30_000, 64_000, "Edits a form", 40_000),
+ (64_000, 80_000, "Saves", 74_000),
+ ],
+ ),
+ (
+ "out of order input is sorted and a repeated start keeps the first chapter",
+ [_chapter(30, "Second"), _chapter(0, "First"), _chapter(30, "Duplicate")],
+ [(0, 30_000, "First", 15_000), (30_000, 80_000, "Second", 55_000)],
+ ),
+ (
+ "the first chapter starts at 0 even when the model skipped the page load",
+ [_chapter(5, "Only part", 20)],
+ [(0, 80_000, "Only part", 20_000)],
+ ),
+ (
+ "a start at or past the video's end is invented and dropped",
+ [_chapter(0, "Real"), _chapter(76, "Invented"), _chapter(900, "Invented")],
+ [(0, 80_000, "Real", 40_000)],
+ ),
+ (
+ "a thumbnail outside its chapter falls back to the midpoint",
+ [_chapter(0, "Browses", 50), _chapter(30, "Buys")],
+ [(0, 30_000, "Browses", 15_000), (30_000, 80_000, "Buys", 55_000)],
+ ),
+ (
+ "a title that was only a leaked citation marker is dropped",
+ [_chapter(0, "Browses"), _chapter(30, "(t 30)")],
+ [(0, 80_000, "Browses", 40_000)],
+ ),
+ (
+ "a chapter with no start is dropped and negative starts clamp to 0",
+ [
+ SummaryChapterResponse(title="No start"),
+ _chapter(-9, "Opens"),
+ _chapter(-2, "Also opens"),
+ _chapter(30, "Buys"),
+ ],
+ [(0, 30_000, "Opens", 15_000), (30_000, 80_000, "Buys", 55_000)],
+ ),
+ ("no chapters stay no chapters", [], []),
+ ]
+ )
+ def test_the_models_chapters_are_repaired_onto_the_session_clock(
+ self,
+ _label: str,
+ chapters: list[SummaryChapterResponse],
+ expected: list[tuple[int, int, str, int]],
+ ) -> None:
+ clock = video_clock_from_export_context({"inactivity_periods": _PERIODS})
+ assert clock is not None
+ # Only the cut map, so these cases cover the repair on its own; idle stretches have their own test.
+ resolved = resolve_chapters(chapters, 80_000, replace(clock, inactive=()))
+ assert [(c.start_ms, c.end_ms, c.title, c.thumbnail_ms) for c in resolved] == expected
+
+ @parameterized.expand(
+ [
+ (
+ "a short pause stays inside its chapter",
+ [(40, 70)],
+ [_chapter(0, "Reads docs", 50), _chapter(200, "Signs up")],
+ [
+ ("activity", 0, 200_000, "Reads docs", 50_000),
+ ("activity", 200_000, 400_000, "Signs up", 300_000),
+ ],
+ ),
+ (
+ "a boundary a second past a long idle snaps to its end",
+ [(100, 200)],
+ [_chapter(0, "Browses"), _chapter(201, "Buys")],
+ [
+ ("activity", 0, 100_000, "Browses", 50_000),
+ ("idle", 100_000, 200_000, "Idle", None),
+ ("activity", 200_000, 400_000, "Buys", 300_000),
+ ],
+ ),
+ (
+ "a long idle inside a chapter splits it and both sides keep the title",
+ [(100, 200)],
+ [_chapter(0, "Reads docs", 150)],
+ [
+ ("activity", 0, 100_000, "Reads docs", 50_000),
+ ("idle", 100_000, 200_000, "Idle", None),
+ ("activity", 200_000, 400_000, "Reads docs", 300_000),
+ ],
+ ),
+ (
+ "long idle at the start and the end of the session",
+ [(0, 70), (320, 400)],
+ [_chapter(0, "Browses", 100)],
+ [
+ ("idle", 0, 70_000, "Idle", None),
+ ("activity", 70_000, 320_000, "Browses", 100_000),
+ ("idle", 320_000, 400_000, "Idle", None),
+ ],
+ ),
+ (
+ "a short chapter the model gave its own entry is kept, however short",
+ [],
+ [_chapter(0, "Browses"), _chapter(100, "Rage clicks buy button"), _chapter(102, "Buys")],
+ [
+ ("activity", 0, 100_000, "Browses", 50_000),
+ ("activity", 100_000, 102_000, "Rage clicks buy button", 101_000),
+ ("activity", 102_000, 400_000, "Buys", 251_000),
+ ],
+ ),
+ (
+ "a sliver of activity between two long idles folds into them",
+ [(0, 100), (101, 400)],
+ [_chapter(0, "Browses")],
+ [("idle", 0, 400_000, "Idle", None)],
+ ),
+ ]
+ )
+ def test_long_inactive_stretches_become_idle_chapters(
+ self,
+ _label: str,
+ inactive: list[tuple[float, float]],
+ chapters: list[SummaryChapterResponse],
+ expected: list[tuple[str, int, int, str, int | None]],
+ ) -> None:
+ clock = VideoClock(spans=(), inactive=tuple(inactive))
+ resolved = resolve_chapters(chapters, 400_000, clock)
+ assert [(c.kind, c.start_ms, c.end_ms, c.title, c.thumbnail_ms) for c in resolved] == expected
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index cd3e6b05a74e..1bbd2612d13e 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -718,6 +718,7 @@ export interface ReplayObservationLabelApi {
/**
* * `thumbnail` - Thumbnail
* * `clip` - Clip
+ * * `chapter` - Chapter
*/
export type ReplayObservationMediaKindEnumApi =
(typeof ReplayObservationMediaKindEnumApi)[keyof typeof ReplayObservationMediaKindEnumApi]
@@ -725,6 +726,7 @@ export type ReplayObservationMediaKindEnumApi =
export const ReplayObservationMediaKindEnumApi = {
Thumbnail: 'thumbnail',
Clip: 'clip',
+ Chapter: 'chapter',
} as const
/**
@@ -733,11 +735,14 @@ export const ReplayObservationMediaKindEnumApi = {
export interface ReplayObservationMediaApi {
/** Id of this media entry. */
readonly id: string
- /** `thumbnail` for the single frame that illustrates the observation, `clip` for a short video.
+ /** `thumbnail` for the single frame that illustrates the observation, `chapter` for the frame of one summary chapter, `clip` for a short video.
*
* * `thumbnail` - Thumbnail
- * * `clip` - Clip */
+ * * `clip` - Clip
+ * * `chapter` - Chapter */
readonly kind: ReplayObservationMediaKindEnumApi
+ /** Order among media of the same kind. For a `chapter` frame, the index into `model_output.chapters`. */
+ readonly position: number
/** Export asset holding the bytes; fetch it from the export content endpoint. */
readonly asset_id: number
/**
@@ -2899,6 +2904,14 @@ export type VisionObservationsRetrieveParams = {
verdict?: string
}
+export type VisionObservationsThumbnailRetrieveParams = {
+ /**
+ * Index into the summary's `model_output.chapters`. Serves that chapter's frame instead of the observation's thumbnail.
+ * @minimum 0
+ */
+ chapter?: number
+}
+
export type VisionObservationsSearchRetrieveParams = {
/**
* Only observations analyzed at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone.
@@ -3224,6 +3237,14 @@ export type VisionScannersObservationsSignalReportsListParams = {
verdict?: string
}
+export type VisionScannersObservationsThumbnailRetrieveParams = {
+ /**
+ * Index into the summary's `model_output.chapters`. Serves that chapter's frame instead of the observation's thumbnail.
+ * @minimum 0
+ */
+ chapter?: number
+}
+
export type VisionScannersObservationsStatsRetrieveParams = {
/**
* Only observations dispatched by this backfill.
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index abaa7ae048b4..f707f5aa3ad2 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -68,6 +68,7 @@ import type {
VisionObservationsRetrieveParams,
VisionObservationsSearchRetrieveParams,
VisionObservationsSearchSuggestionsRetrieveParams,
+ VisionObservationsThumbnailRetrieveParams,
VisionQuotaApi,
VisionScannersBackfillsListParams,
VisionScannersImpactRetrieveParams,
@@ -76,6 +77,7 @@ import type {
VisionScannersObservationsRetrieveParams,
VisionScannersObservationsSignalReportsListParams,
VisionScannersObservationsStatsRetrieveParams,
+ VisionScannersObservationsThumbnailRetrieveParams,
VisionScannersPromptSuggestionsListParams,
VisionScannersWatchFeedRetrieveParams,
VisionSpendSeriesApi,
@@ -455,8 +457,24 @@ export const visionObservationsSignalReportsList = async (
})
}
-export const getVisionObservationsThumbnailRetrieveUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/vision/observations/${id}/thumbnail/`
+export const getVisionObservationsThumbnailRetrieveUrl = (
+ projectId: string,
+ id: string,
+ params?: VisionObservationsThumbnailRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/vision/observations/${id}/thumbnail/?${stringifiedParams}`
+ : `/api/projects/${projectId}/vision/observations/${id}/thumbnail/`
}
/**
@@ -465,9 +483,10 @@ export const getVisionObservationsThumbnailRetrieveUrl = (projectId: string, id:
export const visionObservationsThumbnailRetrieve = async (
projectId: string,
id: string,
+ params?: VisionObservationsThumbnailRetrieveParams,
options?: RequestInit
): Promise<unknown> => {
- return apiMutator<unknown>(getVisionObservationsThumbnailRetrieveUrl(projectId, id), {
+ return apiMutator<unknown>(getVisionObservationsThumbnailRetrieveUrl(projectId, id, params), {
...options,
method: 'GET',
})
@@ -1204,8 +1223,25 @@ export const visionScannersObservationsSignalReportsList = async (
)
}
-export const getVisionScannersObservationsThumbnailRetrieveUrl = (projectId: string, scannerId: string, id: string) => {
- return `/api/projects/${projectId}/vision/scanners/${scannerId}/observations/${id}/thumbnail/`
+export const getVisionScannersObservationsThumbnailRetrieveUrl = (
+ projectId: string,
+ scannerId: string,
+ id: string,
+ params?: VisionScannersObservationsThumbnailRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/vision/scanners/${scannerId}/observations/${id}/thumbnail/?${stringifiedParams}`
+ : `/api/projects/${projectId}/vision/scanners/${scannerId}/observations/${id}/thumbnail/`
}
/**
@@ -1215,9 +1251,10 @@ export const visionScannersObservationsThumbnailRetrieve = async (
projectId: string,
scannerId: string,
id: string,
+ params?: VisionScannersObservationsThumbnailRetrieveParams,
options?: RequestInit
): Promise<unknown> => {
- return apiMutator<unknown>(getVisionScannersObservationsThumbnailRetrieveUrl(projectId, scannerId, id), {
+ return apiMutator<unknown>(getVisionScannersObservationsThumbnailRetrieveUrl(projectId, scannerId, id, params), {
...options,
method: 'GET',
})
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yaml
index 0046f5cc591d..f895d5519084 100644
--- a/products/replay_vision/mcp/tools.yaml
+++ b/products/replay_vision/mcp/tools.yaml
@@ -197,7 +197,9 @@ tools:
`scanner_result.model_output.reasoning_segments` interleaves prose with `chip` segments, and a chip's
`timestamp_ms` is the recording-relative offset of the moment being cited — append `?t=<seconds>`
(`timestamp_ms` / 1000, rounded down) to that URL to seek straight to it. When you report a finding to
- someone, deep-link the one or two moments it turns on rather than only describing them.
+ someone, deep-link the one or two moments it turns on rather than only describing them. A summarizer's
+ `model_output.chapters` breaks the recording into ordered parts; each chapter's `start_ms` seeks the same
+ way.
url_prefix: /replay
vision-observations-label-create:
operation: vision_observations_label_create
@@ -838,7 +840,9 @@ tools:
`scanner_result.model_output.reasoning_segments` interleaves prose with `chip` segments, and a chip's
`timestamp_ms` is the recording-relative offset of the moment being cited — append `?t=<seconds>`
(`timestamp_ms` / 1000, rounded down) to that URL to seek straight to it. When you report a finding to
- someone, deep-link the one or two moments it turns on rather than only describing them.
+ someone, deep-link the one or two moments it turns on rather than only describing them. A summarizer's
+ `model_output.chapters` breaks the recording into ordered parts; each chapter's `start_ms` seeks the same
+ way.
url_prefix: /replay
vision-scanners-observations-label-create:
operation: vision_scanners_observations_label_create
diff --git a/products/replay_vision/skills/exploring-replay-vision-observations/SKILL.md b/products/replay_vision/skills/exploring-replay-vision-observations/SKILL.md
index d937877bd30a..0601ad303f6b 100644
--- a/products/replay_vision/skills/exploring-replay-vision-observations/SKILL.md
+++ b/products/replay_vision/skills/exploring-replay-vision-observations/SKILL.md
@@ -20,7 +20,7 @@ and doing something useful with it. For creating or sizing scanners, use [[creat
- `classifier` → one or more `tags` from the scanner's label set, plus `tags_freeform` when the scanner
allows freeform tags, and the `reasoning`.
- `scorer` → a numeric `score` on the scanner's `scale`, and the `reasoning`.
- - `summarizer` → a `title` and free-text `summary`.
+ - `summarizer` → a `title`, a free-text `summary`, and `chapters`: the recording broken into ordered parts, each with `start_ms`, `end_ms`, a short `title` and a `thumbnail_ms`, all offsets into the recording (seek with `?t=<start_ms / 1000>`). A chapter with `kind: idle` is a stretch of a minute or more that the replay player marked inactive (no interaction recorded), taken from the render rather than the model.
- **Only `succeeded` observations carry a finding.** Triage the rest by `status`/`error_reason` (see below).
- **Observations are LLM judgments, not ground truth.** One observation is one model's read of one session —
corroborate before you act on it.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 64fe401211a7..219be2891617 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -64240,6 +64240,7 @@ export namespace Schemas {
/**
* * `thumbnail` - Thumbnail
* * `clip` - Clip
+ * * `chapter` - Chapter
*/
export type ReplayObservationMediaKindEnum = typeof ReplayObservationMediaKindEnum[keyof typeof ReplayObservationMediaKindEnum];
@@ -64247,6 +64248,7 @@ export namespace Schemas {
export const ReplayObservationMediaKindEnum = {
Thumbnail: 'thumbnail',
Clip: 'clip',
+ Chapter: 'chapter',
} as const;
/**
@@ -64255,11 +64257,14 @@ export namespace Schemas {
export interface ReplayObservationMedia {
/** Id of this media entry. */
readonly id: string;
- /** `thumbnail` for the single frame that illustrates the observation, `clip` for a short video.
+ /** `thumbnail` for the single frame that illustrates the observation, `chapter` for the frame of one summary chapter, `clip` for a short video.
*
* * `thumbnail` - Thumbnail
- * * `clip` - Clip */
+ * * `clip` - Clip
+ * * `chapter` - Chapter */
readonly kind: ReplayObservationMediaKindEnum;
+ /** Order among media of the same kind. For a `chapter` frame, the index into `model_output.chapters`. */
+ readonly position: number;
/** Export asset holding the bytes; fetch it from the export content endpoint. */
readonly asset_id: number;
/**
@@ -122532,6 +122537,14 @@ export namespace Schemas {
verdict?: string;
};
+ export type VisionObservationsThumbnailRetrieveParams = {
+ /**
+ * Index into the summary's `model_output.chapters`. Serves that chapter's frame instead of the observation's thumbnail.
+ * @minimum 0
+ */
+ chapter?: number;
+ };
+
export type VisionObservationsSearchRetrieveParams = {
/**
* Only observations analyzed at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone.
@@ -122856,6 +122869,14 @@ export namespace Schemas {
verdict?: string;
};
+ export type VisionScannersObservationsThumbnailRetrieveParams = {
+ /**
+ * Index into the summary's `model_output.chapters`. Serves that chapter's frame instead of the observation's thumbnail.
+ * @minimum 0
+ */
+ chapter?: number;
+ };
+
export type VisionScannersObservationsStatsRetrieveParams = {
/**
* Only observations dispatched by this backfill.
diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.ts
index 4f6e425f1cb9..29a74cc81048 100644
--- a/services/mcp/src/tools/generated/replay_vision.ts
+++ b/services/mcp/src/tools/generated/replay_vision.ts
@@ -394,7 +394,7 @@ const visionObservationsGet = (): ToolBase<
})
return withAgentNote(
await withPostHogUrl(context, result, `/replay/${result.session_id}`),
- "`_posthogUrl` opens the recording this observation analysed. `scanner_result.model_output.reasoning_segments` interleaves prose with `chip` segments, and a chip's `timestamp_ms` is the recording-relative offset of the moment being cited — append `?t=<seconds>` (`timestamp_ms` / 1000, rounded down) to that URL to seek straight to it. When you report a finding to someone, deep-link the one or two moments it turns on rather than only describing them.\n"
+ "`_posthogUrl` opens the recording this observation analysed. `scanner_result.model_output.reasoning_segments` interleaves prose with `chip` segments, and a chip's `timestamp_ms` is the recording-relative offset of the moment being cited — append `?t=<seconds>` (`timestamp_ms` / 1000, rounded down) to that URL to seek straight to it. When you report a finding to someone, deep-link the one or two moments it turns on rather than only describing them. A summarizer's `model_output.chapters` breaks the recording into ordered parts; each chapter's `start_ms` seeks the same way.\n"
)
},
})
@@ -1357,7 +1357,7 @@ const visionScannersObservationsGet = (): ToolBase<
})
return withAgentNote(
await withPostHogUrl(context, result, `/replay/${result.session_id}`),
- "`_posthogUrl` opens the recording this observation analysed. `scanner_result.model_output.reasoning_segments` interleaves prose with `chip` segments, and a chip's `timestamp_ms` is the recording-relative offset of the moment being cited — append `?t=<seconds>` (`timestamp_ms` / 1000, rounded down) to that URL to seek straight to it. When you report a finding to someone, deep-link the one or two moments it turns on rather than only describing them.\n"
+ "`_posthogUrl` opens the recording this observation analysed. `scanner_result.model_output.reasoning_segments` interleaves prose with `chip` segments, and a chip's `timestamp_ms` is the recording-relative offset of the moment being cited — append `?t=<seconds>` (`timestamp_ms` / 1000, rounded down) to that URL to seek straight to it. When you report a finding to someone, deep-link the one or two moments it turns on rather than only describing them. A summarizer's `model_output.chapters` breaks the recording into ordered parts; each chapter's `start_ms` seeks the same way.\n"
)
},
})