: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): show the frame each observation found (#102670)
Tue Haulunde30a069c8d6e
diff --git a/bin/temporal-recording-rasterizer-worker b/bin/temporal-recording-rasterizer-workerindex c3cc29e6e99d..c718523b8b24 100755--- a/bin/temporal-recording-rasterizer-worker+++ b/bin/temporal-recording-rasterizer-worker@@ -11,6 +11,13 @@ IMAGE_NAME="recording-rasterizer:local"DOCKERFILE="$ROOT_DIR/Dockerfile.recording-rasterizer"HASH_FILE="$ROOT_DIR/.posthog/.generated/rasterizer-image.hash"+# Build for the host: chrome-headless-shell ships an arm64 build, and an emulated amd64 Chromium is+# far too slow to render with. Apple Silicon and the arm64 devboxes both land here.+case "$(uname -m)" in+arm64 | aarch64) PLATFORM="linux/arm64" ;;+*) PLATFORM="linux/amd64" ;;+esac+cd "$ROOT_DIR"# --- Step 1: Build TypeScript locally ---@@ -26,12 +33,13 @@ pnpm --filter=@posthog/nodejs build# Hash the Dockerfile and key dependency files to detect when a rebuild is needed.# Source code changes are picked up via volume mounts, so we only need to rebuild# when the image structure (deps, base image, system packages) changes.-current_hash=$(cat \+# The platform is part of the hash so a cached image from another architecture is rebuilt.+current_hash=$( { cat \"$DOCKERFILE" \"$ROOT_DIR/pnpm-lock.yaml" \"$ROOT_DIR/nodejs/package.json" \"$ROOT_DIR/common/replay-headless/package.json" \- 2>/dev/null | shasum -a 256 | cut -d' ' -f1)+ 2>/dev/null; echo "$PLATFORM"; } | shasum -a 256 | cut -d' ' -f1)previous_hash=""if [ -f "$HASH_FILE" ]; then@@ -46,7 +54,7 @@ fiif [ "$current_hash" != "$previous_hash" ]; thenecho "Docker image outdated or missing, rebuilding..."docker build \- --platform linux/amd64 \+ --platform "$PLATFORM" \-f "$DOCKERFILE" \-t "$IMAGE_NAME" \"$ROOT_DIR"@@ -84,7 +92,7 @@ fidocker run --rm --security-opt seccomp=unconfined --security-opt apparmor=unconfined \--name "$CONTAINER_NAME" \--network posthog_default \- --platform linux/amd64 \+ --platform "$PLATFORM" \--add-host localhost:host-gateway \--add-host host.docker.internal:host-gateway \-e NODE_ENV=development \diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 93e78c1070a3..3c6227dfd136 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10133,21 +10133,21 @@ snapshots:scenes-app-replay-vision--home-watch-feed-empty--light:hash: v1.k794b7964.33393d260f0654e59dbc209d6052c2b0730dfc6e8f59925406cd3a9349569980.63xRgoQrVu1PM7n1sBaVx6QV7Otc_rKCusdfHhsGuBUscenes-app-replay-vision--observation-detail--dark:- hash: v1.k794b7964.5c1e4dc71fab8dd16212232b0a6483e7b96f884bd6c9761f276e9d6d788192a3.EyeOt5zd-9ySXBJcK-nvwOcO-Q1umL8pWldTB9PWh9s+ hash: v1.k794b7964.e9fd7c14ee1899c90ba01049012a8d9947f013869b8ec7d767b7db2220d46166.XZIczm04vBGXxRP7z-rzHaqy34GQDRXXfTrEhICqxi0scenes-app-replay-vision--observation-detail--light:- hash: v1.k794b7964.d1585db51286bdddac28280c4285203c786279225e77694079f94c172dee4fc8.hXxdPRDiseuUCTAafU1no8DEGo0wRGTJ_wTRbrL-eS0+ hash: v1.k794b7964.7e192691951be3702d927d1d9d192f06ea3e9cd1a241cb36d3c29c5ce09fc21b.am09e5v4YWSCyyjBOBTw5cCclechXFAeWEuXy3E6m0wscenes-app-replay-vision--observation-detail-calibration-entry-point--dark:- hash: v1.k794b7964.5eadf71e71ce8bff83fbfab1d535f8fe9a16f7d1951a1254e597e7fda840385f.WlAvmuhf9a6IIRDRS4LNKKH_rxwAtrkGTb_njulZdt0+ hash: v1.k794b7964.9d8ee815926f025fd68e694c3bc316d8f1b485f2d54bb36153c4e5cdcb9d3ae3.IXdjhtQjEyeeEZsSSy_BcLQvLYIA18srQOSptAU-QX4scenes-app-replay-vision--observation-detail-calibration-entry-point--light:- hash: v1.k794b7964.2d2242ab7bd12d2212bbeca131141596ba2e51e2a64ab8ec65c0fb9a25e57469.fmZ8U__-CGZtcNADdCZVqao35Kp4yNW9IlEj-tvWFAw+ hash: v1.k794b7964.cc28834863341019f828f1080b3abe045d508fcf2609f482d91e346157f7b2b2.rw_A7OzvU27gTV4WIxLiJXQHcJMSAfDUeYSQughz8Zcscenes-app-replay-vision--observation-detail-feedback-prompt--dark:- hash: v1.k794b7964.df5cc209a6eab8b0f3e98080117062434c61ec57f2ff9dde173605b886d330c5.A21pn55lNieyAs2DNS_PHDmHINmM9PvjvuSaEcv5xVA+ hash: v1.k794b7964.25f4f6b0b5f27fdcf98ec072b92d97ca9c7eccf55af31d002031197082d27673.aIbt54OC817JeBomMqEOMUqk-HFM2x-UDuWAC4h4Zasscenes-app-replay-vision--observation-detail-feedback-prompt--light:- hash: v1.k794b7964.a61d0f88db1faea81a901faa9dcaebc0d21d66504907d8ad354fce1f9d9e9257.B_NQ0x5MdoUPDm3d8dUbsPP4np-hIjaWDy5oe7kMNPM+ hash: v1.k794b7964.59677d24da0b5cb9cd755a5f5af898c7a9999560caa6c7a9f653c0cdb1cd9198.VziTZTShcVxzXQMyJRuUCTDfplGGmCGd7yESU8U1m4Qscenes-app-replay-vision--observation-detail-monitor--dark:- hash: v1.k794b7964.55b81d9639474eba1f729479fac38f935641f164712a7f1e1ed7f5d595a9b40f.eonn1G6FtkOAzQ1GkpW7q_FtXrzYhkty8Zuxe1LCyMI+ hash: v1.k794b7964.ef99171cd2a5ed8008fbd26ede08aa1c63539dd86331657f74ef887b6ce224e3.iw5USyEwKvl52slTujh069twP8ZiUjNOHpw0SLM7FBMscenes-app-replay-vision--observation-detail-monitor--light:- hash: v1.k794b7964.c5243eda52db803aa1ebe8b08aafb31657c3e4bb087dec468a6e9108576a3a66.ZDaQ5Hu-nxVYAP_w41BkXf-IjyT-nl-Skp_jbIwftb8+ hash: v1.k794b7964.266af7318c0609fc4b1df50ffdc70b05f6a33d7f0cedbd8fcaff5040de483cb2.flvYykloNw1KibfSjtHG9M_L_Gl_knRVLMgWHk5TRxEscenes-app-replay-vision--scanner-alerts--dark:hash: v1.k794b7964.c416988b5908944127a58d491bf68dceb3f1f9caf728b69185f372f11f2ab68c.aHRUHVbQvkxQzLEFJmWx1YUCfAPgMVcTyiAeuvNfUS4scenes-app-replay-vision--scanner-alerts--light:@@ -10225,9 +10225,9 @@ snapshots:scenes-app-replay-vision--scanner-editor-triggers--light:hash: v1.k794b7964.1325a276c040c4fdec27fd9d75ecde45e08d343f4e76806a03819747f4c52973.6k8EbsIyUMKtWUuUvV-ElrJCGK5_-iSXLT4bi_fp3Ggscenes-app-replay-vision--scanner-observations--dark:- hash: v1.k794b7964.ef7f3a8337ab0bc95105a6ec2ed2d4091aee06901f63fb5c832e011ad9c7959b.PoRYAH-QBKLTSwZfXB6tHx0Bba7w_jlyUmFh8-V1aQA+ hash: v1.k794b7964.402fa9ac00801dcc40affa0aab0764fa66e3123f71d692459218b3a2b31608b9.C79AV3kXB1w8Sh4jz60Ch1ZxmN5OAsAmD3ivWpg8nooscenes-app-replay-vision--scanner-observations--light:- hash: v1.k794b7964.a187475b68b70130820a9e8c8d99d0b5f68cb9e5cb5267cda20f4e3b2d98ce3c.YjRP5UBMhYYOFX4_QJWB0oLpjyMAwKvhg66uJeDtZ7A+ hash: v1.k794b7964.00d24a18b12ab5fd776a9367e0aea1b7563617afffac960e4d693ab473d49717.ASmLzygbIkg4yJ2vKiSaImoFPpMALHMSluBBKkY4G5Mscenes-app-replay-vision--scanner-on-demand--dark:hash: v1.k794b7964.e3c55f635fcc957d786bf810c6be7f7ba8da1287a4390314893282062f43e108._oT0AUvPgnwHst_b6VX6Op2av3k5NsOyjnquUcgTB4cscenes-app-replay-vision--scanner-on-demand--light:@@ -10272,6 +10272,22 @@ snapshots:hash: v1.k794b7964.30975bcc2085658200ab6ea0f24d7981bdcf1fc13fccc9c3dc758c0063372d46.j1VtD47yDmX3mczn_DBkVGbGZgPUsuAPFLN1COo1n0Iscenes-app-replay-vision--usage-tab-redesigned--light:hash: v1.k794b7964.4c8e665d2f6197115d5a0ffb3e914027d2ffa63f2856ca17c7c0e92fb4ea1c84.YIHK8qU8f2M6OTil-h7HvXzENlVMfNUeI3LYVikCjuA+ scenes-app-replay-vision-observationthumbnail--frame--dark:+ hash: v1.k794b7964.25e0fc3a30206636572afe40dc1dece511909b329125acdd76d5cd6b70e4cebd.vUNWqzn2OcfR4oaaUWZaXz4aKxivNKx8scF34tw7JEE+ scenes-app-replay-vision-observationthumbnail--frame--light:+ hash: v1.k794b7964.7d9a481298ab6b3dbd5c82018f21e0dcd803c047bee534e0f9e77f15f630f72b.0-OjMQOzHGO_oMK-n24PeFB0Bbm9ApaS5O_svEqGll0+ scenes-app-replay-vision-observationthumbnail--frame-as-a-play-target--dark:+ hash: v1.k794b7964.3fcdf5a9ca58ff631ef3fcdd67efe92280c94443dd355d9f14673c31ddcbeb9f.1y4aa8yIaZKKuogyqF07BXfjNI4v-dUotJP5oUbZa_c+ scenes-app-replay-vision-observationthumbnail--frame-as-a-play-target--light:+ hash: v1.k794b7964.7a7893925322e4009de95c5ed1eacef98186316132b476fdf1e848ee10f1ad13.u4UVrKPJmHOtkDfNMbnSOpGSwEJ0QwXMJkLHUYNGvcY+ scenes-app-replay-vision-observationthumbnail--frame-fails-to-load--dark:+ hash: v1.k794b7964.d3c3aea7db95e55f3a3c6bd3266ed6a6c8a6b7d0c9639197be8499d52a311583.TS-u3VBrvbpIYhO3unbR-mcmNk_hDt_I0vWn0OV7aFw+ scenes-app-replay-vision-observationthumbnail--frame-fails-to-load--light:+ hash: v1.k794b7964.7ea8bf86c6c2c46e8e19a7f65aeff30e4be8ea79e8159dc0ea9bc10baa4cd2c5.ai3KgdzcNZ3odAx_kqdviQYapM9eKik1dCkHn-PEW68+ scenes-app-replay-vision-observationthumbnail--no-frame-yet--dark:+ hash: v1.k794b7964.d3c3aea7db95e55f3a3c6bd3266ed6a6c8a6b7d0c9639197be8499d52a311583.vcVaKjae7hHygKO4H_NDzkoa62WYvDIZvSa-Y-3DEr0+ scenes-app-replay-vision-observationthumbnail--no-frame-yet--light:+ hash: v1.k794b7964.7ea8bf86c6c2c46e8e19a7f65aeff30e4be8ea79e8159dc0ea9bc10baa4cd2c5.xt9_PBGwUPblnhPAtL-bcbSs_gQzXDfxAVB4vz8c63sscenes-app-replay-vision-spendtrajectorychart--hits-the-limit--dark:hash: v1.k794b7964.cf96414912c6d8f0d73808db3f1d833c661d12b3b0449cdd49b95d4dc8059e80.3sA2mn18MksUWQQ4mq6wEPbkJhGP3O258Y6Q2fTWhgMscenes-app-replay-vision-spendtrajectorychart--hits-the-limit--light:diff --git a/frontend/src/mocks/fixtures/sessionFrame.ts b/frontend/src/mocks/fixtures/sessionFrame.tsnew file mode 100644index 000000000000..ece4d4d55a7f--- /dev/null+++ b/frontend/src/mocks/fixtures/sessionFrame.ts@@ -0,0 +1,14 @@+/**+ * A stand-in frame for stories that render a thumbnail of a session recording.+ *+ * Invented, not captured: a flat drawing of a checkout that declined a card, which is the kind of moment a+ * scan picks a frame from. Inline base64 so a mock can serve real image bytes without a static asset.+ */+export const SESSION_FRAME_PNG_BASE64 =+ 'iVBORw0KGgoAAAANSUhEUgAAAoAAAAFoCAIAAABIUN0GAAAcMUlEQVR42u3deXxU5aHw8WcmARKNIrKEtQhBdsQV2WSnoqJVQcTaVy2vIqjofdXboq1t3b1arYrVane1tpfL4lbrggoostReZIdWhCgQQpRFIGSf94+xaZpJImsCyff78Y8wmXPOM88gv88zM+dMZPPmDQEAqF5RUwAAAgwAAgwACDAACDAAIMAAIMAAQNWSTUEIYfv27SYBgL133HHHCfBBSG+nTt38ZQJg761Zs+IAMxyps1fCkl4AajDDdTTA27dvl14ADlaG96PB+/MSdL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3FF6t5KSksLCwtJ9hBAikX/b7datn3fu3KVRo+O3bv2iuLi4ceMm0Wg0Pz/fhHP486krK2CoAQ0bHrdp06akpGg0+tXfz6ysTV27dk9YvMbKbfjFF5+3aNEyhNCiRcutWz8vLi7Oz89v3rzltm1bt279ol27jK1bvzC9qC8CDBXLzFzXr99ZHTt2LioqjDc4K2tj8+YtNm3aUPWGq1ataNWqTZ8+/Vu1arNy5YoQQk7OlpSUlIKCgu3bt3n9GfXlsBKJxWJmoXbIy8sNtfS7aVNTU0866ZSFCz+orc/d0KHD/QUO3tNV3+A9YDicpKc379ix85Ili00F1r4IMFSf7OzN2dmbzQPqS/AeMADqiwADqC8CDID6IsAAIMAAgAADgAATXBHCnAMCjB5gtgEBRhXMMyDAaANmGAi+jIFwML+MAQArYAAQYABAgAFAgAEAAQYAAQYABBgABBgABBgAEGAAEGAAQIABQIABAAEGAAEGAAQYAAQYAAQYABBgABBgAECAAUCAAQABBgABBgAEGAAEGADqtv8PhFOcQU8A7UcAAAAASUVORK5CYII='++/** Serve the frame as an image response, for mocking an endpoint an `<img>` loads from. */+export function sessionFrameResponse(): Response {+ const bytes = Uint8Array.from(atob(SESSION_FRAME_PNG_BASE64), (character) => character.charCodeAt(0))+ return new Response(bytes, { headers: { 'Content-Type': 'image/png' } })+}diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/thumbnail.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/thumbnail.test.tsnew file mode 100644index 000000000000..bb84a26d7673--- /dev/null+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/thumbnail.test.ts@@ -0,0 +1,68 @@+import { uniformBorderRect } from '../thumbnail'++const BORDER: [number, number, number] = [26, 31, 38]++function frame(+ width: number,+ height: number,+ content: { x: number; y: number; w: number; h: number } | null,+ fill: [number, number, number] = [253, 253, 253]+): Buffer {+ const buffer = Buffer.alloc(width * height * 3)+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const inside =+ content !== null &&+ x >= content.x &&+ x < content.x + content.w &&+ y >= content.y &&+ y < content.y + content.h+ const [r, g, b] = inside ? fill : BORDER+ const at = (y * width + x) * 3+ buffer[at] = r+ buffer[at + 1] = g+ buffer[at + 2] = b+ }+ }+ return buffer+}++describe('uniformBorderRect', () => {+ it('finds the page in a canvas padded with the player background', () => {+ const buffer = frame(1280, 688, { x: 472, y: 0, w: 336, h: 688 })++ expect(uniformBorderRect(buffer, 1280, 688)).toEqual({ w: 336, h: 688, x: 472, y: 0 })+ })++ it('keeps a frame that is already all content', () => {+ expect(uniformBorderRect(frame(1280, 688, { x: 0, y: 0, w: 1280, h: 688 }), 1280, 688)).toBeNull()+ })++ it('keeps a frame whose border is too thin to bother with', () => {+ expect(uniformBorderRect(frame(1280, 688, { x: 20, y: 0, w: 1240, h: 688 }), 1280, 688)).toBeNull()+ })++ it('keeps a dark page rather than cropping into it', () => {+ // The case a luma threshold gets wrong: dark content, not a border.+ const buffer = frame(1280, 688, { x: 0, y: 0, w: 1280, h: 688 }, [30, 34, 41])++ expect(uniformBorderRect(buffer, 1280, 688)).toBeNull()+ })++ it('keeps a blank frame whole', () => {+ expect(uniformBorderRect(frame(1280, 688, null), 1280, 688)).toBeNull()+ })++ it('ignores a truncated buffer', () => {+ expect(uniformBorderRect(Buffer.alloc(100), 1280, 688)).toBeNull()+ })++ it('crops vertical padding too', () => {+ expect(uniformBorderRect(frame(800, 600, { x: 100, y: 80, w: 600, h: 300 }), 800, 600)).toEqual({+ w: 600,+ h: 300,+ x: 100,+ y: 80,+ })+ })+})diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/config.ts b/nodejs/src/session-replay/recording-rasterizer/capture/config.tsindex 786eb9905fff..e73bfb19bf39 100644--- a/nodejs/src/session-replay/recording-rasterizer/capture/config.ts+++ b/nodejs/src/session-replay/recording-rasterizer/capture/config.ts@@ -17,7 +17,7 @@ const SESSION_ID_RE = /^(?!\.+$)[A-Za-z0-9_.:-]{1,200}$/// here (e.g. from a future caller that skips upstream validation) could still land in the option// list or filtergraph as a raw string. Throwing keeps interpolation injection-proof regardless of// the caller: a finite number stringifies to [0-9.eE+-] only, so no spaces or filter metacharacters.-function toFiniteNumber(value: unknown, field: string): number {+export function toFiniteNumber(value: unknown, field: string): number {const n = Number(value)if (!Number.isFinite(n)) {throw new RasterizationError(`${field} must be a finite number, got: ${String(value)}`, false, 'INVALID_INPUT')diff --git a/nodejs/src/session-replay/recording-rasterizer/errors.ts b/nodejs/src/session-replay/recording-rasterizer/errors.tsindex 8676b2098070..93420de85052 100644--- a/nodejs/src/session-replay/recording-rasterizer/errors.ts+++ b/nodejs/src/session-replay/recording-rasterizer/errors.ts@@ -13,6 +13,11 @@ export const RASTERIZATION_ERROR_CODES = ['RECORDING_TOO_LARGE','S3_UPLOAD_FAILED','S3_UPLOAD_UNDECODABLE_RESPONSE',+ 'S3_DOWNLOAD_FAILED',+ 'S3_DOWNLOAD_UNDECODABLE_RESPONSE',+ 'S3_DOWNLOAD_EMPTY',+ 'THUMBNAIL_EXTRACT_FAILED',+ 'THUMBNAIL_EMPTY_OUTPUT','NO_SNAPSHOTS','INIT_FAILED','DATA_LOAD_FAILED',diff --git a/nodejs/src/session-replay/recording-rasterizer/storage.ts b/nodejs/src/session-replay/recording-rasterizer/storage.tsindex 33262d872b36..4ef548ab7234 100644--- a/nodejs/src/session-replay/recording-rasterizer/storage.ts+++ b/nodejs/src/session-replay/recording-rasterizer/storage.ts@@ -1,9 +1,11 @@-import { S3Client } from '@aws-sdk/client-s3'+import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'import { defaultProvider } from '@aws-sdk/credential-provider-node'import { Upload } from '@aws-sdk/lib-storage'import { NodeHttpHandler } from '@smithy/node-http-handler'import * as fs from 'fs'import { HttpsProxyAgent } from 'https-proxy-agent'+import { Readable } from 'stream'+import { pipeline } from 'stream/promises'import { config } from './config'import { resolveEgressProxyUrl } from './egress-proxy'@@ -56,6 +58,7 @@ const FORMAT_META: Record<string, { ext: string; contentType: string }> = {mp4: { ext: 'mp4', contentType: 'video/mp4' },webm: { ext: 'webm', contentType: 'video/webm' },gif: { ext: 'gif', contentType: 'image/gif' },+ png: { ext: 'png', contentType: 'image/png' },}export async function uploadToS3(@@ -63,7 +66,7 @@ export async function uploadToS3(bucket: string,keyPrefix: string,id: string,- format: 'mp4' | 'webm' | 'gif' = 'mp4',+ format: 'mp4' | 'webm' | 'gif' | 'png' = 'mp4',onProgress?: () => void): Promise<string> {const { ext, contentType } = FORMAT_META[format] || FORMAT_META.mp4@@ -120,3 +123,43 @@ export async function uploadToS3(return target}++/** Fetch one object to a local path. The thumbnail activity reads the analysis MP4 this way. */+export async function downloadFromS3(bucket: string, key: string, localPath: string): Promise<void> {+ try {+ const res = await getS3Client().send(new GetObjectCommand({ Bucket: bucket, Key: key }))+ if (!res.Body) {+ throw new RasterizationError(`S3 object is empty: s3://${bucket}/${key}`, false, 'S3_DOWNLOAD_EMPTY')+ }+ // Streamed, not buffered: the media worker reads several tens-of-megabytes MP4s at once.+ await pipeline(res.Body as Readable, fs.createWriteStream(localPath))+ } catch (err) {+ if (err instanceof RasterizationError) {+ throw err+ }+ const undecodable = undecodableResponse(err)+ if (undecodable) {+ // An egress proxy answering HTML surfaces as a parser error, with the real reason in the body.+ log.warn(+ { bucket, key, status: undecodable.status, response_body: undecodable.body },+ 'S3 download returned an unreadable response'+ )+ throw new RasterizationError(+ `S3 download failed: the object store returned an unreadable (non-XML) response (status ${undecodable.status ?? 'unknown'})`,+ true,+ 'S3_DOWNLOAD_UNDECODABLE_RESPONSE',+ err+ )+ }+ const status = (err as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode+ log.warn({ bucket, key, status, err: (err as Error)?.message }, 'S3 download failed')+ // Only a missing object is permanent; a 403 is the credential-refresh race the upload path allows for.+ const retryable = status !== 404+ throw new RasterizationError(+ `S3 download failed${status ? ` (status ${status})` : ''}: ${(err as Error)?.message ?? String(err)}`,+ retryable,+ 'S3_DOWNLOAD_FAILED',+ err+ )+ }+}diff --git a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.tsindex 0b4f0705b90e..76af3846f326 100644--- a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts+++ b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts@@ -13,8 +13,10 @@ import { createLogger } from '~/session-replay/recording-rasterizer/logger'import { RasterizationMetrics } from '~/session-replay/recording-rasterizer/metrics'import { videoTimestampsFromFrames } from '~/session-replay/recording-rasterizer/postprocess'import { uploadToS3 } from '~/session-replay/recording-rasterizer/storage'+import { extractThumbnail } from '~/session-replay/recording-rasterizer/thumbnail'import {ActivityTimings,+ ExtractThumbnailInput,RasterizationProgress,RasterizeRecordingInput,RasterizeRecordingOutput,@@ -224,5 +226,22 @@ async function rasterizeRecordingActivity(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()+ }+ },}}diff --git a/nodejs/src/session-replay/recording-rasterizer/thumbnail.ts b/nodejs/src/session-replay/recording-rasterizer/thumbnail.tsnew file mode 100644index 000000000000..9b32cadb0010--- /dev/null+++ b/nodejs/src/session-replay/recording-rasterizer/thumbnail.ts@@ -0,0 +1,255 @@+import { execFile } from 'child_process'+import * as fs from 'fs/promises'+import * as os from 'os'+import * as path from 'path'+import { promisify } from 'util'++import { toFiniteNumber } from './capture/config'+import { RasterizationError } from './errors'+import { createLogger } from './logger'+import { downloadFromS3, uploadToS3 } from './storage'+import type { ExtractThumbnailInput, ExtractThumbnailOutput } from './types'++const execFileAsync = promisify(execFile)+const log = createLogger()++// One frame out of an existing MP4 never approaches the render timeouts; a longer wait means ffmpeg+// is wedged on a corrupt file rather than working.+const FFMPEG_TIMEOUT_MS = 60_000++function parseS3Uri(uri: string): { bucket: string; key: string } {+ const match = /^s3:\/\/([^/]+)\/(.+)$/.exec(uri)+ if (!match) {+ throw new RasterizationError(`Not an S3 URI: ${uri}`, false, 'INVALID_INPUT')+ }+ return { bucket: match[1], key: match[2] }+}++export interface Rect {+ w: number+ h: number+ x: number+ y: number+}++const BORDER_TOLERANCE = 6+// Every 8th row/column is enough to tell a uniform bar from page content, and keeps the scan cheap.+const SCAN_STEP = 8++function matchesBorder(frame: Buffer, offset: number, r: number, g: number, b: number): boolean {+ return (+ Math.abs(frame[offset] - r) <= BORDER_TOLERANCE &&+ Math.abs(frame[offset + 1] - g) <= BORDER_TOLERANCE &&+ Math.abs(frame[offset + 2] - b) <= BORDER_TOLERANCE+ )+}++/** The page inside the analysis canvas, when a phone-sized session leaves a uniform border around it. */+// Corner colour rather than a luma threshold: the background is not black, so cropdetect misses it, and+// a threshold high enough to catch it crops into a dark page.+export function uniformBorderRect(frame: Buffer, width: number, height: number): Rect | null {+ if (frame.length < width * height * 3) {+ return null+ }+ const [r, g, b] = [frame[0], frame[1], frame[2]]+ const at = (x: number, y: number): number => (y * width + x) * 3++ const columnIsBorder = (x: number): boolean => {+ for (let y = 0; y < height; y += SCAN_STEP) {+ if (!matchesBorder(frame, at(x, y), r, g, b)) {+ return false+ }+ }+ return true+ }+ const rowIsBorder = (y: number): boolean => {+ for (let x = 0; x < width; x += SCAN_STEP) {+ if (!matchesBorder(frame, at(x, y), r, g, b)) {+ return false+ }+ }+ return true+ }++ let left = 0+ while (left < width && columnIsBorder(left)) {+ left+++ }+ if (left === width) {+ // A frame of nothing but border: the render is blank, so there is no page to find.+ return null+ }+ let right = width - 1+ while (right > left && columnIsBorder(right)) {+ right--+ }+ let top = 0+ while (top < height && rowIsBorder(top)) {+ top+++ }+ let bottom = height - 1+ while (bottom > top && rowIsBorder(bottom)) {+ bottom--+ }++ const rect = { w: right - left + 1, h: bottom - top + 1, x: left, y: top }+ if (rect.w < width * 0.1 || rect.h < height * 0.1) {+ return null+ }+ // Worth a second ffmpeg pass only when it removes a real share of the frame.+ if (1 - (rect.w * rect.h) / (width * height) < 0.15) {+ return null+ }+ return rect+}++async function frameSize(sourcePath: string): Promise<{ width: number; height: number } | null> {+ try {+ const { stdout } = await execFileAsync(+ 'ffprobe',+ [+ '-v',+ 'error',+ '-select_streams',+ 'v:0',+ '-show_entries',+ 'stream=width,height',+ '-of',+ 'csv=p=0',+ sourcePath,+ ],+ { timeout: FFMPEG_TIMEOUT_MS }+ )+ const [width, height] = stdout.trim().split(',').map(Number)+ return Number.isFinite(width) && Number.isFinite(height) ? { width, height } : null+ } catch (err) {+ log.warn({ err: (err as Error)?.message }, 'ffprobe could not read the frame size')+ return null+ }+}++async function detectBorder(+ sourcePath: string,+ rawPath: string,+ videoTimeS: number,+ footerCrop: string,+ width: number,+ height: number+): Promise<Rect | null> {+ try {+ await execFileAsync(+ 'ffmpeg',+ [+ '-nostdin',+ '-loglevel',+ 'error',+ '-ss',+ String(videoTimeS),+ '-i',+ sourcePath,+ '-frames:v',+ '1',+ '-vf',+ footerCrop,+ '-pix_fmt',+ 'rgb24',+ '-f',+ 'rawvideo',+ '-y',+ rawPath,+ ],+ { timeout: FFMPEG_TIMEOUT_MS }+ )+ return uniformBorderRect(await fs.readFile(rawPath), width, height)+ } catch (err) {+ // Best-effort: a failed probe means the full frame, never a failed thumbnail.+ log.warn({ err: (err as Error)?.message }, 'border detection failed, keeping the full frame')+ return null+ }+}++/**+ * 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')++ try {+ await downloadFromS3(source.bucket, source.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',+ 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 }+ } finally {+ await fs.rm(workDir, { recursive: true, force: true })+ }+}diff --git a/nodejs/src/session-replay/recording-rasterizer/types.ts b/nodejs/src/session-replay/recording-rasterizer/types.tsindex 33be2fccb8e0..c21d2dacae34 100644--- a/nodejs/src/session-replay/recording-rasterizer/types.ts+++ b/nodejs/src/session-replay/recording-rasterizer/types.ts@@ -26,6 +26,25 @@ export interface RasterizeRecordingInput {s3_key_prefix: string // e.g. "exports/mp4/team-123/task-456"}+export interface ExtractThumbnailInput {+ /** The rendered analysis MP4 to cut the frame from. */+ source_s3_uri: string+ /** Seconds into the analysis video, which is the time base the model's citations use. */+ video_time_s: number+ /** 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+ id: string+}++export interface ExtractThumbnailOutput {+ 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 videodiff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 07364413e212..04ac69fa221f 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -1,7 +1,7 @@import osfrom posthog.settings.access import SECRET_KEY-from posthog.settings.base_variables import CLOUD_DEPLOYMENT, DEBUG+from posthog.settings.base_variables import CLOUD_DEPLOYMENT, DEBUG, TESTfrom posthog.settings.utils import get_from_env, get_list, str_to_boolTEMPORAL_NAMESPACE: str = os.getenv("TEMPORAL_NAMESPACE", "default")@@ -306,7 +306,10 @@ LOGS_VOLUME_TICK_TASK_QUEUE = _set_temporal_task_queue(RASTERIZATION_TASK_QUEUE = "rasterization-task-queue" # Not collapsed in dev — separate Node.js worker process# Replay Vision observation media (thumbnails, clips). Kept off the shared rasterization# queue so media never competes with customer exports and session video summaries.-RASTERIZATION_MEDIA_TASK_QUEUE = "rasterization-media-task-queue"+# Collapsed in dev, where a single rasterizer serves every queue: nothing polls the media+# queue locally, so the render would strand and the poster would never appear. Tests keep the+# split, because what they assert about routing is the production behaviour.+RASTERIZATION_MEDIA_TASK_QUEUE = RASTERIZATION_TASK_QUEUE if DEBUG and not TEST else "rasterization-media-task-queue"# Error tracking# Global on/off switch for auto-merging close fingerprints into their nearest issue.diff --git a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.pyindex 9c119be4143e..6840e972462e 100644--- a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py+++ b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py@@ -16,6 +16,7 @@ from products.exports.backend.analytics import capture_export_eventfrom products.exports.backend.models.exported_asset import ExportedAsset, is_valid_session_recording_idfrom products.exports.backend.source_authentication import assert_export_authorization+from ..storage_keys import content_location_from_s3_urifrom ..types import (RASTERIZE_RENDER_MAX_ATTEMPTS,RASTERIZE_RENDER_TIMEOUT,@@ -201,10 +202,6 @@ def finalize_rasterization(inputs: FinalizeRasterizationInput) -> None:close_old_connections()result = inputs.result- prefix = f"s3://{settings.OBJECT_STORAGE_BUCKET}/"- if not result.s3_uri.startswith(prefix):- raise ValueError(f"Unexpected s3_uri prefix: {result.s3_uri} (expected {prefix}...)")-# Row lock serializes the JSONB read-modify-write against prep_session_video_asset_activity.with transaction.atomic():asset = (@@ -212,7 +209,7 @@ def finalize_rasterization(inputs: FinalizeRasterizationInput) -> None:.select_for_update(of=("self",)).get(pk=inputs.exported_asset_id))- asset.content_location = result.s3_uri[len(prefix) :]+ asset.content_location = content_location_from_s3_uri(result.s3_uri)if asset.export_context is None:asset.export_context = {}diff --git a/posthog/temporal/session_replay/rasterize_recording/storage_keys.py b/posthog/temporal/session_replay/rasterize_recording/storage_keys.pynew file mode 100644index 000000000000..1ec0e0c835dc--- /dev/null+++ b/posthog/temporal/session_replay/rasterize_recording/storage_keys.py@@ -0,0 +1,11 @@+"""The one place that knows how the rasterizer's `s3://` output maps onto an asset's `content_location`."""++from django.conf import settings+++def content_location_from_s3_uri(s3_uri: str) -> str:+ """Strip the bucket prefix the Node uploader returns, leaving the key an ExportedAsset stores."""+ prefix = f"s3://{settings.OBJECT_STORAGE_BUCKET}/"+ if not s3_uri.startswith(prefix):+ raise ValueError(f"Unexpected s3_uri prefix: {s3_uri} (expected {prefix}...)")+ return s3_uri[len(prefix) :]diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex 7dc113efa7af..c67c548ea51c 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -99,6 +99,7 @@ post_delete:products.feature_flags.backend.local_evaluation.evaluation_context_cpost_delete:products.feature_flags.backend.local_evaluation.experiment_changedpost_delete:products.feature_flags.backend.local_evaluation.feature_flag_changedpost_delete:products.managed_warehouse.backend.models._observe_duckgres_server_delete+post_delete:products.replay_vision.backend.media_expiry.expire_media_assetpost_delete:products.signals.backend.receivers.mark_scout_suggestions_stale_on_fleet_changepost_delete:products.signals.backend.receivers.reconcile_report_embedding_on_verdict_deletedpost_delete:products.signals.backend.receivers.tombstone_report_embedding_on_hard_deletediff --git a/products/exports/backend/api/exports.py b/products/exports/backend/api/exports.pyindex c20c55b4eef1..8ffffdcbbd79 100644--- a/products/exports/backend/api/exports.py+++ b/products/exports/backend/api/exports.py@@ -549,6 +549,11 @@ class ExportedAssetViewSet(if not instance.is_session_recording_export and instance.created_by_id != self.request.user.id:raise NotFound()+ if export_context.get("observation_id"):+ # Media a product owns and authorizes on its own endpoint. This endpoint checks the recording,+ # which is a weaker gate than the one the owner applies, and asset ids are guessable integers.+ raise NotFound()+session_recording_id = export_context.get("session_recording_id")# Both can be set on one asset, and the renderer prefers the insight, so checking only thediff --git a/products/exports/backend/tasks/failure_handler.py b/products/exports/backend/tasks/failure_handler.pyindex b5816291ea8f..0b72a7a2ccd6 100644--- a/products/exports/backend/tasks/failure_handler.py+++ b/products/exports/backend/tasks/failure_handler.py@@ -108,6 +108,10 @@ RASTERIZATION_CODE_TO_FAILURE_TYPE: dict[str, str] = {"DATA_LOAD_FAILED": FAILURE_TYPE_SYSTEM,"S3_UPLOAD_UNDECODABLE_RESPONSE": FAILURE_TYPE_SYSTEM,"S3_UPLOAD_FAILED": FAILURE_TYPE_SYSTEM,+ "S3_DOWNLOAD_FAILED": FAILURE_TYPE_SYSTEM,+ "S3_DOWNLOAD_EMPTY": FAILURE_TYPE_SYSTEM,+ "THUMBNAIL_EXTRACT_FAILED": FAILURE_TYPE_SYSTEM,+ "THUMBNAIL_EMPTY_OUTPUT": FAILURE_TYPE_SYSTEM,"INIT_FAILED": FAILURE_TYPE_SYSTEM,"BLOCK_LISTING_FAILED": FAILURE_TYPE_SYSTEM,"TARGET_CLOSED": FAILURE_TYPE_SYSTEM,@@ -133,6 +137,10 @@ _RASTERIZATION_MESSAGES: dict[str, str] = {"DATA_LOAD_FAILED": "We could not load this recording's data. Try the export again in a few minutes.","S3_UPLOAD_UNDECODABLE_RESPONSE": "The finished video could not be saved. Try the export again.","S3_UPLOAD_FAILED": "The finished video could not be saved. Try the export again.",+ "S3_DOWNLOAD_FAILED": "The source video could not be read. Try again.",+ "S3_DOWNLOAD_EMPTY": "The source video is no longer stored. Render it again to create a new one.",+ "THUMBNAIL_EXTRACT_FAILED": "A still frame could not be taken from the video. Try again.",+ "THUMBNAIL_EMPTY_OUTPUT": "The video has no frame at that point. Pick an earlier time.","INIT_FAILED": "The video renderer could not start. Try the export again.","BLOCK_LISTING_FAILED": "We could not read this recording. Try the export again in a few minutes.","TARGET_CLOSED": "The video renderer stopped before it finished. Try the export again.",diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex 2b5597a11f71..c2f73e8df75f 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -12,6 +12,7 @@ from django.db.models import Case, IntegerField, Q, QuerySet, Value, Whenfrom django.db.models.fields.json import KeyTextTransform, KeyTransformfrom django.db.models.functions import Castfrom django.http.response import HttpResponseBase+from django.utils.timezone import nowimport requestsimport structlog@@ -40,7 +41,9 @@ from posthog.models.user import Userfrom posthog.permissions import is_scout_sandbox_requestfrom posthog.rate_limit import ReplayVisionSearchBurstRateThrottle, ReplayVisionSearchSustainedRateThrottlefrom posthog.renderers import ServerSentEventRenderer+from posthog.session_recordings.models.session_recording import SessionRecording+from products.exports.backend.facade.api import get_export_asset_content_responsefrom products.replay_vision.backend.api.errors import ReplayVisionErrorSerializerfrom products.replay_vision.backend.api.filters import MultiChoiceFilter, OrderByFilter, ordering_enum, split_csvfrom products.replay_vision.backend.api.observation_progress import stream_observation_progress@@ -57,6 +60,7 @@ from products.replay_vision.backend.models.replay_observation import (jsonb_typeof,)from products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabel+from products.replay_vision.backend.models.replay_observation_media import ReplayObservationMediafrom products.replay_vision.backend.models.replay_observation_view import ReplayObservationViewfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerOrigin, ScannerTypefrom products.replay_vision.backend.observation_formatting import summarize_observation@@ -189,6 +193,35 @@ class ReplayObservationLabelSerializer(serializers.Serializer):)+class ReplayObservationMediaSerializer(serializers.Serializer):+ """One thumbnail or clip illustrating an observation."""++ id = serializers.UUIDField(read_only=True, help_text="Id of this media entry.")+ 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.",+ )+ asset_id = serializers.IntegerField(+ read_only=True,+ help_text="Export asset holding the bytes; fetch it from the export content endpoint.",+ )+ description = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text="One sentence saying what the clip shows. Null for thumbnails.",+ )+ video_start_ms = serializers.IntegerField(+ read_only=True,+ help_text="Where this media starts in the analysis video, in milliseconds.",+ )+ video_end_ms = serializers.IntegerField(+ read_only=True,+ allow_null=True,+ help_text="Where a clip ends in the analysis video, in milliseconds. Null for thumbnails.",+ )++class ReplayObservationSerializer(serializers.ModelSerializer):scanner_id = serializers.UUIDField(read_only=True, help_text="The scanner that produced this observation.")scanner_origin = serializers.ChoiceField(@@ -303,6 +336,26 @@ class ReplayObservationSerializer(serializers.ModelSerializer):viewed = serializers.BooleanField(read_only=True, help_text="Whether the calling user has opened this observation.")+ media = serializers.SerializerMethodField(+ help_text="Thumbnails and clips illustrating this observation, in order. Empty until the media render finishes.",+ )++ @extend_schema_field(ReplayObservationMediaSerializer(many=True))+ def get_media(self, obj: ReplayObservation) -> list[dict]:+ return [+ {+ "id": media.id,+ "kind": media.kind,+ "asset_id": media.asset_id,+ "description": media.description,+ "video_start_ms": media.video_start_ms,+ "video_end_ms": media.video_end_ms,+ }+ for media in obj.media.all()+ # No content location means the render has not landed yet, so there is nothing to fetch.+ if media.asset.content_location+ ]+summary_line = serializers.SerializerMethodField(help_text=("One line of plain text saying what the scanner found: its verdict, score, tags or title, then its "@@ -337,6 +390,7 @@ class ReplayObservationSerializer(serializers.ModelSerializer):"next_observation_id","label","viewed",+ "media","summary_line","started_at","completed_at",@@ -1079,6 +1133,57 @@ class ReplayObservationViewSet()return Response(status=status.HTTP_204_NO_CONTENT)+ @extend_schema(+ request=None,+ 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.",+ ),+ },+ )+ @action(+ detail=True,+ methods=["GET"],+ url_path="thumbnail",+ required_scopes=["replay_scanner:read", "session_recording:read"],+ )+ 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."""+ 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+ 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.+ and not (entry.asset.expires_after is not None and entry.asset.expires_after <= now())+ ),+ None,+ )+ if media is None:+ raise NotFound("This observation has no thumbnail.")+ # 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.+ recording = SessionRecording.objects.filter(+ team_id=observation.team_id, session_id=observation.session_id+ ).first()+ if recording is not None and not self.user_access_control.check_access_level_for_object(+ recording, required_level="viewer"+ ):+ raise NotFound()+ # Served from here, not through the export content endpoint: that one authorizes a recording+ # export by the recording alone, which would let a reader denied this scanner fetch its frames.+ response = get_export_asset_content_response(asset=media.asset, download=False)+ # The response redirects to a signed, expiring URL, so a cached redirect outlives its target.+ response["Cache-Control"] = "no-store"+ return response+@extend_schema(request=None,responses={diff --git a/products/replay_vision/backend/apps.py b/products/replay_vision/backend/apps.pyindex aae792015e59..e65acee1e99e 100644--- a/products/replay_vision/backend/apps.py+++ b/products/replay_vision/backend/apps.py@@ -9,4 +9,4 @@ class ReplayVisionConfig(AppConfig):def ready(self) -> None:# Temporal workers and commands write scanners too, so the receivers connect in every process.- from products.replay_vision.backend import activity_logging # noqa: F401, PLC0415+ from products.replay_vision.backend import activity_logging, media_expiry # noqa: F401, PLC0415diff --git a/products/replay_vision/backend/media_expiry.py b/products/replay_vision/backend/media_expiry.pynew file mode 100644index 000000000000..0bcd07a047db--- /dev/null+++ b/products/replay_vision/backend/media_expiry.py@@ -0,0 +1,27 @@+"""Retiring the stored object when an observation's media row goes away.++Expire, never delete: the asset row is the only pointer to the stored object, so the sweep+(`delete_expired_assets`) needs it to delete the object and then the row. Deleting the row here would+leak the object, which is how `ee/hogai/videos/session_moments.py` leaks today.++A receiver rather than a call at each deletion site: Django sends `post_delete` per instance for+cascaded and queryset deletes alike, so a retry, a scanner delete, a team delete, the Max tool and+anything added later are all covered without the caller knowing this exists.+"""++from django.db.models.signals import post_delete+from django.dispatch import receiver+from django.utils.timezone import now++from products.exports.backend.models.exported_asset import ExportedAsset+from products.replay_vision.backend.models.replay_observation_media import ReplayObservationMedia+++@receiver(post_delete, sender=ReplayObservationMedia)+def expire_media_asset(+ sender: type[ReplayObservationMedia], instance: ReplayObservationMedia, **kwargs: object+) -> None:+ # Filtered rather than saved, so the sweep's own asset delete cascades here and matches nothing.+ ExportedAsset.objects.filter(pk=instance.asset_id, team_id=instance.team_id, expires_after__gt=now()).update(+ expires_after=now()+ )diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.pyindex 7a7335763af6..b1b20944124f 100644--- a/products/replay_vision/backend/models/replay_observation.py+++ b/products/replay_vision/backend/models/replay_observation.py@@ -6,6 +6,7 @@ from django.db.models.functions import Castfrom posthog.models.utils import UUIDModelfrom products.replay_vision.backend.error_kinds import ERROR_REASON_HELP_TEXT+from products.replay_vision.backend.models.replay_observation_media import ReplayObservationMediafrom products.replay_vision.backend.models.replay_observation_view import ReplayObservationView@@ -202,7 +203,19 @@ def hydrate_for_serialization(if viewer_id is not Noneelse Value(False, output_field=models.BooleanField()))- return qs.select_related("triggered_by_user", "label").annotate(scanner_origin=F("scanner__origin"), viewed=viewed)+ return (+ qs.select_related("triggered_by_user", "label")+ # Explicit queryset, because the serializer reads `media` off each row and the reverse manager is+ # fail-closed: without one it raises unless the caller happens to sit inside a team scope. The rows+ # are reachable only through an observation the caller already passed team filtering on.+ .prefetch_related(+ models.Prefetch(+ "media",+ queryset=ReplayObservationMedia.objects.unscoped().select_related("asset").order_by("kind", "position"),+ )+ )+ .annotate(scanner_origin=F("scanner__origin"), viewed=viewed)+ )def annotate_output_number(diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.pyindex 6d8690935878..3bf01ade1ad7 100644--- a/products/replay_vision/backend/temporal/__init__.py+++ b/products/replay_vision/backend/temporal/__init__.py@@ -21,6 +21,7 @@ from products.replay_vision.backend.temporal.activities import (fetch_session_events_activity,fetch_session_network_activity,finalize_evaluation_activity,+ finalize_observation_thumbnail_activity,find_backfill_candidates_activity,find_scanner_candidates_activity,list_enabled_scanners_activity,@@ -33,6 +34,7 @@ from products.replay_vision.backend.temporal.activities import (meter_scanner_read_bytes_activity,pause_backfill_schedule_activity,prepare_backfill_tick_activity,+ prepare_observation_thumbnail_activity,reap_backfill_schedules_activity,reap_childless_inline_scanners_activity,reap_orphaned_observations_activity,@@ -54,6 +56,7 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep import (ReplayVisionGeminiCleanupSweepWorkflow,sweep_gemini_files_activity,)+from products.replay_vision.backend.temporal.media_workflow import ObservationMediaWorkflowfrom products.replay_vision.backend.temporal.read_meter import MeterScannerReadsWorkflowfrom products.replay_vision.backend.temporal.reconciler import ReconcileScannerSchedulesWorkflowfrom products.replay_vision.backend.temporal.search_suggestions import RefreshSearchSuggestionsWorkflow@@ -72,6 +75,7 @@ WORKFLOWS = [BackfillScannerWorkflow,EvaluatePromptSuggestionWorkflow,MeterScannerReadsWorkflow,+ ObservationMediaWorkflow,ReconcileScannerSchedulesWorkflow,RefreshScannerEstimatesWorkflow,RefreshSearchSuggestionsWorkflow,@@ -100,6 +104,8 @@ ACTIVITIES: list[Callable[..., Any]] = [emit_observation_signal_activity,emit_observation_signals_activity,cleanup_gemini_file_activity,+ prepare_observation_thumbnail_activity,+ finalize_observation_thumbnail_activity,find_scanner_candidates_activity,count_in_flight_applies_activity,count_in_flight_by_team_activity,@@ -136,6 +142,7 @@ __all__ = ["BackfillScannerWorkflow","EvaluatePromptSuggestionWorkflow","MeterScannerReadsWorkflow",+ "ObservationMediaWorkflow","ReconcileScannerSchedulesWorkflow","RefreshScannerEstimatesWorkflow","RefreshSearchSuggestionsWorkflow",diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.pyindex 94b77eb93788..86b772945be6 100644--- a/products/replay_vision/backend/temporal/activities/__init__.py+++ b/products/replay_vision/backend/temporal/activities/__init__.py@@ -37,6 +37,10 @@ from products.replay_vision.backend.temporal.activities.list_stale_scanner_estimlist_stale_scanner_estimates_activity,)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_thumbnail_activity,+ prepare_observation_thumbnail_activity,+)from products.replay_vision.backend.temporal.activities.observation_state import (mark_observation_failed_activity,mark_observation_ineligible_activity,@@ -66,18 +70,13 @@ from products.replay_vision.backend.temporal.activities.upload_video_to_gemini i__all__ = ["advance_backfill_cursor_activity","advance_scanner_watermark_activity",- "delete_backfill_schedule_activity",- "find_backfill_candidates_activity",- "pause_backfill_schedule_activity",- "prepare_backfill_tick_activity",- "reap_backfill_schedules_activity",- "refresh_prompt_suggestion_activity","call_scanner_provider_activity","check_scanner_budget_activity","cleanup_gemini_file_activity","count_in_flight_applies_activity","count_in_flight_by_team_activity","create_observation_activity",+ "delete_backfill_schedule_activity","delete_scanner_schedule_activity","embed_observation_activity","emit_classifier_tags_activity",@@ -88,18 +87,25 @@ __all__ = ["fetch_session_events_activity","fetch_session_network_activity","finalize_evaluation_activity",+ "finalize_observation_thumbnail_activity",+ "find_backfill_candidates_activity","find_scanner_candidates_activity","list_enabled_scanners_activity","list_scanner_schedules_activity","list_stale_scanner_estimates_activity",- "meter_scanner_read_bytes_activity","mark_observation_failed_activity","mark_observation_ineligible_activity","mark_observation_running_activity","mark_observation_succeeded_activity",+ "meter_scanner_read_bytes_activity",+ "pause_backfill_schedule_activity",+ "prepare_backfill_tick_activity",+ "prepare_observation_thumbnail_activity",+ "reap_backfill_schedules_activity","reap_childless_inline_scanners_activity","reap_orphaned_observations_activity","record_evaluation_result_activity",+ "refresh_prompt_suggestion_activity","refresh_scanner_estimate_activity","select_evaluation_sessions_activity","upload_video_to_gemini_activity",diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.pyindex 1e147491b87b..0c7fd2c1bf82 100644--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py@@ -75,6 +75,7 @@ from products.replay_vision.backend.temporal.network_tool import (from products.replay_vision.backend.temporal.scanners import scanner_from_snapshotfrom products.replay_vision.backend.temporal.scanners.base import (STEP_CORE,+ STEP_MEDIA,STEP_SIGNALS,TIMESTAMP_CITATION_RE,BaseScanner,@@ -142,6 +143,7 @@ class _MissionOutcome:finalized: BaseScannerOutputsignals: list[SignalFinding]verification: VerificationRecord | None = None+ thumbnail_video_s: int | None = None@activity.defn@@ -321,7 +323,22 @@ async def run_scan(duration_ms = int(llm_inputs.metadata.duration_seconds * 1000)finalized = _resolve_citations(outcome.finalized, scanner, duration_ms, video_clock)signals = [_signal_on_session_clock(signal, video_clock) for signal in outcome.signals]- return ScannerCallOutput(model_output=finalized, signals=signals, verification=outcome.verification)+ return ScannerCallOutput(+ model_output=finalized,+ signals=signals,+ verification=outcome.verification,+ thumbnail_video_s=_clamp_thumbnail(outcome.thumbnail_video_s, video_clock, duration_ms),+ # Read off `outcome.signals`, which is still on the video clock; `signals` above is not.+ signal_video_spans=[(s.start_time, s.end_time) for s in outcome.signals],+ )+++def _clamp_thumbnail(thumbnail_video_s: int | None, video_clock: VideoClock, duration_ms: int) -> int | None:+ """Hold the model's pick inside the rendered video, which is shorter than the session wherever the render cut."""+ if thumbnail_video_s is None:+ return None+ ceiling = video_clock.video_duration_s if video_clock.video_duration_s is not None else duration_ms / 1000+ return max(0, min(thumbnail_video_s, int(ceiling)))def _scan_trace_id(inputs: CallScannerProviderInputs) -> str:@@ -629,7 +646,10 @@ async def _run_mission(await _delete_video_cache(cache_client, cache.name)finalized, signals = scanner.assemble(step_outputs)- return _MissionOutcome(finalized=finalized, signals=signals, verification=verification)+ thumbnail_video_s = getattr(step_outputs.get(STEP_MEDIA), "thumbnail_t", None)+ return _MissionOutcome(+ finalized=finalized, signals=signals, verification=verification, thumbnail_video_s=thumbnail_video_s+ )async def _verify_positive_verdict(@@ -794,21 +814,29 @@ async def _run_steps(for step in steps:checkpoint = len(convo)convo.append(types.Part(text=step.instruction))- result = await _run_step(- client=client,- model=model,- step=step,- convo=convo,- cache_name=cache_name,- video_part=video_part,- preamble_text=preamble_text,- dispatch=dispatch,- team_id=team_id,- tools=tools,- metric_labels=metric_labels,- trace_id=trace_id,- on_round=on_round,- )+ try:+ result = await _run_step(+ client=client,+ model=model,+ step=step,+ convo=convo,+ cache_name=cache_name,+ video_part=video_part,+ preamble_text=preamble_text,+ dispatch=dispatch,+ team_id=team_id,+ tools=tools,+ metric_labels=metric_labels,+ trace_id=trace_id,+ on_round=on_round,+ )+ except Exception as exc:+ if step.required:+ raise+ # A provider error arrives here, not as an empty output, and must not sink a paid-for scan.+ logger.warning("replay_vision.call_scanner_provider.optional_step_failed", step=step.name, error=str(exc))+ del convo[checkpoint:]+ continueif result.output is None:# Roll the failed step's half-finished exchange back so the next instruction follows the last good# model turn, not a dangling correction/tool call (which would leave two user turns in a row).diff --git a/products/replay_vision/backend/temporal/activities/observation_media.py b/products/replay_vision/backend/temporal/activities/observation_media.pynew file mode 100644index 000000000000..89fb46cc3d28--- /dev/null+++ b/products/replay_vision/backend/temporal/activities/observation_media.py@@ -0,0 +1,190 @@+from datetime import timedelta+from typing import Any+from uuid import uuid4++from django.conf import settings+from django.db import IntegrityError, transaction+from django.utils.timezone import now++import structlog+from asgiref.sync import sync_to_async+from temporalio import activity+from temporalio.exceptions import ApplicationError++from posthog.temporal.session_replay.rasterize_recording.storage_keys import content_location_from_s3_uri++from products.exports.backend.models.exported_asset import ExportedAsset+from products.replay_vision.backend.models.replay_observation import ReplayObservation+from products.replay_vision.backend.models.replay_observation_media import ReplayObservationMedia+from products.replay_vision.backend.temporal.decorators import track_activity+from products.replay_vision.backend.temporal.media_types import (+ ANALYSIS_FOOTER_HEIGHT_PX,+ FALLBACK_THUMBNAIL_FRACTION,+ THUMBNAIL_WIDTH_PX,+ ExtractThumbnailActivityInput,+ FinalizeObservationThumbnailInputs,+ ObservationMediaInputs,+ PrepareObservationThumbnailOutput,+)+from products.replay_vision.backend.temporal.video_clock import VideoClock, video_clock_from_export_context++logger = structlog.get_logger(__name__)++_MEDIA_EXPIRY = timedelta(days=90)+# ffmpeg writes no frame when the seek lands past the end of the video.+_END_MARGIN_S = 0.5+++def _media_key_prefix(team_id: int, observation_id: Any) -> str:+ # Not under `OBJECT_STORAGE_EXPORTS_FOLDER`: those rules drop an mp4 at 30 days and glacier the rest.+ return f"replay-vision/media/team-{team_id}/{observation_id}"+++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:+ return None+ for field in ("summary_segments", "reasoning_segments"):+ 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 None+++def _pick_video_time_s(+ inputs: ObservationMediaInputs, model_output: dict[str, Any] | None, clock: VideoClock | None, duration_s: float+) -> float:+ picked = float(inputs.thumbnail_video_s) if inputs.thumbnail_video_s is not None else None+ if picked is None:+ picked = _first_citation_video_s(model_output, clock)+ if picked is None and inputs.signal_video_times:+ start, end = inputs.signal_video_times[0]+ picked = (start + end) / 2+ if picked is None:+ picked = duration_s * FALLBACK_THUMBNAIL_FRACTION+ return max(0.0, min(picked, max(0.0, duration_s - _END_MARGIN_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+ asset = await ExportedAsset.objects.aget(pk=media_inputs.analysis_asset_id, team_id=media_inputs.team_id)+ 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)++ context = asset.export_context or {}+ duration_s = float(context.get("video_duration_s") or 0)+ 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.+ observation = (+ await ReplayObservation.objects.filter(pk=media_inputs.observation_id, team_id=media_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)+ 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++ export_context = {+ # 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,+ }+ # Get-or-create: a retried activity would otherwise leave a second asset and object behind.+ 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,+ )+ .order_by("id")+ .afirst()+ )+ if media_asset is None:+ media_asset = await ExportedAsset.objects.acreate(+ team_id=media_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 PrepareObservationThumbnailOutput(+ media_asset_id=media_asset.id,+ activity_input=ExtractThumbnailActivityInput(+ source_s3_uri=f"s3://{settings.OBJECT_STORAGE_BUCKET}/{asset.content_location}",+ video_time_s=video_time_s,+ footer_crop_px=ANALYSIS_FOOTER_HEIGHT_PX if context.get("show_metadata_footer") else 0,+ width=THUMBNAIL_WIDTH_PX,+ s3_bucket=settings.OBJECT_STORAGE_BUCKET,+ s3_key_prefix=_media_key_prefix(media_inputs.team_id, media_inputs.observation_id),+ id=str(uuid4()),+ ),+ video_start_ms=int(video_time_s * 1000),+ rec_start_ms=rec_start_ms,+ )+++def _link_media(inputs: FinalizeObservationThumbnailInputs, content_location: str) -> None:+ """Point the asset at the rendered object and link it, as one write.++ 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.+ """+ 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+ )+++@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++ try:+ # `for_team` resolves the canonical team with a synchronous query of its own.+ await sync_to_async(_link_media)(inputs, content_location)+ except (IntegrityError, ReplayObservation.DoesNotExist):+ # The observation went away between the render and this write, so nothing will point at the object.+ # 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()+ )+ return++ logger.info(+ "replay_vision.thumbnail_ready",+ observation_id=str(inputs.observation_id),+ asset_id=inputs.media_asset_id,+ file_size_bytes=inputs.result.file_size_bytes,+ )diff --git a/products/replay_vision/backend/temporal/media_types.py b/products/replay_vision/backend/temporal/media_types.pynew file mode 100644index 000000000000..6d71085b6d6d--- /dev/null+++ b/products/replay_vision/backend/temporal/media_types.py@@ -0,0 +1,58 @@+"""Types for the observation media workflow: one thumbnail per succeeded observation today, clips later."""++from uuid import UUID++from pydantic import BaseModel, Field++# Matches `footerHeight` in common/replay-headless/src/standalone-player.ts.+ANALYSIS_FOOTER_HEIGHT_PX = 32++THUMBNAIL_WIDTH_PX = 1280++# Far enough in to clear the loading screen a session opens on.+FALLBACK_THUMBNAIL_FRACTION = 0.25+++class ObservationMediaInputs(BaseModel, frozen=True):+ """Input to ObservationMediaWorkflow, started fail-soft once an observation has succeeded."""++ team_id: int+ observation_id: UUID+ session_id: str+ analysis_asset_id: int+ # Video-time seconds, used to pick a moment when the model cited none.+ signal_video_times: list[tuple[int, int]] = Field(default_factory=list)+ thumbnail_video_s: int | None = None+++class ExtractThumbnailActivityInput(BaseModel, frozen=True):+ """Input sent to the Node.js `extract-thumbnail` activity; field names match its TypeScript interface."""++ source_s3_uri: str+ video_time_s: float+ footer_crop_px: int = ANALYSIS_FOOTER_HEIGHT_PX+ width: int = THUMBNAIL_WIDTH_PX+ s3_bucket: str+ s3_key_prefix: str+ id: str+++class ExtractThumbnailActivityOutput(BaseModel, frozen=True):+ s3_uri: str+ file_size_bytes: int = 0+++class PrepareObservationThumbnailOutput(BaseModel, frozen=True):+ media_asset_id: int+ activity_input: ExtractThumbnailActivityInput+ video_start_ms: int+ rec_start_ms: int | None+++class FinalizeObservationThumbnailInputs(BaseModel, frozen=True):+ team_id: int+ observation_id: UUID+ media_asset_id: int+ video_start_ms: int+ rec_start_ms: int | None+ result: ExtractThumbnailActivityOutputdiff --git a/products/replay_vision/backend/temporal/media_workflow.py b/products/replay_vision/backend/temporal/media_workflow.pynew file mode 100644index 000000000000..091cb1c91b0e--- /dev/null+++ b/products/replay_vision/backend/temporal/media_workflow.py@@ -0,0 +1,61 @@+import datetime as dt++import temporalio.workflow as wf+from temporalio import common++from posthog.temporal.common.base import PostHogWorkflow++with wf.unsafe.imports_passed_through():+ from django.conf import settings++ from products.replay_vision.backend.temporal.activities.observation_media import (+ finalize_observation_thumbnail_activity,+ prepare_observation_thumbnail_activity,+ )+ from products.replay_vision.backend.temporal.media_types import (+ ExtractThumbnailActivityOutput,+ FinalizeObservationThumbnailInputs,+ ObservationMediaInputs,+ PrepareObservationThumbnailOutput,+ )++_THUMBNAIL_TIMEOUT = dt.timedelta(minutes=5)+_STATE_RETRY = common.RetryPolicy(maximum_attempts=3)++[email protected](name="replay-vision-media")+class ObservationMediaWorkflow(PostHogWorkflow):+ """Render the media that illustrates one succeeded observation. Today that is a single thumbnail."""++ inputs_cls = ObservationMediaInputs++ @wf.run+ async def run(self, inputs: ObservationMediaInputs) -> None:+ prepared: PrepareObservationThumbnailOutput = await wf.execute_activity(+ prepare_observation_thumbnail_activity,+ inputs,+ start_to_close_timeout=dt.timedelta(seconds=30),+ retry_policy=_STATE_RETRY,+ )++ raw_result = await wf.execute_activity(+ "extract-thumbnail",+ prepared.activity_input.model_dump(exclude_none=True),+ task_queue=settings.RASTERIZATION_MEDIA_TASK_QUEUE,+ start_to_close_timeout=_THUMBNAIL_TIMEOUT,+ retry_policy=common.RetryPolicy(maximum_attempts=2),+ )++ await wf.execute_activity(+ finalize_observation_thumbnail_activity,+ FinalizeObservationThumbnailInputs(+ team_id=inputs.team_id,+ observation_id=inputs.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.model_validate(raw_result),+ ),+ start_to_close_timeout=dt.timedelta(seconds=30),+ retry_policy=_STATE_RETRY,+ )diff --git a/products/replay_vision/backend/temporal/scanners/base.py b/products/replay_vision/backend/temporal/scanners/base.pyindex 02489c0e3223..c2f8f9e1a2f1 100644--- a/products/replay_vision/backend/temporal/scanners/base.py+++ b/products/replay_vision/backend/temporal/scanners/base.py@@ -40,6 +40,7 @@ MIN_SIGNAL_CONFIDENCE = 0.4# Stable step names the producer (`mission_steps`) and consumers (`assemble`) key on.STEP_CORE = "core"STEP_SIGNALS = "signals"+STEP_MEDIA = "media"# Ceiling on one step's response, thought tokens included, because Gemini counts thinking against the cap.# Every response schema is a few hundred tokens of JSON, so this only bounds the tail: a model that thinks@@ -48,6 +49,10 @@ STEP_SIGNALS = "signals"# a re-prompt that bills them again.STEP_MAX_OUTPUT_TOKENS = 16_384+# The media turn answers with one integer, so its whole cost is the thinking in front of it. Held well+# below the shared cap, because this turn rides every scan in the product.+MEDIA_STEP_MAX_OUTPUT_TOKENS = 2_048+class SignalFinding(BaseModel, frozen=True):"""Optional side-mission finding: a bug, crash, or design flaw the recording itself reveals. See the side-mission prompt block."""@@ -111,6 +116,18 @@ class SignalsResponse(BaseModel, frozen=True):return self+class MediaResponse(BaseModel, frozen=True):+ """The media turn's structured output: which frame of the video illustrates the finding."""++ thumbnail_t: int = Field(+ ge=0,+ description=(+ "The moment to cut the thumbnail from, 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`."+ ),+ )++@dataclass(frozen=True)class MissionStep:"""One structured turn in a scanner's conversation: an instruction, the schema the model must answer with,@@ -275,12 +292,24 @@ class BaseScanner(BaseModel, frozen=True):]def mission_steps(self) -> list[MissionStep]:- """The full ordered turn list: the core task, then the signals side mission when enabled."""+ """The full ordered turn list: the core task, the signals side mission when enabled, then the media turn."""steps = self.core_steps()if self.emits_signals:steps.append(self._signals_step())+ steps.append(self._media_step())return steps+ def _media_step(self) -> MissionStep:+ instruction = render_prompt("media_step.jinja")+ # Best-effort, and last, so the thumbnail can never move a calibrated answer or sink a paid-for scan.+ return MissionStep(+ name=STEP_MEDIA,+ instruction=instruction,+ response_model=MediaResponse,+ required=False,+ max_output_tokens=MEDIA_STEP_MAX_OUTPUT_TOKENS,+ )+def _signals_step(self) -> MissionStep:instruction = render_prompt("signals_step.jinja", min_signal_confidence=MIN_SIGNAL_CONFIDENCE)# Best-effort: a side-mission failure must not sink the whole scan.diff --git a/products/replay_vision/backend/temporal/scanners/prompts/media_step.jinja b/products/replay_vision/backend/temporal/scanners/prompts/media_step.jinjanew file mode 100644index 000000000000..0fc49a574808--- /dev/null+++ b/products/replay_vision/backend/temporal/scanners/prompts/media_step.jinja@@ -0,0 +1,5 @@+Last pass, and a small one. Pick the single frame that best illustrates what you found, so a person scanning a list of recordings can tell at a glance what this one is about.++Give the moment in `thumbnail_t`, in whole seconds of video time — the same scale you cite moments in, not the footer's `REC_T`.++Pick a frame where the screen shows the thing itself: the error, the broken layout, the step the user was stuck on, the page your answer is about. Avoid a blank page, a full-page spinner, a modal backdrop mid-fade, and the first seconds of the recording, which are usually still loading. When nothing stands out, pick a moment where the user was clearly doing something rather than the start of the video.diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.pyindex f186a387e20e..e8308d58f449 100644--- a/products/replay_vision/backend/temporal/types.py+++ b/products/replay_vision/backend/temporal/types.py@@ -274,6 +274,10 @@ class ScannerCallOutput(BaseModel, frozen=True):# Extracted from the LLM response before `finalize` so per-type output mapping can't drop them.signals: list[SignalFinding] = Field(default_factory=list)verification: VerificationRecord | None = None+ # Video seconds the model picked for the thumbnail; None when the best-effort media turn produced nothing.+ thumbnail_video_s: int | None = None+ # Signal spans on the video clock, which `signals` no longer carries once they move to session time.+ signal_video_spans: list[tuple[int, int]] = Field(default_factory=list)class CleanupGeminiFileInputs(BaseModel, frozen=True):diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.pyindex ec61a47c1592..6d6d7aa442a9 100644--- a/products/replay_vision/backend/temporal/workflow.py+++ b/products/replay_vision/backend/temporal/workflow.py@@ -11,6 +11,7 @@ from temporalio.exceptions import (ChildWorkflowError,TimeoutError as TemporalTimeoutError,)+from temporalio.workflow import ParentClosePolicyfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.errors import MAX_ERROR_MESSAGE_CHARS, truncate_for_temporal_payload, unwrap_temporal_cause@@ -55,6 +56,7 @@ from products.replay_vision.backend.temporal.errors import (IneligibleSessionKind,ScannerFailureError,)+from products.replay_vision.backend.temporal.media_types import ObservationMediaInputsfrom products.replay_vision.backend.temporal.scanners.base import BaseScannerOutputfrom products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutputfrom products.replay_vision.backend.temporal.types import (@@ -410,6 +412,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):)except Exception:wf.logger.exception("Event emission failed for succeeded observation %s", observation_id)+ await self._render_media(inputs, observation_id, asset_result.asset_id, call_output)await self._apply_scanner_side_effects(inputs, observation_id, call_output.model_output)except Exception as e:ineligible_kind = _extract_kind_for_type(e, INELIGIBLE_SESSION_ERROR_TYPE)@@ -553,6 +556,40 @@ class ApplyScannerWorkflow(PostHogWorkflow):# Re-classify the rasterizer's failure so the user sees a rasterizer label, not a generic "internal error".raise ScannerFailureError(_root_cause_message(e), kind=FailureKind.RASTERIZATION_FAILED) from e+ async def _render_media(+ self,+ inputs: ApplyScannerInputs,+ observation_id: UUID,+ analysis_asset_id: int,+ call_output: ScannerCallOutput,+ ) -> None:+ """Render the observation's thumbnail. Fail-soft: a missing poster must never fail a paid-for scan."""+ if not wf.patched("replay-vision-media-2026-09"):+ return+ try:+ # Started, not awaited: the poster is delivery, and the scan has no reason to hold a workflow+ # slot open while one frame is cut. ABANDON keeps the child alive past the parent's close.+ await wf.start_child_workflow(+ "replay-vision-media",+ ObservationMediaInputs(+ team_id=inputs.team_id,+ observation_id=observation_id,+ session_id=inputs.session_id,+ analysis_asset_id=analysis_asset_id,+ signal_video_times=call_output.signal_video_spans,+ thumbnail_video_s=call_output.thumbnail_video_s,+ ),+ id=f"replay-vision-media-{observation_id}",+ task_queue=settings.REPLAY_VISION_TASK_QUEUE,+ # A retried observation reuses its id, and the run it supersedes has long closed.+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ parent_close_policy=ParentClosePolicy.ABANDON,+ retry_policy=common.RetryPolicy(maximum_attempts=2),+ execution_timeout=dt.timedelta(minutes=20),+ )+ except Exception:+ wf.logger.exception("Media rendering could not be started for observation %s", observation_id)+async def _mark_failed(self, observation_id: UUID, scanner_type: ScannerType, kind: str, message: str) -> None:await wf.execute_activity(mark_observation_failed_activity,diff --git a/products/replay_vision/backend/tests/test_access_control.py b/products/replay_vision/backend/tests/test_access_control.pyindex 5715be5b2252..e5a95c7014b7 100644--- a/products/replay_vision/backend/tests/test_access_control.py+++ b/products/replay_vision/backend/tests/test_access_control.py@@ -2,13 +2,17 @@ from unittest.mock import MagicMock, patchfrom django.db import connectionfrom django.test.utils import CaptureQueriesContext+from django.utils import timezonefrom posthog.constants import AvailableFeaturefrom posthog.models import OrganizationMembership, PersonalAPIKey, Userfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.session_recordings.models.session_recording import SessionRecordingfrom products.access_control.backend.models.access_control import AccessControl+from products.exports.backend.models.exported_asset import ExportedAssetfrom products.replay_vision.backend.models.replay_observation import ReplayObservation+from products.replay_vision.backend.models.replay_observation_media import ReplayObservationMediafrom products.replay_vision.backend.tests.helpers import create_experiment, snapshot_forfrom products.replay_vision.backend.tests.test_api import _VisionAPITestCase@@ -457,3 +461,50 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):for sql in observation_reads:self.assertNotIn("SELECT DISTINCT", sql, sql)self.assertTrue(observation.id.hex in sql or sql.endswith("LIMIT 1"), sql)+++class TestObservationThumbnailAccessControl(_AccessControlTestCase):+ """The frame is recording content, so denying the recording has to hide it."""++ def setUp(self) -> None:+ super().setUp()+ self._set_resource_default("session_recording", "editor")+ self._set_resource_default("replay_scanner", "editor")+ self.scanner = self._create_scanner()+ self.observation = ReplayObservation.objects.create(+ scanner=self.scanner,+ team=self.team,+ session_id="sess-thumbnail",+ status="succeeded",+ completed_at=timezone.now(),+ triggered_by="schedule",+ scanner_snapshot=snapshot_for(self.scanner),+ )+ asset = ExportedAsset.objects.create(+ team=self.team,+ export_format=ExportedAsset.ExportFormat.PNG,+ export_context={"observation_id": str(self.observation.id)},+ content_location=f"replay-vision/media/team-{self.team.id}/{self.observation.id}/x.png",+ is_system=True,+ )+ ReplayObservationMedia.objects.for_team(self.team.id).create(+ observation=self.observation,+ asset=asset,+ kind=ReplayObservationMedia.Kind.THUMBNAIL,+ position=0,+ video_start_ms=1000,+ )+ self.recording = SessionRecording.objects.create(team=self.team, session_id=self.observation.session_id)+ self.url = f"{self.observations_url(str(self.scanner.id))}{self.observation.id}/thumbnail/"++ def test_a_reader_of_the_recording_gets_the_frame(self) -> None:+ self.client.force_login(self.other_user)++ self.assertEqual(self.client.get(self.url).status_code, 302)++ def test_a_reader_denied_the_recording_does_not(self) -> None:+ # Object-level access keys on the row id, which is what `check_access_level_for_object` reads.+ self._grant_object_access(self.other_user, "session_recording", str(self.recording.id), "none")+ self.client.force_login(self.other_user)++ self.assertEqual(self.client.get(self.url).status_code, 404)diff --git a/products/replay_vision/backend/tests/test_call_scanner_provider.py b/products/replay_vision/backend/tests/test_call_scanner_provider.pyindex 28704c2e41e4..541185e80abf 100644--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py@@ -19,6 +19,7 @@ from posthog.dataclasses import frozenfrom products.replay_vision.backend.models.replay_scanner import ScannerTypefrom products.replay_vision.backend.temporal.activities.call_scanner_provider import (+ _clamp_thumbnail,_maybe_create_video_cache,_MissionOutcome,_remaining_verify_budget_seconds,@@ -33,6 +34,7 @@ from products.replay_vision.backend.temporal.events_tool import events_toolfrom products.replay_vision.backend.temporal.metrics import REPLAY_VISION_VERIFICATION_OUTCOMESfrom products.replay_vision.backend.temporal.scanners.base import (STEP_MAX_OUTPUT_TOKENS,+ MediaResponse,MissionStep,SignalFinding,SignalsResponse,@@ -85,7 +87,8 @@ class _Resp:class _FakeModels:def __init__(self, responses: list[_Resp]) -> None:- self._it = iter(responses)+ # Every full mission ends with the best-effort media turn, which no test is about.+ self._it = iter([*responses, _Resp(text=MediaResponse(thumbnail_t=1).model_dump_json())])self.calls: list[dict[str, Any]] = []async def generate_content(self, **kwargs: Any) -> _Resp:@@ -435,7 +438,45 @@ async def test_signal_timestamps_use_recording_duration()assert cast(MonitorOutput, outcome.finalized).verdict == "yes"assert outcome.signals == ([] if expected_end is None else [signal.model_copy(update={"end_time": expected_end})])- assert len(client.models.calls) == 1 + len(end_times)+ assert len(client.models.calls) == 2 + len(end_times)+++async def test_a_provider_error_on_a_non_required_step_leaves_the_scan_standing() -> None:+ # A provider blip on the last, optional turn used to fail the whole paid-for scan.+ steps = [+ MissionStep(name="summary", instruction="sum", response_model=_Core),+ MissionStep(name="media", instruction="pick", response_model=_Side, required=False),+ ]++ class _ExplodingModels(_FakeModels):+ async def generate_content(self, **kwargs: Any) -> _Resp:+ if len(self.calls) >= 1:+ raise RuntimeError("provider is down")+ return await super().generate_content(**kwargs)++ client = _FakeClient([_Resp(text='{"verdict":"yes"}')])+ client.models = _ExplodingModels([_Resp(text='{"verdict":"yes"}')])++ out = await _run(client, steps)++ assert "summary" in out+ assert "media" not in out+++async def test_a_provider_error_on_a_required_step_still_fails_the_scan() -> None:+ steps = [MissionStep(name="summary", instruction="sum", response_model=_Core)]++ class _ExplodingModels(_FakeModels):+ async def generate_content(self, **kwargs: Any) -> _Resp:+ raise RuntimeError("provider is down")++ client = _FakeClient([])+ client.models = _ExplodingModels([])++ with pytest.raises(RuntimeError):+ await _run(client, steps)@pytest.mark.asyncio@@ -649,15 +690,11 @@ class TestVerifyPositives:calls.append({"steps": [step.name for step in steps], "cache_name": cache_name})# Collect rather than assert: the verify draw runs inside an `except Exception` that turns any# error into `draw_failed`, so an assertion raised here would pass the test instead of failing it.- unchecked_steps.extend(- step.name- for step in steps- if step.name != "signals" and not (step.required and step.validate is not None)- )+ unchecked_steps.extend(step.name for step in steps if step.required and step.validate is None)answer = next(pending)if isinstance(answer, Exception):raise answer- return {step.name: self._answer(answer) for step in steps if step.name != "signals"}+ return {step.name: self._answer(answer) for step in steps if step.required}async def fake_delete(*_: Any) -> None:calls.append("delete_cache")@@ -817,7 +854,7 @@ class TestVerifyPositives:async def test_verify_draws_are_blind_core_only_turns_over_the_live_cache(self) -> None:run = await self._scan(mode="enforce", answers=["yes", "no"], emits_signals=True)assert run.calls == [- {"steps": ["core", "signals"], "cache_name": "caches/abc"},+ {"steps": ["core", "signals", "media"], "cache_name": "caches/abc"},{"steps": ["core_verify_2"], "cache_name": "caches/abc"},"delete_cache",]@@ -875,3 +912,17 @@ async def test_video_cache_creation_is_best_effort() -> None:cast(Any, _BoomClient()), "models/gemini-3-flash-preview", _VIDEO, "PRE", tools=[events_tool()])assert result is None+++ "picked,expected",+ [+ (None, None),+ (5, 5),+ (40, 30),+ (-3, 0),+ ],+)+def test_the_thumbnail_pick_is_held_inside_the_rendered_video(picked: int | None, expected: int | None) -> None:+ # A seek past the end makes ffmpeg exit 0 with no frame, which would leave the observation without a poster.+ assert _clamp_thumbnail(picked, _IDENTITY_CLOCK, duration_ms=30_000) == expecteddiff --git a/products/replay_vision/backend/tests/test_observation_media.py b/products/replay_vision/backend/tests/test_observation_media.pynew file mode 100644index 000000000000..cc0fa856d507--- /dev/null+++ b/products/replay_vision/backend/tests/test_observation_media.py@@ -0,0 +1,271 @@+from datetime import datetime, timedelta+from typing import Any++from posthog.test.base import BaseTest++from django.conf import settings+from django.utils import timezone++from asgiref.sync import async_to_sync+from parameterized import parameterized++from posthog.models.utils import uuid7++from products.exports.backend.models.exported_asset import ExportedAsset+from products.replay_vision.backend.api.observations import ReplayObservationSerializer+from products.replay_vision.backend.models.replay_observation import (+ ObservationStatus,+ ObservationTrigger,+ ReplayObservation,+ hydrate_for_serialization,+)+from products.replay_vision.backend.models.replay_observation_media import ReplayObservationMedia+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.temporal.activities.observation_media import (+ finalize_observation_thumbnail_activity,+ prepare_observation_thumbnail_activity,+)+from products.replay_vision.backend.temporal.media_types import (+ ExtractThumbnailActivityOutput,+ FinalizeObservationThumbnailInputs,+ ObservationMediaInputs,+)+from products.replay_vision.backend.tests.helpers import snapshot_for+++class TestObservationMedia(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.scanner = ReplayScanner.objects.create(+ team=self.team,+ name="Checkout monitor",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "did the user check out?"},+ model=ScannerModel.GEMINI_3_8_FLASH,+ )+ self.session_id = f"s-{uuid7()}"+ self.observation = ReplayObservation.objects.create(+ scanner=self.scanner,+ team=self.team,+ session_id=self.session_id,+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ scanner_snapshot=snapshot_for(self.scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ )+ self.analysis_asset = ExportedAsset.objects.create(+ team=self.team,+ export_format=ExportedAsset.ExportFormat.MP4,+ export_context={+ "session_recording_id": self.session_id,+ "video_duration_s": 100,+ "show_metadata_footer": True,+ },+ content_location="exports/mp4/team-1/task-1",+ is_system=True,+ )++ def _prepare(self, **overrides: Any) -> Any:+ fields: dict[str, Any] = {+ "team_id": self.team.id,+ "observation_id": self.observation.id,+ "session_id": self.session_id,+ "analysis_asset_id": self.analysis_asset.id,+ }+ fields.update(overrides)+ return async_to_sync(prepare_observation_thumbnail_activity)(ObservationMediaInputs(**fields))++ def test_media_object_is_written_outside_the_exports_prefix(self) -> None:+ prepared = self._prepare()++ 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)+ 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+ assert asset.expires_after is not None+ assert 89 <= (asset.expires_after - asset.created_at).days <= 90++ def test_the_models_pick_wins_over_every_fallback(self) -> None:+ self.observation.scanner_result = {+ "model_output": {"summary_segments": [{"kind": "chip", "timestamp_ms": 12_000}]}+ }+ self.observation.save(update_fields=["scanner_result"])++ prepared = self._prepare(thumbnail_video_s=70, signal_video_times=[(40, 60)])++ assert prepared.activity_input.video_time_s == 70.0++ @parameterized.expand(+ [+ ("citation_wins", {"summary_segments": [{"kind": "chip", "timestamp_ms": 12_000}]}, [(40, 60)], 12.0),+ ("signal_midpoint", {"summary_segments": [{"kind": "text", "value": "no chip"}]}, [(40, 60)], 50.0),+ ("quarter_of_the_video", {}, [], 25.0),+ ]+ )+ def test_thumbnail_moment(+ self, _name: str, model_output: dict[str, Any], signals: list[tuple[int, int]], expected_s: float+ ) -> None:+ self.observation.scanner_result = {"model_output": model_output}+ self.observation.save(update_fields=["scanner_result"])++ 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)++ def test_finalize_links_the_rendered_object_to_the_observation(self) -> None:+ prepared = self._prepare()++ 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,+ ),+ )+ )++ 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/")++ 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,+ ),+ )+ )++ asset = ExportedAsset.objects_including_ttl_deleted.get(pk=prepared.media_asset_id)+ assert asset.expires_after is not None+ assert (asset.content_location or "").startswith("replay-vision/media/")+++class TestObservationMediaExpiry(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.scanner = ReplayScanner.objects.create(+ team=self.team,+ name="Checkout monitor",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "did the user check out?"},+ model=ScannerModel.GEMINI_3_8_FLASH,+ )+ self.observation = ReplayObservation.objects.create(+ scanner=self.scanner,+ team=self.team,+ session_id=f"s-{uuid7()}",+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ scanner_snapshot=snapshot_for(self.scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ )+ self.asset = ExportedAsset.objects.create(+ team=self.team,+ export_format=ExportedAsset.ExportFormat.PNG,+ export_context={"observation_id": str(self.observation.id)},+ content_location=f"replay-vision/media/team-{self.team.id}/{self.observation.id}/x.png",+ expires_after=timezone.now() + timedelta(days=90),+ is_system=True,+ )+ ReplayObservationMedia.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ observation=self.observation,+ asset=self.asset,+ kind=ReplayObservationMedia.Kind.THUMBNAIL,+ position=0,+ video_start_ms=1000,+ )++ def _expires_after(self) -> datetime:+ expires_after = ExportedAsset.objects_including_ttl_deleted.get(pk=self.asset.pk).expires_after+ assert expires_after is not None+ return expires_after++ @parameterized.expand(+ [+ # Every path that removes an observation reaches the media row through a cascade.+ ("observation delete, as a retry does", lambda self: self.observation.delete()),+ ("scanner delete", lambda self: self.scanner.delete()),+ ]+ )+ def test_media_is_expired_when_its_observation_goes_away(self, _name: str, delete) -> None:+ delete(self)++ assert self._expires_after() <= timezone.now()+ assert ExportedAsset.objects_including_ttl_deleted.filter(pk=self.asset.pk).exists()++ def test_the_sweeps_own_delete_is_not_undone(self) -> None:+ self.asset.delete()++ assert not ExportedAsset.objects_including_ttl_deleted.filter(pk=self.asset.pk).exists()+++class TestObservationMediaSerialization(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ scanner = ReplayScanner.objects.create(+ team=self.team,+ name="Checkout monitor",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "did the user check out?"},+ model=ScannerModel.GEMINI_3_8_FLASH,+ )+ self.observation = ReplayObservation.objects.create(+ scanner=scanner,+ team=self.team,+ session_id=f"s-{uuid7()}",+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ scanner_snapshot=snapshot_for(scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ )++ def _add_media(self, *, rendered: bool, position: int = 0) -> ReplayObservationMedia:+ asset = ExportedAsset.objects.create(+ team=self.team,+ export_format=ExportedAsset.ExportFormat.PNG,+ export_context={"observation_id": str(self.observation.id)},+ content_location=f"replay-vision/media/team-{self.team.id}/x-{position}.png" if rendered else None,+ is_system=True,+ )+ return ReplayObservationMedia.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ observation=self.observation,+ asset=asset,+ kind=ReplayObservationMedia.Kind.THUMBNAIL,+ position=position,+ video_start_ms=1000 * (position + 1),+ )++ def test_only_rendered_media_is_served(self) -> None:+ ready = self._add_media(rendered=True, position=0)+ self._add_media(rendered=False, position=1)++ observation = hydrate_for_serialization(ReplayObservation.objects.filter(pk=self.observation.pk)).get()+ media = ReplayObservationSerializer(observation).data["media"]++ assert [entry["id"] for entry in media] == [ready.id]+ assert media[0]["asset_id"] == ready.asset_id+ assert media[0]["video_start_ms"] == 1000diff --git a/products/replay_vision/backend/tests/test_observation_thumbnail_api.py b/products/replay_vision/backend/tests/test_observation_thumbnail_api.pynew file mode 100644index 000000000000..8fb395dc6be7--- /dev/null+++ b/products/replay_vision/backend/tests/test_observation_thumbnail_api.py@@ -0,0 +1,82 @@+from datetime import timedelta++from django.utils import timezone++from products.exports.backend.models.exported_asset import ExportedAsset+from products.replay_vision.backend.models.replay_observation import (+ ObservationStatus,+ ObservationTrigger,+ ReplayObservation,+)+from products.replay_vision.backend.models.replay_observation_media import ReplayObservationMedia+from products.replay_vision.backend.tests.test_api import _VisionAPITestCase+++class TestObservationThumbnail(_VisionAPITestCase):+ def setUp(self) -> None:+ super().setUp()+ self.scanner = self._create_scanner()+ self.observation = ReplayObservation.objects.create(+ scanner=self.scanner,+ team=self.team,+ session_id="sess-1",+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ triggered_by=ObservationTrigger.ON_DEMAND,+ )++ def _url(self) -> str:+ return f"{self.observations_url(self.scanner.id)}{self.observation.id}/thumbnail/"++ def _add_thumbnail(self, *, rendered: bool) -> ExportedAsset:+ asset = ExportedAsset.objects.create(+ team=self.team,+ export_format=ExportedAsset.ExportFormat.PNG,+ export_context={"observation_id": str(self.observation.id)},+ content_location=f"replay-vision/media/team-{self.team.id}/{self.observation.id}/x.png"+ if rendered+ else None,+ is_system=True,+ )+ ReplayObservationMedia.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ observation=self.observation,+ asset=asset,+ kind=ReplayObservationMedia.Kind.THUMBNAIL,+ position=0,+ video_start_ms=1000,+ )+ return asset++ def test_it_serves_the_image(self) -> None:+ self._add_thumbnail(rendered=True)++ response = self.client.get(self._url())++ assert response.status_code in (200, 302)+ # 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_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.+ asset = self._add_thumbnail(rendered=True)++ response = self.client.get(f"/api/projects/{self.team.id}/exports/{asset.id}/content")++ assert response.status_code == 404++ def test_an_unfinished_render_is_not_found(self) -> None:+ self._add_thumbnail(rendered=False)++ assert self.client.get(self._url()).status_code == 404++ def test_an_expired_frame_is_not_served(self) -> None:+ # The sweep deletes the object some time after the row expires, and until then the join would+ # still hand it out.+ asset = self._add_thumbnail(rendered=True)+ ExportedAsset.objects_including_ttl_deleted.filter(pk=asset.pk).update(+ expires_after=timezone.now() - timedelta(seconds=1)+ )++ assert self.client.get(self._url()).status_code == 404diff --git a/products/replay_vision/backend/tests/test_scanners.py b/products/replay_vision/backend/tests/test_scanners.pyindex 78fd8038756a..57a3aa161484 100644--- a/products/replay_vision/backend/tests/test_scanners.py+++ b/products/replay_vision/backend/tests/test_scanners.py@@ -857,12 +857,12 @@ class TestSignalSideMission:def test_mission_excludes_signals_step_by_default(self) -> None:scanner = scanner_from_db(_build_replay_scanner())- assert [s.name for s in scanner.mission_steps()] == ["core"]+ assert [s.name for s in scanner.mission_steps()] == ["core", "media"]assert _signals_step(scanner) is Nonedef test_mission_appends_signals_step_when_emitting(self) -> None:scanner = scanner_from_db(_build_replay_scanner(emits_signals=True))- step = scanner.mission_steps()[-1]+ step = scanner.mission_steps()[-2]assert step.name == "signals"assert step.response_model is SignalsResponse# The side mission is best-effort: a failed signals turn must not sink the scan.@@ -873,7 +873,7 @@ class TestSignalSideMission:scanner = scanner_from_db(_build_replay_scanner(scanner_type=scanner_type, scanner_config=config, emits_signals=True))- assert scanner.mission_steps()[-1].name == "signals"+ assert scanner.mission_steps()[-2].name == "signals"@pytest.mark.parametrize("start_time, end_time", [(0, 0), (72, 72), (72, 78)])def test_signals_parse_and_assemble_alongside_output(self, start_time: int, end_time: int) -> None:diff --git a/products/replay_vision/frontend/components/ObservationThumbnail.stories.tsx b/products/replay_vision/frontend/components/ObservationThumbnail.stories.tsxnew file mode 100644index 000000000000..778560954392--- /dev/null+++ b/products/replay_vision/frontend/components/ObservationThumbnail.stories.tsx@@ -0,0 +1,45 @@+import { Meta, StoryFn } from '@storybook/react'++import { IconPlayFilled } from '@posthog/icons'++import { mswDecorator } from '~/mocks/browser'+import { sessionFrameResponse } from '~/mocks/fixtures/sessionFrame'++import { ReplayObservationApi } from '../generated/api.schemas'+import { ObservationThumbnail } from './ObservationThumbnail'++const withFrame = {+ id: '0198f2a1-0000-7000-8000-000000000001',+ media: [{ id: '0198f2a1-0000-7000-8000-0000000000f1', kind: 'thumbnail', asset_id: 4001 }],+} as unknown as ReplayObservationApi++const withoutFrame = { id: '0198f2a1-0000-7000-8000-000000000002', media: [] } as unknown as ReplayObservationApi++const meta: Meta<typeof ObservationThumbnail> = {+ title: 'Scenes-App/Replay Vision/ObservationThumbnail',+ component: ObservationThumbnail,+ decorators: [+ mswDecorator({+ get: { '/api/projects/:team_id/vision/observations/:id/thumbnail/': () => sessionFrameResponse() },+ }),+ ],+}+export default meta++export const Frame: StoryFn = () => <ObservationThumbnail observation={withFrame} className="w-80" />++export const FrameAsAPlayTarget: StoryFn = () => (+ <ObservationThumbnail observation={withFrame} className="w-80">+ <IconPlayFilled className="text-xl text-brand-red drop-shadow" />+ </ObservationThumbnail>+)++// What an observation scanned before this shipped looks like, until a backfill gives it a frame.+export const NoFrameYet: StoryFn = () => <ObservationThumbnail observation={withoutFrame} className="w-80" />++export const FrameFailsToLoad: StoryFn = () => <ObservationThumbnail observation={withFrame} className="w-80" />+FrameFailsToLoad.decorators = [+ mswDecorator({+ get: { '/api/projects/:team_id/vision/observations/:id/thumbnail/': () => [500, {}] },+ }),+]diff --git a/products/replay_vision/frontend/components/ObservationThumbnail.tsx b/products/replay_vision/frontend/components/ObservationThumbnail.tsxnew file mode 100644index 000000000000..a8b59d5139f5--- /dev/null+++ b/products/replay_vision/frontend/components/ObservationThumbnail.tsx@@ -0,0 +1,80 @@+import { useValues } from 'kea'+import { useEffect, useRef, useState } from 'react'++import { IconVideoCamera } from '@posthog/icons'++import { teamLogic } from 'scenes/teamLogic'++import { getVisionObservationsThumbnailRetrieveUrl } from '../generated/api'+import { ReplayObservationApi } from '../generated/api.schemas'++interface ObservationThumbnailProps {+ observation: ReplayObservationApi+ /** Sizing and shape come from the caller, since a table cell and a detail page want very different frames. */+ className?: string+ children?: React.ReactNode+}++const RETRY_DELAY_MS = 2000++/** The frame the scan picked out of the session, as a 16:9 poster. */+export function ObservationThumbnail({ observation, className, children }: ObservationThumbnailProps): JSX.Element {+ const { currentTeamId } = useValues(teamLogic)+ const [attempt, setAttempt] = useState(0)+ const [failedId, setFailedId] = useState<string | null>(null)+ const retryTimer = useRef<ReturnType<typeof setTimeout> | null>(null)++ // A row's instance is reused as the table pages, so a failure can outlive the observation it was for.+ useEffect(() => {+ setAttempt(0)+ setFailedId(null)+ }, [observation.id])++ useEffect(() => {+ return () => {+ if (retryTimer.current !== null) {+ clearTimeout(retryTimer.current)+ }+ }+ }, [])++ const failed = failedId === observation.id++ // Gated on the media the list response already carried, so a page of observations without one costs+ // no requests. The URL is the endpoint rather than the asset, so a re-render after a retry still resolves.+ // Optional at runtime, whatever the generated type says: fixtures and a response cached from before+ // the field existed both reach here, and a poster must not take the scene down with it.+ const hasThumbnail = (observation.media ?? []).some((entry) => entry.kind === 'thumbnail')+ const baseSrc =+ hasThumbnail && currentTeamId !== null && !failed+ ? getVisionObservationsThumbnailRetrieveUrl(String(currentTeamId), observation.id)+ : undefined+ const src = baseSrc !== undefined && attempt > 0 ? `${baseSrc}?retry=${attempt}` : baseSrc++ const onError = (): void => {+ // One retry: the redirect target can blink, and the poster would stay blank for the whole mount.+ if (attempt === 0) {+ retryTimer.current = setTimeout(() => setAttempt(1), RETRY_DELAY_MS)+ return+ }+ setFailedId(observation.id)+ }++ return (+ <div className={`relative aspect-video overflow-hidden rounded border bg-surface-secondary ${className ?? ''}`}>+ {src && (+ <img+ src={src}+ alt=""+ className="absolute inset-0 size-full object-cover"+ loading="lazy"+ decoding="async"+ onError={onError}+ />+ )}+ <div className="absolute inset-0 flex items-center justify-center">+ {children ?? (!src && <IconVideoCamera className="text-xl text-tertiary" aria-hidden />)}+ </div>+ </div>+ )+}diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 787e8b98c404..91f4979f8538 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -586,6 +586,45 @@ export interface ReplayObservationLabelApi {feedback?: string}+/**+ * * `thumbnail` - Thumbnail+ * * `clip` - Clip+ */+export type ReplayObservationMediaKindEnumApi =+ (typeof ReplayObservationMediaKindEnumApi)[keyof typeof ReplayObservationMediaKindEnumApi]++export const ReplayObservationMediaKindEnumApi = {+ Thumbnail: 'thumbnail',+ Clip: 'clip',+} as const++/**+ * One thumbnail or clip illustrating an observation.+ */+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` - Thumbnail+ * * `clip` - Clip */+ readonly kind: ReplayObservationMediaKindEnumApi+ /** Export asset holding the bytes; fetch it from the export content endpoint. */+ readonly asset_id: number+ /**+ * One sentence saying what the clip shows. Null for thumbnails.+ * @nullable+ */+ readonly description: string | null+ /** Where this media starts in the analysis video, in milliseconds. */+ readonly video_start_ms: number+ /**+ * Where a clip ends in the analysis video, in milliseconds. Null for thumbnails.+ * @nullable+ */+ readonly video_end_ms: number | null+}+export interface ReplayObservationApi {readonly id: string/** The scanner that produced this observation. */@@ -651,6 +690,8 @@ export interface ReplayObservationApi {readonly label: ReplayObservationLabelApi | null/** Whether the calling user has opened this observation. */readonly viewed: boolean+ /** Thumbnails and clips illustrating this observation, in order. Empty until the media render finishes. */+ readonly media: readonly ReplayObservationMediaApi[]/** One line of plain text saying what the scanner found: its verdict, score, tags or title, then its own words, with markdown flattened and the text truncated. An observation that produced no result carries the reason instead, and one still in flight carries an empty string. Read this in place of `scanner_result` when you scan a list of observations. */readonly summary_line: string/** @nullable */diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex bf156dde4bd8..54e9d8478f3e 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -453,6 +453,24 @@ export const visionObservationsSignalReportsList = async (})}+export const getVisionObservationsThumbnailRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/vision/observations/${id}/thumbnail/`+}++/**+ * Redirect to the frame that illustrates this observation, so a caller with only the observation id can show it.+ */+export const visionObservationsThumbnailRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<unknown> => {+ return apiMutator<unknown>(getVisionObservationsThumbnailRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getVisionObservationsViewedCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/vision/observations/${id}/viewed/`}@@ -1184,6 +1202,25 @@ export const visionScannersObservationsSignalReportsList = async ()}+export const getVisionScannersObservationsThumbnailRetrieveUrl = (projectId: string, scannerId: string, id: string) => {+ return `/api/projects/${projectId}/vision/scanners/${scannerId}/observations/${id}/thumbnail/`+}++/**+ * Redirect to the frame that illustrates this observation, so a caller with only the observation id can show it.+ */+export const visionScannersObservationsThumbnailRetrieve = async (+ projectId: string,+ scannerId: string,+ id: string,+ options?: RequestInit+): Promise<unknown> => {+ return apiMutator<unknown>(getVisionScannersObservationsThumbnailRetrieveUrl(projectId, scannerId, id), {+ ...options,+ method: 'GET',+ })+}+export const getVisionScannersObservationsViewedCreateUrl = (projectId: string, scannerId: string, id: string) => {return `/api/projects/${projectId}/vision/scanners/${scannerId}/observations/${id}/viewed/`}diff --git a/products/replay_vision/frontend/observations/ReplayObservation.tsx b/products/replay_vision/frontend/observations/ReplayObservation.tsxindex 197b5bfcdffe..812a1f2818e4 100644--- a/products/replay_vision/frontend/observations/ReplayObservation.tsx+++ b/products/replay_vision/frontend/observations/ReplayObservation.tsx@@ -45,6 +45,7 @@ import {} from '../components/ObservationCard'import { ObservationProgressBar } from '../components/ObservationProgressBar'import { ObservationRetryButton } from '../components/ObservationRetryButton'+import { ObservationThumbnail } from '../components/ObservationThumbnail'import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'import { ScannerTypeBadge } from '../components/ScannerTypeBadge'import type { ReplayObservationApi } from '../generated/api.schemas'@@ -325,9 +326,9 @@ export function ReplayObservationSceneComponent(): JSX.Element {aria-expanded={false}data-attr="vision-observation-recording-toggle">- <span className="flex items-center justify-center w-20 h-12 rounded bg-black shrink-0">- <IconPlayFilled className="text-xl text-brand-red" />- </span>+ <ObservationThumbnail observation={observation} className="w-20 shrink-0">+ <IconPlayFilled className="text-xl text-brand-red drop-shadow" />+ </ObservationThumbnail><span className="flex-1 min-w-0"><h3 className="text-lg font-semibold m-0">Watch the recording</h3><span className="text-sm text-muted">Play the session this observation was made from</span>diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex ec413b5f9bea..c0141ead096e 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -6,6 +6,7 @@ import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'import { billingJson } from '~/mocks/fixtures/_billing'+import { sessionFrameResponse } from '~/mocks/fixtures/sessionFrame'import { RecordingsQuery } from '~/queries/schema/schema-general'import { StartupProgramLabel } from '~/types'@@ -226,6 +227,16 @@ const observation = (overrides: Partial<ReplayObservationApi> = {}): ReplayObserstarted_at: '2026-05-11T09:00:00Z',completed_at: '2026-05-11T09:01:00Z',created_at: '2026-05-11T09:00:00Z',+ media: [+ {+ id: '00000000-0000-0000-0000-0000000000f1',+ kind: 'thumbnail',+ asset_id: 4001,+ description: null,+ video_start_ms: 24000,+ video_end_ms: null,+ },+ ],...overrides,}) as ReplayObservationApi@@ -252,6 +263,8 @@ const observations = {scanner_result: null,recording_subject_email: null,distinct_id: null,+ // A scan that never produced a result never rendered a frame either.+ media: [],}),observation({id: '00000000-0000-0000-0000-0000000000b4',@@ -602,6 +615,10 @@ const meta: Meta = {evaluation_session_cap: 25,},'/api/projects/:team_id/vision/observations/:id/': observationDetail,+ // Real bytes, so the poster in the table and on the detail page renders as a reader sees it.+ '/api/projects/:team_id/vision/observations/:id/thumbnail/': () => sessionFrameResponse(),+ '/api/projects/:team_id/vision/scanners/:scannerId/observations/:id/thumbnail/': () =>+ sessionFrameResponse(),'/api/environments/:team_id/session_recordings/': { results: onDemandRecordings, has_next: false },'/api/environments/:team_id/session_recordings/matching_events': { results: [] },'/api/projects/:team_id/signals/scout/configs/': [],diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsxindex daedadc1a04c..1000cf2c5d3b 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx@@ -17,6 +17,7 @@ import { FilterPill } from '../../components/FilterPill'import { NumericRangeFilterPill } from '../../components/NumericRangeFilterPill'import { ObservationResultSummary, ObservationStatusTag } from '../../components/ObservationCard'import { ObservationRetryButton } from '../../components/ObservationRetryButton'+import { ObservationThumbnail } from '../../components/ObservationThumbnail'import type { ReplayObservationApi } from '../../generated/api.schemas'import { observationDetailUrl } from '../../observations/replayObservationLogic'import { shortBackfillId } from '../../utils/backfills'@@ -135,6 +136,19 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):const scoreScale = scanner?.scanner_type === 'scorer' ? scanner.scanner_config.scale : undefinedconst columns: LemonTableColumns<ReplayObservationApi> = [+ {+ title: '',+ key: 'thumbnail',+ width: 96,+ render: (_, obs) => (+ <Link+ to={observationDetailUrl(obs.id, observationDetailLinkParams)}+ aria-label={`Open the observation for session ${obs.session_id}`}+ >+ <ObservationThumbnail observation={obs} className="w-20" />+ </Link>+ ),+ },{title: 'Session',key: 'session',diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 34f48ae88952..3fbc2fd3a81b 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -194,6 +194,9 @@ tools:vision-observations-signal-reports-list:operation: vision_observations_signal_reports_listenabled: false+ vision-observations-thumbnail-retrieve:+ operation: vision_observations_thumbnail_retrieve+ enabled: falsevision-observations-viewed-create:operation: vision_observations_viewed_createenabled: false@@ -548,6 +551,9 @@ tools:ask the person to rate a few results before you call `vision-scanners-prompt-suggestions-generate`. Recordtheir verdicts with `vision-observations-label-create` rather than supplying your own. Testing a suggestionis not available over MCP, so tell them to test it on the scanner's Calibration tab before they apply it.+ vision-scanners-observations-thumbnail-retrieve:+ operation: vision_scanners_observations_thumbnail_retrieve+ enabled: falsevision-scanners-observations-viewed-create:operation: vision_scanners_observations_viewed_createenabled: falsediff --git a/products/signals/frontend/inbox/components/signalCards/RecordingPreview.tsx b/products/signals/frontend/inbox/components/signalCards/RecordingPreview.tsxindex 28247e47a6f9..f84f3377be2d 100644--- a/products/signals/frontend/inbox/components/signalCards/RecordingPreview.tsx+++ b/products/signals/frontend/inbox/components/signalCards/RecordingPreview.tsx@@ -8,16 +8,16 @@ import { Spinner } from '@posthog/lemon-ui'import { sessionRecordingInfoLogic } from 'lib/components/ViewRecordingButton/sessionRecordingInfoLogic'import { RecordingPlayerType, useRecordingButton } from 'lib/components/ViewRecordingButton/ViewRecordingButton'import { Dayjs } from 'lib/dayjs'-import { teamLogic } from 'scenes/teamLogic'-import { getExportsContentRetrieveUrl } from '~/generated/core/api'+// Long enough for a thumbnail render to land, short enough that a reader still sees the frame appear.+const THUMBNAIL_RETRY_MS = 45_000interface RecordingPreviewProps {sessionId: string/** Instant the player seeks to when the frame is clicked. */seekTime?: Dayjs- /** Exported screenshot of that moment, shown as the frame's background while it can be fetched. */- exportedAssetId?: number | null+ /** Image of that moment, shown as the frame's background while it can be fetched. */+ thumbnailSrc?: stringalt: string}@@ -26,14 +26,33 @@ interface RecordingPreviewProps {* it opens the recording in the player modal at `seekTime`. Disables itself, instead of opening an* empty player, when the recording wasn't captured or has expired.*/-export function RecordingPreview({ sessionId, seekTime, exportedAssetId, alt }: RecordingPreviewProps): JSX.Element {- const { currentTeamId } = useValues(teamLogic)- const [thumbnailFailed, setThumbnailFailed] = useState(false)+export function RecordingPreview({ sessionId, seekTime, thumbnailSrc, alt }: RecordingPreviewProps): JSX.Element {+ // A replay signal reaches the inbox before its frame finishes rendering, so the first fetch usually 404s.+ // One delayed retry covers that; between the two the frame is unmounted, so nothing waits on a dead image.+ const [attempt, setAttempt] = useState(0)+ const [waiting, setWaiting] = useState(false)+ const [gaveUp, setGaveUp] = useState(false)- const thumbnailSrc =- currentTeamId !== null && exportedAssetId != null && !thumbnailFailed- ? getExportsContentRetrieveUrl(String(currentTeamId), exportedAssetId)- : undefined+ useEffect(() => {+ setAttempt(0)+ setWaiting(false)+ setGaveUp(false)+ }, [thumbnailSrc])++ useEffect(() => {+ if (!waiting) {+ return+ }+ const timer = setTimeout(() => {+ setAttempt(1)+ setWaiting(false)+ }, THUMBNAIL_RETRY_MS)+ return () => clearTimeout(timer)+ }, [waiting])++ const onError = (): void => (attempt === 0 ? setWaiting(true) : setGaveUp(true))++ const src = thumbnailSrc && !waiting && !gaveUp ? `${thumbnailSrc}?attempt=${attempt}` : undefinedconst { checkRecordingInfo } = useActions(sessionRecordingInfoLogic)const { getRecordingExists, isRecordingExistsLoading } = useValues(sessionRecordingInfoLogic)@@ -61,29 +80,29 @@ export function RecordingPreview({ sessionId, seekTime, exportedAssetId, alt }:data-attr="inbox-signal-recording-preview"className="group relative w-full aspect-video rounded overflow-hidden border bg-surface-secondary mb-2 cursor-pointer disabled:cursor-default disabled:opacity-70">- {thumbnailSrc && (+ {src && (// Defer this full-frame screenshot: the evidence rail opens expanded and can hold// one preview per replay signal, so eager loading fetches frames never scrolled to.<img- src={thumbnailSrc}+ src={src}alt={alt}className="absolute inset-0 size-full object-cover"loading="lazy"decoding="async"- onError={() => setThumbnailFailed(true)}+ onError={onError}/>)}<divclassName={clsx('absolute inset-0 flex items-center justify-center transition-colors motion-reduce:transition-none',- thumbnailSrc ? 'bg-black/20 group-hover:bg-black/30' : 'group-hover:bg-fill-highlight-100'+ src ? 'bg-black/20 group-hover:bg-black/30' : 'group-hover:bg-fill-highlight-100')}>{recordingCheckLoading ? (- <Spinner className={clsx('text-2xl', thumbnailSrc ? 'text-white' : 'text-tertiary')} />+ <Spinner className={clsx('text-2xl', src ? 'text-white' : 'text-tertiary')} />) : (<IconPlay- className={clsx('size-10 drop-shadow', thumbnailSrc ? 'text-white' : 'text-tertiary')}+ className={clsx('size-10 drop-shadow', src ? 'text-white' : 'text-tertiary')}aria-hidden/>)}diff --git a/products/signals/frontend/inbox/components/signalCards/ScannerFindingSignalCard.tsx b/products/signals/frontend/inbox/components/signalCards/ScannerFindingSignalCard.tsxindex 93b9ee88ff0f..b8c88bbc3a33 100644--- a/products/signals/frontend/inbox/components/signalCards/ScannerFindingSignalCard.tsx+++ b/products/signals/frontend/inbox/components/signalCards/ScannerFindingSignalCard.tsx@@ -1,7 +1,11 @@+import { useValues } from 'kea'+import { Dayjs, dayjs } from 'lib/dayjs'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { colonDelimitedDuration, humanFriendlyDuration } from 'lib/utils/durations'+import { teamLogic } from 'scenes/teamLogic'+import { getVisionObservationsThumbnailRetrieveUrl } from 'products/replay_vision/frontend/generated/api'import type { ReplayVisionScannerFindingSignalExtraApi } from 'products/signals/frontend/generated/api.schemas'import { RecordingPreview } from './RecordingPreview'@@ -32,6 +36,7 @@ function findingSeekTime(recordingStartTime: string | null | undefined, offsetSe/** Live card for a replay-vision scanner finding: thumbnail preview and a play affordance that seeks to the observation. */export function ScannerFindingSignalCard({ signal }: SignalCardProps): JSX.Element {+ const { currentTeamId } = useValues(teamLogic)const extra = signal.extra as Record<string, unknown> & ReplayVisionScannerFindingSignalExtraApiconst activeDuration =@@ -51,7 +56,11 @@ export function ScannerFindingSignalCard({ signal }: SignalCardProps): JSX.Eleme<RecordingPreviewsessionId={extra.session_id}seekTime={findingSeekTime(extra.recording_start_time, extra.start_time)}- exportedAssetId={extra.exported_asset_id}+ thumbnailSrc={+ currentTeamId !== null+ ? getVisionObservationsThumbnailRetrieveUrl(String(currentTeamId), extra.observation_id)+ : undefined+ }alt={`Recording preview for ${extra.scanner_name}`}/>diff --git a/products/signals/frontend/inbox/components/signalCards/SessionReplaySignalCard.tsx b/products/signals/frontend/inbox/components/signalCards/SessionReplaySignalCard.tsxindex f1e89927a195..6a4e3af9fe2a 100644--- a/products/signals/frontend/inbox/components/signalCards/SessionReplaySignalCard.tsx+++ b/products/signals/frontend/inbox/components/signalCards/SessionReplaySignalCard.tsx@@ -10,6 +10,9 @@ import { Dayjs, dayjs } from 'lib/dayjs'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { humanFriendlyDuration, reverseColonDelimitedDuration } from 'lib/utils/durations'+import { teamLogic } from 'scenes/teamLogic'++import { getExportsContentRetrieveUrl } from '~/generated/core/api'import type {SessionProblemEventEntryApi,@@ -105,6 +108,7 @@ export function SessionReplaySignalCard({ signal }: SignalCardProps): JSX.Elemenconst segmentSeekTime = recordingSeekTime(extra.session_start_time ?? undefined, extra.start_time)const { getRecordingExists, isRecordingExistsLoading } = useValues(sessionRecordingInfoLogic)+ const { currentTeamId } = useValues(teamLogic)const recordingExists = getRecordingExists(extra.session_id)const recordingExistsLoading = isRecordingExistsLoading(extra.session_id)@@ -131,7 +135,11 @@ export function SessionReplaySignalCard({ signal }: SignalCardProps): JSX.Elemen<RecordingPreviewsessionId={extra.session_id}seekTime={segmentSeekTime}- exportedAssetId={extra.exported_asset_id}+ thumbnailSrc={+ currentTeamId !== null+ ? getExportsContentRetrieveUrl(String(currentTeamId), extra.exported_asset_id)+ : undefined+ }alt={`Recording preview for ${extra.segment_title}`}/>) : (diff --git a/products/signals/frontend/inbox/components/signalCards/SignalCards.stories.tsx b/products/signals/frontend/inbox/components/signalCards/SignalCards.stories.tsxindex 42e6e26cc47d..2e92346e4175 100644--- a/products/signals/frontend/inbox/components/signalCards/SignalCards.stories.tsx+++ b/products/signals/frontend/inbox/components/signalCards/SignalCards.stories.tsx@@ -413,6 +413,9 @@ const meta: Meta = {pngResponse(['103', '104'].includes(String(req.params.exportId)) ? ATTACHMENT_PNG : RECORDING_PREVIEW_PNG),+ // A scanner finding takes its frame from Replay Vision, addressed by observation.+ '/api/projects/:id/vision/observations/:observationId/thumbnail/': () =>+ pngResponse(RECORDING_PREVIEW_PNG),},post: {'/api/environments/:id/session_recordings/batch_check_exists': () => [diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 393ee959f6e2..9eed3723bc47 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -57647,6 +57647,45 @@ export namespace Schemas {feedback?: string;}+ /**+ * * `thumbnail` - Thumbnail+ * * `clip` - Clip+ */+ export type ReplayObservationMediaKindEnum = typeof ReplayObservationMediaKindEnum[keyof typeof ReplayObservationMediaKindEnum];+++ export const ReplayObservationMediaKindEnum = {+ Thumbnail: 'thumbnail',+ Clip: 'clip',+ } as const;++ /**+ * One thumbnail or clip illustrating an observation.+ */+ 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` - Thumbnail+ * * `clip` - Clip */+ readonly kind: ReplayObservationMediaKindEnum;+ /** Export asset holding the bytes; fetch it from the export content endpoint. */+ readonly asset_id: number;+ /**+ * One sentence saying what the clip shows. Null for thumbnails.+ * @nullable+ */+ readonly description: string | null;+ /** Where this media starts in the analysis video, in milliseconds. */+ readonly video_start_ms: number;+ /**+ * Where a clip ends in the analysis video, in milliseconds. Null for thumbnails.+ * @nullable+ */+ readonly video_end_ms: number | null;+ }+export interface ReplayObservation {readonly id: string;/** The scanner that produced this observation. */@@ -57712,6 +57751,8 @@ export namespace Schemas {readonly label: ReplayObservationLabel | null;/** Whether the calling user has opened this observation. */readonly viewed: boolean;+ /** Thumbnails and clips illustrating this observation, in order. Empty until the media render finishes. */+ readonly media: readonly ReplayObservationMedia[];/** One line of plain text saying what the scanner found: its verdict, score, tags or title, then its own words, with markdown flattened and the text truncated. An observation that produced no result carries the reason instead, and one still in flight carries an empty string. Read this in place of `scanner_result` when you scan a list of observations. */readonly summary_line: string;/** @nullable */