: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): rework the scanner page (#105563)
Tue Haulund567d270b45aa
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex e80a88a6c054..89994b0fa153 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10720,6 +10720,14 @@ snapshots:hash: v1.k794b7964.70707572ec3098ed0c916ac56ec8618ccd95b7b270cffb5a5425d447622912d5.Dayhp1AO69NWJL7h-i4nDDzqeXSh_3lNJjcRDBvOASUscenes-app-project-homepage--project-homepage--light:hash: v1.k794b7964.45567c13e93e1def5dabfea7b6a4a5a47253482e6dd5c587be257ae5b9374639.IC346vxEHrTKcFor0vVTajrOk8lCGCu3C5pdFW2iTOQ+ scenes-app-replay-vision--classifier-observations--dark:+ hash: v1.k794b7964.9c567d3ebe0964afd041a18db1e8cfa7a2bb55dddc9291c1a030fd0082e18c2a.ZcUfCIK8e1NAEYqouFz_hA_28_QKXba6S1iuL0AKYpA+ scenes-app-replay-vision--classifier-observations--light:+ hash: v1.k794b7964.5b8b69a5cdb77d25032a78c0080d1de77328318aa75cef6ea815122eb7a6823c.J0_8oGlsgOosNjN8ijl4Q4x4qgocLhseNZPOArJmwqo+ scenes-app-replay-vision--classifier-overview--dark:+ hash: v1.k794b7964.3fb8a94b80b8f27f760bed4dcaf7546a2f9e111c413f9d50fd3d17869b415f63.Y2tZfKVD78BzTE9Y5nE3K2RNJbODPuEqNLkVcWYtZRI+ scenes-app-replay-vision--classifier-overview--light:+ hash: v1.k794b7964.54e1507d4d1c2f9c8832f70a46dfe370e7982c888494621d0df25c5c17b29f7a.-OIOK1tAi0jaWtLGHq1WgiiY28wi6OnDSiR1dUzOHIQscenes-app-replay-vision--home-watch-feed--dark:hash: v1.k794b7964.ea6584e63096062feb704e29988aaf456173f7964bea67873abf90ffca241df8.1D5HCNI8k0RrgRrCkrSFNEtgf69avW52B465iVgukkkscenes-app-replay-vision--home-watch-feed--light:@@ -10732,6 +10740,18 @@ snapshots:hash: v1.k794b7964.535ecf83de06a037ebef4b617eb118149cf1a1a88bc190f878a8ec6ad8580ed3.zfGqUNO52i8cUGb_n92QrVLoGmuF1dFl3yat56TLZYoscenes-app-replay-vision--home-watch-feed-only-newest--light:hash: v1.k794b7964.6815df3576b3f2c4695eaa1c3ce6e27a5787edde8889b8f83ade58468074e654.4Nh0vul-NwpqwooPzZLWCuK4Q21TmRv2scmOlval-o4+ scenes-app-replay-vision--monitor-observations--dark:+ hash: v1.k794b7964.96d80a38110ad0abf32d13d9709f4b21f58027b2ac72d306dcd102d5496b831f.zHot-qyqnA8iZSK6-U5PHca9lzckgE3oJb4JoimsDEk+ scenes-app-replay-vision--monitor-observations--light:+ hash: v1.k794b7964.2a7790b6eb9fa8d10f1b9724c812d6a5d20890c9855c8820c99501f298a6e2ea.iXx1izsriGGU-Jcw_plK-Bp9GlurceSvj09w_HQi8w0+ scenes-app-replay-vision--monitor-overview--dark:+ hash: v1.k794b7964.89ff5f3ba879e477ef095a3d213b7c6f003a6d95720807192ff3b6fd30452e62.gUSqGrYZOkGLKFj1AzfH1uySsXu2KS0gqoNLTKS-WPM+ scenes-app-replay-vision--monitor-overview--light:+ hash: v1.k794b7964.abcec2cb1abbce5113ad16af2cc347ed17c7bb2640fc2c3832723bacc79ea56f.2AZaLO5YIdg1bGoeE7QfGMa_QfFMjKh_-3VavrnrQQQ+ scenes-app-replay-vision--monitor-overview-with-scout-report--dark:+ hash: v1.k794b7964.dc482e2b6a20e47cd7cdc205c72b8084446dcb6eb0a82299f7ed65ad453b4746.euygb2aLl1mZSRNu5Bokqhp20b0yUK__oMVKyf0_wpY+ scenes-app-replay-vision--monitor-overview-with-scout-report--light:+ hash: v1.k794b7964.30d42b704c4a00911529c2a6cb542f8ee8649c8dd25e0a98f93d45338fcba97e._KqWLoMbKiDjbPWHIePRk4RycV1OpAwZOOrqOgNjJtUscenes-app-replay-vision--observation-detail--dark:hash: v1.k794b7964.e9fd7c14ee1899c90ba01049012a8d9947f013869b8ec7d767b7db2220d46166.XZIczm04vBGXxRP7z-rzHaqy34GQDRXXfTrEhICqxi0scenes-app-replay-vision--observation-detail--light:@@ -10749,41 +10769,29 @@ snapshots:scenes-app-replay-vision--observation-detail-monitor--light:hash: v1.k794b7964.768885316fe8f5e6d6e766920805adb17331c67f5452cb81878273e718d46128.613JBEPeFxtEAhgh9tMgylbHMAk-bHGqX6WL2hhlLEIscenes-app-replay-vision--scanner-alerts--dark:- hash: v1.k794b7964.87fdb6e06721ceec6ed9bb54eb0e48ab04c117a20e18d2b64a4253671999876f.4o_jktzFiZNieMvqKaefp4SP6mCmkG6X7OVBhkaXcWs+ hash: v1.k794b7964.07adaa26f0b868d6c64d7d99e3d1a317307dff376b1dc5d740c9c9cc9c2ff926.c9kS5X0nGVIU2VHq4sxwidzwpjG5bpqnlvPM-r8yEf8scenes-app-replay-vision--scanner-alerts--light:- hash: v1.k794b7964.2628f34e2afc6ae3de0dd163305ac123beb35162605a459ce27d5be4e64b1348.MCzcvn963uAvFXtcxt5QUpz-2YlH48oi74L2y_Y-6-A+ hash: v1.k794b7964.cfaac837acb4b55f109bbe852790f4c064838fdcd4539e1425dc5e42f9c79c0c.peRboBNRpJ_iNGusrz2WkxU44RCvjMWUpPvcos5Y9HAscenes-app-replay-vision--scanner-alerts-empty--dark:- hash: v1.k794b7964.ccc6612e3032bc8df51a78f1d5db9f05ab068fbf9dfcaa6e61c0b089269fcc20.qbpdY0ssP6h0w0MTmE1hkEICNtqz7vMLGb5PkzSZq8k+ hash: v1.k794b7964.1d191acecb1c1b5ec85d622be702926c23f31ae6a6a8fabed240948b32ffa95c.wO1kuSdFMFzS35nSjXDx77xR6QNLgeHAN9FfQl6Jw-kscenes-app-replay-vision--scanner-alerts-empty--light:- hash: v1.k794b7964.d90d7c951a6cc5eb3a8812b5b88ec6b487fc9cb7061c1eb9f8dedb8c3cd6997e.H9Vt0ME7aUMtsDLFF_jVNmlZGYWHsEvAj_x2_tq894c+ hash: v1.k794b7964.8c82998d816554275028175706f6f90c01554ce48f4372202c6ee27048085e8d.Ctvl3-vCPYro_vJSpxgJTe5GcAlNK3F_kvlLUPh6FOUscenes-app-replay-vision--scanner-calibration--dark:hash: v1.k794b7964.5e0f861f7937065a33c6b68973fe2b5f853d0a2ce9660aaf41f53d1c7cfef4e0.p3b3ZO--YxEqmZWSi9DT8ndq3ZP2J2dU7WuRMhOhOd4scenes-app-replay-vision--scanner-calibration--light:hash: v1.k794b7964.43b310ff18e050913e41203405a1c07bc828efb546578e719db5fe304db986ec.bIxzTXCnMK2zCCr-iNlrImXP0hCopvBQTqpcyc_sIawscenes-app-replay-vision--scanner-calibration-activation-badge--dark:- hash: v1.k794b7964.29ac23a47de6f34ef5d51fd8e36b9a238f5aea7789d750828790d91362256961.Yhgjh0An9dM-SADDp5cxxL5TeNIzkTlV57QNEdAF6tU+ hash: v1.k794b7964.b1743f4f583a81389e417f34020a8a4d495f5533ac9c966bc5ece5acb94e849a.QOQbqK3P7P2EgDmdYIBVXZ7mqFbmlq9PSshYDs_JzGkscenes-app-replay-vision--scanner-calibration-activation-badge--light:- hash: v1.k794b7964.d28929c4ac28d432357a90b416c9bdcfed986df55ca55c5d01dd995d60315ff8.f0l_fgADuy7e8-QAaFjpc_BlAI0icVsqsi1UVW1iu5E+ hash: v1.k794b7964.b73a0c3cdc8e19a7ec8dd1a3ff78bc9169d06594741cc311e4962678363e8726.BFqkP465wmTytybrM2BguW2WS7fv2Yo0AU6sS2zoFBoscenes-app-replay-vision--scanner-calibration-activation-prompt--dark:- hash: v1.k794b7964.ac385326a77b8943731bc6f58dfc17128bdfb0c9bcab0557cbabff8ac84e9266.AAHOM9SvqLqszqls1kpl2bG9AFbTaDfalHCB_sxZf0M+ hash: v1.k794b7964.69e02a700f12edbf21a81446f639d22b7481371248cb7d60df338a9ada4f0022.IjCmvCQnl2UKnTLAsgD5766y0Gxs9lAuCsbtDaHX-E4scenes-app-replay-vision--scanner-calibration-activation-prompt--light:- hash: v1.k794b7964.612f55d5d6b3ba8a3acd684cf691ca960be67c77e8b3a28832fa551ae0c9e87d.dajJ5kPDA3I2YSzwubGBCUPdED3KIAfJJVxhWtVRp7M+ hash: v1.k794b7964.f669ee17da0d3dda835925459a6afd9856d152c71f206fd6edfec3242238d4b7.LPIdSzTU7W0OsjL0L76EEPioPgHXeCpHcQWWj7KRftgscenes-app-replay-vision--scanner-calibration-test-nudge--dark:hash: v1.k794b7964.8498adbaf6b8b428d0dfddd3835cd36f7ed726788f15e7e25dbc413cf99a238d.dcJ3uNWDx7xQJpRQsw7_7UQyhPIdYSmikafisPHur90scenes-app-replay-vision--scanner-calibration-test-nudge--light:hash: v1.k794b7964.cd9edecc6e5724f6fabda9d3c67545ee900d8834ca875fa982544e6a82e959cc.dfLBW0Pc4UZBPc43ce00mYiKIWMLOKohcIevHVGJZ9c- scenes-app-replay-vision--scanner-configuration--dark:- hash: v1.k794b7964.301f453cefdf0fe2128e76c61bc1de01f8628229f855c9ae45f8a74f7a2688eb.LIiZp_TmIOBDZDyTJADogI-Ceqt5yt07I-u71xNNDvk- scenes-app-replay-vision--scanner-configuration--light:- hash: v1.k794b7964.7e988a775c325a75ce5883bb1d11fcc02d64abb732b5c3f67a7d9daf85144423.bMsjttayvTrQQekiCtzm2uagEglefj5Zk81P2WdYzjo- scenes-app-replay-vision--scanner-configuration-lite-standard-pro--dark:- hash: v1.k794b7964.8694aae4c12bb68692b71e679cc5e4f3cd1d68caadd3197b6f4cf72853bb4609.gMNUr6auG0bBaMc8jtUhxdAUMsw-lZ6CbGIwAUQEmOw- scenes-app-replay-vision--scanner-configuration-lite-standard-pro--light:- hash: v1.k794b7964.aede48e49edc8118aaf63f1e629774294ad9c82da8ed0b6573c1f040eda76eb7.JmC9-XqCP_VVxxmUFIEeSMez7QArWBm-2Gya8M1MrDg- scenes-app-replay-vision--scanner-configuration-tier-names--dark:- hash: v1.k794b7964.6608759699f4c2cb9a7fe8b20ce707ba93fecc5ca1ef20f3111b509a45581ec5.q22jVY9nU23yEWsA6SRcDf5oPvfLanzi3H8953d_LjQ- scenes-app-replay-vision--scanner-configuration-tier-names--light:- hash: v1.k794b7964.99613f3da6df0b847d8e5aceee496d548249074a6aed2207189de67df11948f3.CE4owRhm1E7_bbxpAN6xVmTnQ2oNbfAP28Ya2lBluEEscenes-app-replay-vision--scanner-editor-budget--dark:hash: v1.k794b7964.37379538a705b9cfdaae3992ffbb357d3f7277abc9b77000c37e5d65d2d9a182.tIr_lkCBHvvxOjUsNFJ_VwNzAkD_MY2q-fN7anGin90scenes-app-replay-vision--scanner-editor-budget--light:@@ -10825,25 +10833,37 @@ 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.a752f7f891f1b2ceaea0400659ccc880f0ca28d966b658ef0f77ce844782c92e.PmMw6zm-TZLtplMoFrVe_tBEPca68mAqAkRRVJNdgyo+ hash: v1.k794b7964.c387527d82d6363ea28508668f08d98d50648aa4d0171c8b072cbb13749a7a36.xuN6K6BLUxpYg54DDJ2PWz8x6TC0dB1YQn3qtUiFhf0scenes-app-replay-vision--scanner-observations--light:- hash: v1.k794b7964.8080138683d8e416aa3a924e9b9284b7803a3b16ba1228d816b73c63915a3b53.Lap3WKKKlTZ176TgR1uH5JfxbNqNn0zIWInq8W3bsT0+ hash: v1.k794b7964.499c29a074eea8bed3fa01e271e61e00a1496a9fc0a181154fb2b96518222f42.xUfD985UqrLys4U18wuzPJW9SyOetZlbvZ-3EYDI05Mscenes-app-replay-vision--scanner-on-demand--dark:- hash: v1.k794b7964.8613b8f3c572a259695f7658d33b058be49f3be5b73e050e3fb358289800c964.DPrs0SWEtTD2prJs342aey5-aX1mEuYdTblY4N9dqaE+ hash: v1.k794b7964.4676a8b3a3b4a911670e39e9ed2045d4ce6e89b11d1fa48ff888acbb767275a2.YUJAEgZeeoAlmzt8O2t05nohUAZMmhRTp2bAdu2-7R4scenes-app-replay-vision--scanner-on-demand--light:- hash: v1.k794b7964.533c571e0ae254f05fe3183bcafa90f28006a8921608c718a012a5227ed2436f.rFjBuser9MhT4H20Nx5g14EIRIt0RqHNKQPC9hssCss+ hash: v1.k794b7964.bf11575a3ca42bb716c09f616d02b338b876123f9eac8627325f6d72af19b5e9.oDkH59MN8O676qPeCUXfZ-LwWZ_8SBnCe3Lu8miXbXUscenes-app-replay-vision--scanner-scan-drought--dark:- hash: v1.k794b7964.47963d3ee2fc2934b80cfd51b0db411baf326710d528c8995ed7eecbae4d6faa.zV2CxUwodEqwEiQT5_Tr3XAFLhkhAGTY3z8LUm97USo+ hash: v1.k794b7964.536a07ad615e70038a2441e46c886800d971c77af7dd8a6c357ada718c6a0d96.BnHNIBHBR7Xmb44vCSdvTMvFLrgdQ4O5-m_zzsHhioAscenes-app-replay-vision--scanner-scan-drought--light:- hash: v1.k794b7964.d3e3119d983ea105adcd26771cfdfbe14e082892971e48cb4000de6ca48e44df.pfdBzR5cE9sN8GjQF_54zIi5OvM-4nGsvyzsZd9TLSk+ hash: v1.k794b7964.8ebbf9f579a1665ef121abea4a217f82e7be3c571aede7f3b893149ff16a2088.zjqRr7hP4v7mDyATcmjF_fEk40_CbQVmRxSHx6AoPHYscenes-app-replay-vision--scanner-scouts--dark:- hash: v1.k794b7964.05cd0d9a8bee23f703a575ecdd315f00c29cb482e83fbaeacf4e548e31bef15c.V8B-a6fRzpuTi6gRsRl1S6KaBcN32QEi2jnAQ2x5ISk+ hash: v1.k794b7964.852f7f408f11eb4680b97c048bd0728bf0f9d35e7eb0d8705585d3a02bfa4a36.njTA-B_BEVagOn-edL8aUXWakfmYz1c6W7wPor5_Npgscenes-app-replay-vision--scanner-scouts--light:- hash: v1.k794b7964.b0180eb02b9c80483d1876933bf2596bd4ae27bfe3821a1f5b40472b42480d0d.A0Kj3VCCbvv17Rm5RppBMGdDGyhlu2T1Y5qpKRw8Y0g+ hash: v1.k794b7964.c06cb5fa9d1cc685384dfbe7de8b3ff3e7598f5dd073675a104c3fb72898d973.71Q9YO-h21Ol6wjKP57HV7t77pDlOhvr9awtXJ-hypkscenes-app-replay-vision--scanner-scouts-empty--dark:- hash: v1.k794b7964.e1b10948c3d6c52419f993497104c7e395a4b049da619e23f5c135ccb0d35ffb.Kf3lZFMUPqBIX1lhDr9s1kXLcM-cDYUP9Xaf65jtRSM+ hash: v1.k794b7964.2817ad61cc1cc59653bcca1bdcc59cc9fce89b104713b1fa54620168b67090e9.pySOk3Isyo1VgX5HwTp-utzfHjIL2SKhduEUMjYuOnQscenes-app-replay-vision--scanner-scouts-empty--light:- hash: v1.k794b7964.12514db00b6d928ab64039a78a5ce02fe74b43daedd26b76621dd65e3088b1e3.6HfZozgO4OvkB-vqEQdBUKp_oL24qSTbw18hzpqsfN0+ hash: v1.k794b7964.e68aed40d120ac23712a7b6f014ab3d7724f1f32a1ab9d7361f31efddd176906.fZQh4nBwJNi5F5MT1HDqe42kDYef4kXSxZtkHOssLDA+ scenes-app-replay-vision--scanner-setup-lite-standard-pro--dark:+ hash: v1.k794b7964.3a800da09278851cb697f4d3baad1a6cae0594847e191fda8fe7b2f9627e0802.GKplvA4F6SMU_Mlj2jDZzoABFhJ4LIKdqWqGoXpUmB0+ scenes-app-replay-vision--scanner-setup-lite-standard-pro--light:+ hash: v1.k794b7964.946928c253de57ff0d33ce750e603a98a39d571d64f4f0e523bd8457e4eef51a.IU9OW1rF7QLesWnqe6lqSkyiyH7k_uJgDNIzTgAiwO8+ scenes-app-replay-vision--scanner-setup-tier-names--dark:+ hash: v1.k794b7964.052e2096a2ec2e3e41225b04a2acca2d042d8622fda3b2f6ac74eeddde798524.kpRlVoL3Rp-GbyOZ-jPewTVxqWJnen1e9VwsGwrdYMQ+ scenes-app-replay-vision--scanner-setup-tier-names--light:+ hash: v1.k794b7964.68ace470c05f39da9e5a2a250764ea1f172bad32f11182dec6bd9f290c1e945f.AfsLd4l-yj_7VtOZL-cdz_dJQBgLFnbSP_6DXBJvNSA+ scenes-app-replay-vision--scanner-status-throttled--dark:+ hash: v1.k794b7964.b4681ca6e30ca943483e5a46a6b2a7abae3fe092a94490c53c66b79159a45a8e.W2wuKPpLsnla_5QXzSygyA5V7tfxY2relLUyyINNxEc+ scenes-app-replay-vision--scanner-status-throttled--light:+ hash: v1.k794b7964.ee301e44caee1eb199c52e8332f5bf89450b2c53e2b802deb340196e7c18e431.JT0dNn7hmKif4mERgCnaWjAwlm8nDDTREskFZ8dGzwcscenes-app-replay-vision--scanner-templates--dark:hash: v1.k794b7964.5730130a0ab80bc33dc701a8cc69c354f8ac4f50df6c4a25f6b0627a4e90ceeb.0zwSfaSwHJZ0F2c__vQj7Bj3VUvQZD3nu5zcrxJym9oscenes-app-replay-vision--scanner-templates--light:@@ -10856,14 +10876,22 @@ snapshots:hash: v1.k794b7964.a521fd50b667cfab5ae7ed053b6da09a9968209dc20bac555dac760812c4a00d.G7vZH_-WgliA6P3jBIZuxtJgqs9W34BsyUFFpcTYafQscenes-app-replay-vision--scanners-list-empty--light:hash: v1.k794b7964.533b2eaad9875974cc55fa28ebaf6b24b8809536d845a614cd395300d1d108e5.BKc-ktztjTfLqTBgG-fnUpDTEFqICcHZ_xkPhKCwZ8k+ scenes-app-replay-vision--scorer-observations--dark:+ hash: v1.k794b7964.d181b6f136ac8aa27120e2a9e44f46c2b7ab8a16df90dd59fa852ee291dc8edf.yg8-er_QOaLh8Ld87xA4sEUXSjG_DmwvmMAt8Ygg3yM+ scenes-app-replay-vision--scorer-observations--light:+ hash: v1.k794b7964.5539629f1125ae0c6bac0f8cba09dd5e5c418f26887404a469b75dce67d4f628.T_Eblxldz9gWTionSAcbSOw6L8BUesjO99tAe7ZKNx8+ scenes-app-replay-vision--scorer-overview--dark:+ hash: v1.k794b7964.7a264ff949b74a429217dd9e6384dedc7de7a63db971562545e140597d53679b.Bi46jQCvp4jzq7MsLs1Cb_m6LJo5Fg3p1aOjwSnehzQ+ scenes-app-replay-vision--scorer-overview--light:+ hash: v1.k794b7964.1fd5476fbd98af37d35ebf8ec47042838f4d41f7438818d1d62d0647e178655a.pArZPQq64Osddye2YHoamGylAf4KP2PL0wlRh71K__Yscenes-app-replay-vision--startup-program-cap--dark:hash: v1.k794b7964.c621d85ea79f9e749deed225cdbca1daa3e3eec5790456dc2a7c0a1fa4d6c692.FCURh_R9xcDFAq5LbaSPxHzkZMXFpB9woeecjM5MhPQscenes-app-replay-vision--startup-program-cap--light:hash: v1.k794b7964.1f2fc262b5c742019e78b9fd8a13820c73291ee4c8086a34b01e8cdd47e31248.WubeGDNAdkP-6NxslVXFGWzr-pHvVfeYQQfEBk4LGj0scenes-app-replay-vision--summarizer-overview--dark:- hash: v1.k794b7964.0a6757ef4af2eca666787799e9521fd3d2c1e3d1310bc69ba983a50bfb742405.04FOFBX4MLEmhdRmTC_vFoRIuVRYA48ybJ2hMQx3pzE+ hash: v1.k794b7964.3cf688b3389147bab0a53625131694cef4cdb603e29b1cbf38025e7995a6ef9f.DZAtxS0vbp0spdTitEBHa5lSEz3cr6P5Npt0xMtFT18scenes-app-replay-vision--summarizer-overview--light:- hash: v1.k794b7964.c897f2b307bb7929d66c0f57b6654cbefeaa609a2bcfbd0d422b7bbc8f8f7fed.2yTPtWm2bYe82ly06Db0a7RBqYCZWq83sZwE8zMSLcQ+ hash: v1.k794b7964.7eb3356bc60e49218796f79dc510d54eac58abb836e55c922558071bfe94520c.4s5dNPolQ0r8tnz0JlQs_lQeP-aUR5ZcGX-V3bRq3L0scenes-app-replay-vision--usage-tab--dark:hash: v1.k794b7964.aab9212ef24367842f0c4b5c6e0b5568efa7b02455e0b762a0dae56f7a251ded.Vis7Q1vljRgKviTHYsDV5sgLm5fLA8DqNHkJ-26wpBEscenes-app-replay-vision--usage-tab--light:diff --git a/products/replay_vision/README.md b/products/replay_vision/README.mdindex 716588c9a14e..9c0e1a9b934f 100644--- a/products/replay_vision/README.md+++ b/products/replay_vision/README.md@@ -37,18 +37,16 @@ A scanner can also carry its own optional `credit_limit` for the same period, so| Scanners | (none) | The team's scanner roster plus the team-wide vision metrics. || Usage | `usage` | Credit spend over time for the org, bucketed daily/weekly/monthly/yearly. |-**Scanner** (`/replay-vision/<scanner-id>`), seven tabs switched through `?tab=`. Overview is the default and writes no param.--| Tab | `?tab=` | What it shows |-| ------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------- |-| Overview | `overview` | At-a-glance panels: impact, verdict mix, top fixed and freeform tags, score distribution. Leads with the scout digest card. |-| Observations | `observations` | The scanner's observations, filterable by status, verdict, tags, and date. |-| On-demand | `on-demand` | Scan now: by session ID, or by picking from recent recordings. |-| Backfills | `backfills` | The scanner's historical backfills: create one over a past window, watch progress, pause/resume. |-| Configuration | `configuration` | Read-only view of the scanner's current config. |-| Calibration | `calibration` | Thumbs up/down ratings, accuracy over time, feedback themes, and the AI prompt recommendation with its prompt test. |-| Scouts | `scouts` | The scanner's signals scouts, including its daily digest. |-| Alerts | `alerts` | The scanner's alerts on the shared alerts platform. |+**Scanner** (`/replay-vision/<scanner-id>`), six tabs switched through `?tab=`. Overview is the default and writes no param.++| Tab | `?tab=` | What it shows |+| ------------ | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Overview | `overview` | Scanner status, findings (verdict mix, top tags, score distribution), the scout digest, a configuration summary, and self-driving results. |+| Observations | `observations` | The scanner's observations, filterable by status, verdict, tags, and date. |+| Run | `run` | Scan one recording, a batch of recordings, or backfill a date range. Old `on-demand` and `backfills` links open here, and `configuration` opens Overview. |+| Calibration | `calibration` | Thumbs up/down ratings, accuracy over time, feedback themes, and the AI prompt recommendation with its prompt test. |+| Scouts | `scouts` | The scanner's signals scouts, including its daily digest. |+| Alerts | `alerts` | The scanner's alerts on the shared alerts platform. |**Scanner editor** (`/replay-vision/<scanner-id>/<step>`) is a stepper rather than tabs: Template, Configure, Scan conditions (`triggers`), Self-driving.Observations have their own scene under `/replay-vision/observations/…`.diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 7c50f6179bec..adb86d948448 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -1,5 +1,5 @@import json-from datetime import timedelta+from datetime import UTC, datetime, timedeltafrom typing import Any, NoReturn, castfrom uuid import UUID@@ -99,6 +99,7 @@ from products.replay_vision.backend.impact import (from products.replay_vision.backend.models.replay_observation import (ObservationStatus,ObservationTrigger,+ ObservationVerdict,ReplayObservation,hydrate_for_serialization,)@@ -158,6 +159,7 @@ from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTHfrom products.replay_vision.backend.tag_suggestions import SuggestionError, suggest_classifier_tagsfrom products.replay_vision.backend.temporal.constants import VISION_SIGNALS_SOURCE_PRODUCT, VISION_SIGNALS_SOURCE_TYPEfrom products.replay_vision.backend.temporal.metrics import record_estimate_outcome, record_scanner_limit_reached+from products.replay_vision.backend.temporal.read_meter_types import current_sweep_throttle_factorfrom products.replay_vision.backend.watch_feed import rank_watch_feed_candidatesfrom products.signals.backend.facade.api import get_outcomes_for_signal_source_slice@@ -592,6 +594,13 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial"enforcement gates apply. Always false when no limit is set."),)+ sweep_throttle_factor = serializers.SerializerMethodField(+ help_text=(+ "How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read "+ "budget. 1 means it checks for new recordings on the normal schedule; N means it checks once "+ "every N schedule intervals. Expensive filters raise it."+ ),+ )last_swept_at = serializers.DateTimeField(read_only=True,help_text="Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery.",@@ -647,6 +656,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial"observations_this_month","credits_used_against_limit","limit_reached",+ "sweep_throttle_factor","last_swept_at","created_at","created_by",@@ -665,6 +675,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial"observations_this_month","credits_used_against_limit","limit_reached",+ "sweep_throttle_factor","last_swept_at","created_at","created_by",@@ -728,6 +739,15 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerialdef get_credits_used_against_limit(self, scanner: ReplayScanner) -> int:return self._scanner_budget(scanner).credits_used+ @extend_schema_field(serializers.IntegerField())+ def get_sweep_throttle_factor(self, scanner: ReplayScanner) -> int:+ return current_sweep_throttle_factor(+ scanner.fast_read_bytes_by_hour,+ scanner.sweep_read_bytes_by_hour,+ scanner.sweep_throttle_factor_override,+ datetime.now(UTC),+ )+@extend_schema_field(serializers.BooleanField())def get_limit_reached(self, scanner: ReplayScanner) -> bool:# `blocked`, not `exhausted`: the enforcement gates admit an observation only when its full cost@@ -1797,8 +1817,8 @@ class ScannerImpactSerializer(serializers.Serializer):affected_sessions = serializers.IntegerField(read_only=True,help_text=(- "Distinct sessions with an affected observation in the window. For monitors only verdict-yes "- "observations count; for other scanner types every succeeded observation counts."+ "Distinct sessions with an affected observation in the window. For monitors only observations with "+ "the requested verdict count (yes by default); for other scanner types every succeeded observation counts."),)affected_users = serializers.IntegerField(@@ -1819,7 +1839,7 @@ class ScannerImpactSerializer(serializers.Serializer):class _ImpactQualifiersSerializer(serializers.Serializer):- """Shared impact parameters. Monitors take none; classifiers require `tag`; scorers require a score bound."""+ """Shared impact parameters. Monitors take an optional `verdict`; classifiers require `tag`; scorers require a score bound."""window_days = serializers.IntegerField(required=False,@@ -1828,6 +1848,16 @@ class _ImpactQualifiersSerializer(serializers.Serializer):max_value=90,help_text="Trailing window of observations to count. Defaults to 30 days.",)+ verdict = serializers.ChoiceField(+ choices=ObservationVerdict.choices,+ required=False,+ allow_null=True,+ default=None,+ help_text=(+ "Monitor scanners only: count sessions with this verdict. Defaults to `yes`. "+ "Not applicable to other scanner types."+ ),+ )tag = serializers.CharField(required=False,allow_null=True,@@ -1887,6 +1917,21 @@ class AffectedCohortResponseSerializer(serializers.Serializer):)+# The lists only feed a menu of links; the counts beside them stay exact.+MAX_SELF_DRIVING_LINKS = 20+++class SelfDrivingReportSerializer(serializers.Serializer):+ id = serializers.CharField(help_text="Signal report ID, for linking to it in the inbox.")+ title = serializers.CharField(allow_null=True, help_text="Report title. Null until the report is summarized.")+ status = serializers.CharField(help_text="The report's inbox status.")+++class SelfDrivingPullRequestSerializer(serializers.Serializer):+ url = serializers.CharField(help_text="URL of the implementation pull request.")+ merged = serializers.BooleanField(help_text="Whether the pull request has merged.")++class ScannerSelfDrivingStatsSerializer(serializers.Serializer):"""Response of GET /vision/scanners/:id/self_driving_stats/."""@@ -1901,6 +1946,12 @@ class ScannerSelfDrivingStatsSerializer(serializers.Serializer):)prs_opened = serializers.IntegerField(help_text="Implementation PRs opened by self-driving on those reports.")prs_merged = serializers.IntegerField(help_text="Of the opened PRs, how many have merged.")+ reports = SelfDrivingReportSerializer(+ many=True, help_text=f"The newest reports counted in `reports_contributed`, at most {MAX_SELF_DRIVING_LINKS}."+ )+ pull_requests = SelfDrivingPullRequestSerializer(+ many=True, help_text=f"The newest PRs counted in `prs_opened`, at most {MAX_SELF_DRIVING_LINKS}."+ )@extend_schema_view(@@ -2558,6 +2609,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viimpact = compute_scanner_impact(scanner,params.validated_data["window_days"],+ verdict=params.validated_data["verdict"],tag=params.validated_data["tag"],min_score=params.validated_data["min_score"],max_score=params.validated_data["max_score"],@@ -2575,6 +2627,10 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi)def self_driving_stats(self, request: Request, **kwargs: Any) -> Response:"""What self-driving did with this scanner's signals: reports contributed to and PRs opened."""+ # `required_scopes` only gates API keys, so a session member denied inbox access would otherwise+ # read the report titles, statuses and PR links that the inbox itself never shows them.+ if not self.user_access_control.check_access_level_for_resource("task", required_level="viewer"):+ raise PermissionDenied("Reading self-driving stats requires inbox read access.")scanner = self.get_object()outcomes = get_outcomes_for_signal_source_slice(team=self.team,@@ -2589,6 +2645,8 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi"reports_contributed": outcomes.report_count,"prs_opened": outcomes.pr_count,"prs_merged": outcomes.merged_pr_count,+ "reports": outcomes.reports[:MAX_SELF_DRIVING_LINKS],+ "pull_requests": outcomes.pull_requests[:MAX_SELF_DRIVING_LINKS],}).data)@@ -2622,6 +2680,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viscanner,cast(User, request.user),window_days=window_days,+ verdict=body.validated_data["verdict"],tag=body.validated_data["tag"],min_score=body.validated_data["min_score"],max_score=body.validated_data["max_score"],diff --git a/products/replay_vision/backend/impact.py b/products/replay_vision/backend/impact.pyindex a0d029e34404..a61e0ac99759 100644--- a/products/replay_vision/backend/impact.py+++ b/products/replay_vision/backend/impact.py@@ -12,6 +12,7 @@ from posthog.models.user import Userfrom products.cohorts.backend.models.cohort import Cohortfrom products.replay_vision.backend.models.replay_observation import (ObservationStatus,+ ObservationVerdict,ReplayObservation,annotate_output_number,)@@ -39,6 +40,7 @@ def affected_observations(scanner: ReplayScanner,window_days: int,*,+ verdict: ObservationVerdict | None = None,tag: str | None = None,min_score: float | None = None,max_score: float | None = None,@@ -60,7 +62,10 @@ def affected_observations(if scanner_type == ScannerType.MONITOR:if tag or has_scores:raise ValueError("Monitor impact is verdict-based; tag and score filters don't apply.")- return base.filter(scanner_result__model_output__verdict="yes")+ return base.filter(scanner_result__model_output__verdict=verdict or ObservationVerdict.YES)++ if verdict is not None:+ raise ValueError("Only monitors produce verdicts; `verdict` doesn't apply.")if scanner_type == ScannerType.CLASSIFIER:if has_scores:@@ -93,12 +98,13 @@ def compute_scanner_impact(scanner: ReplayScanner,window_days: int = DEFAULT_IMPACT_WINDOW_DAYS,*,+ verdict: ObservationVerdict | None = None,tag: str | None = None,min_score: float | None = None,max_score: float | None = None,) -> ScannerImpact:aggregates = affected_observations(- scanner, window_days, tag=tag, min_score=min_score, max_score=max_score+ scanner, window_days, verdict=verdict, tag=tag, min_score=min_score, max_score=max_score).aggregate(affected_sessions=Count("session_id", distinct=True),affected_users=Count("distinct_id", filter=_HAS_USER, distinct=True),@@ -107,7 +113,12 @@ def compute_scanner_impact(return ScannerImpact(window_days=window_days, **aggregates)-def _qualifier_label(tag: str | None, min_score: float | None, max_score: float | None) -> str:+def _qualifier_label(+ verdict: ObservationVerdict | None, tag: str | None, min_score: float | None, max_score: float | None+) -> str:+ # A plain monitor cohort has always meant verdict yes, so only the other verdicts get a label.+ if verdict and verdict != ObservationVerdict.YES:+ return f", verdict {verdict}"if tag:return f", tag {tag}"if min_score is not None and max_score is not None:@@ -124,13 +135,14 @@ def create_affected_cohort(user: User | None,window_days: int = DEFAULT_IMPACT_WINDOW_DAYS,*,+ verdict: ObservationVerdict | None = None,tag: str | None = None,min_score: float | None = None,max_score: float | None = None,) -> tuple[Cohort, int]:"""Static cohort of matched users; returns (cohort, real member count). Raises ValueError when not creatable."""distinct_ids = list(- affected_observations(scanner, window_days, tag=tag, min_score=min_score, max_score=max_score)+ affected_observations(scanner, window_days, verdict=verdict, tag=tag, min_score=min_score, max_score=max_score).filter(_HAS_USER).values_list("distinct_id", flat=True).distinct()[: MAX_COHORT_DISTINCT_IDS + 1]@@ -140,7 +152,7 @@ def create_affected_cohort(if len(distinct_ids) > MAX_COHORT_DISTINCT_IDS:raise ValueError(f"Too many users to save as one cohort (over {MAX_COHORT_DISTINCT_IDS:,}). Narrow the window.")- qualifier = _qualifier_label(tag, min_score, max_score)+ qualifier = _qualifier_label(verdict, tag, min_score, max_score)cohort = Cohort.objects.create(team_id=scanner.team_id,name=f"{COHORT_NAME_PREFIX}{scanner.name}{qualifier} ({timezone.now().date().isoformat()})"[:400],diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.pyindex b1b20944124f..cd5f7f997e9a 100644--- a/products/replay_vision/backend/models/replay_observation.py+++ b/products/replay_vision/backend/models/replay_observation.py@@ -29,6 +29,12 @@ IN_FLIGHT_STATUSES = (ObservationStatus.PENDING, ObservationStatus.RUNNING)TERMINAL_STATUSES = tuple(status for status in ObservationStatus if status not in IN_FLIGHT_STATUSES)+class ObservationVerdict(models.TextChoices):+ YES = "yes", "Yes"+ NO = "no", "No"+ INCONCLUSIVE = "inconclusive", "Inconclusive"++class ObservationTrigger(models.TextChoices):SCHEDULE = "schedule", "Schedule"ON_DEMAND = "on_demand", "On demand"diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.pyindex 36d27310a9b2..3f738d384a7a 100644--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py@@ -47,10 +47,10 @@ from products.replay_vision.backend.temporal.metrics import (record_sweep_outcome,)from products.replay_vision.backend.temporal.read_meter_types import (+ buckets_or_pre_split,+ current_sweep_throttle_factor,deep_spend_bytes_per_day,deep_sweep_throttle_factor,- sweep_spend_bytes_24h,- sweep_throttle_factor,)from products.replay_vision.backend.temporal.sweep_types import (CandidateSessionPayload,@@ -234,9 +234,11 @@ def _throttled(scanner: ReplayScanner) -> bool:lagging behind the horizon) is never throttled harder while it drains its backlog."""now = dt.datetime.now(dt.UTC)- factor = sweep_throttle_factor(- sweep_spend_bytes_24h(_buckets_or_pre_split(scanner.fast_read_bytes_by_hour, scanner), now),+ factor = current_sweep_throttle_factor(+ scanner.fast_read_bytes_by_hour,+ scanner.sweep_read_bytes_by_hour,scanner.sweep_throttle_factor_override,+ now,)if factor <= 1:return False@@ -275,12 +277,6 @@ def _priming_pass(scanner: ReplayScanner, query: RecordingsQuery, limit: int) ->return []-def _buckets_or_pre_split(buckets: dict[str, int] | None, scanner: ReplayScanner) -> dict[str, int] | None:- """`is None`, not truthiness: only a column the meter has never written falls back to the- pre-split total bucket, which keeps throttled scanners throttled across the deploy."""- return scanner.sweep_read_bytes_by_hour if buckets is None else buckets--# Kept back for the activity's own wrap-up (exclusion filtering, result serialization)._DEEP_QUERY_RESERVE_SECONDS = 60# Below this a deep query over a padded events window has no realistic chance of finishing.@@ -326,7 +322,9 @@ def _deep_sweep(if now - last_attempt < DEEP_SWEEP_INTERVAL:return [], Nonefactor = deep_sweep_throttle_factor(- deep_spend_bytes_per_day(_buckets_or_pre_split(scanner.deep_read_bytes_by_hour, scanner), now)+ deep_spend_bytes_per_day(+ buckets_or_pre_split(scanner.deep_read_bytes_by_hour, scanner.sweep_read_bytes_by_hour), now+ ))if now - last_attempt < DEEP_SWEEP_INTERVAL * factor:return [], Nonediff --git a/products/replay_vision/backend/temporal/read_meter_types.py b/products/replay_vision/backend/temporal/read_meter_types.pyindex 4f994c6a80ff..59bccc589c75 100644--- a/products/replay_vision/backend/temporal/read_meter_types.py+++ b/products/replay_vision/backend/temporal/read_meter_types.py@@ -78,6 +78,26 @@ def sweep_throttle_factor(spend_bytes: int, override: int | None) -> int:return _throttle_factor(spend_bytes, SWEEP_READ_BUDGET_BYTES_24H, SWEEP_THROTTLE_MAX_FACTOR)+def buckets_or_pre_split(+ buckets: dict[str, int] | None, pre_split_by_hour: dict[str, int] | None+) -> dict[str, int] | None:+ """`is None`, not truthiness: only a column the meter has never written falls back to the+ pre-split total bucket, which keeps throttled scanners throttled across the deploy."""+ return pre_split_by_hour if buckets is None else buckets+++def current_sweep_throttle_factor(+ fast_by_hour: dict[str, int] | None,+ pre_split_by_hour: dict[str, int] | None,+ override: int | None,+ now: dt.datetime,+) -> int:+ """The frequent sweep's throttle factor right now, from the scanner's metered read buckets."""+ return sweep_throttle_factor(+ sweep_spend_bytes_24h(buckets_or_pre_split(fast_by_hour, pre_split_by_hour), now), override+ )++def deep_sweep_throttle_factor(spend_bytes_per_day: int) -> int:"""Interval-stretch multiplier for the deep pass: N means it runs every N x DEEP_SWEEP_INTERVAL.diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 63d5501a676c..79551bbe589d 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -58,6 +58,7 @@ from products.replay_vision.backend.search import ObservationMatchfrom products.replay_vision.backend.temporal.constants import (APPLY_SCANNER_EXECUTION_TIMEOUT,APPLY_SCANNER_WORKFLOW_NAME,+ SWEEP_READ_BUDGET_BYTES_24H,build_apply_scanner_workflow_id,on_demand_priority,)@@ -66,7 +67,11 @@ from products.replay_vision.backend.tests.helpers import (seed_scanner_spend,snapshot_for as _snapshot_for,)-from products.signals.backend.facade.api import SignalSourceSliceOutcomes, SignalSourceSliceReport+from products.signals.backend.facade.api import (+ SignalSourceSliceOutcomes,+ SignalSourceSlicePullRequest,+ SignalSourceSliceReport,+)from products.signals.backend.models import SignalSourceConfig@@ -3936,6 +3941,19 @@ class TestScannerSpend(_VisionAPITestCase):self.assertIs(resp.json()["limit_reached"], True)self.assertEqual(resp.json()["credits_used_against_limit"], cost)+ def test_sweep_throttle_factor_follows_the_frequent_sweeps_reads_and_the_override(self) -> None:+ scanner = self._create_scanner()+ hour = datetime.now(UTC).replace(minute=0, second=0, microsecond=0).isoformat()+ # Deep-pass reads have their own budget, so they must not slow the sweep the status reports.+ ReplayScanner.objects.filter(pk=scanner.pk).update(+ fast_read_bytes_by_hour={hour: 3 * SWEEP_READ_BUDGET_BYTES_24H},+ deep_read_bytes_by_hour={hour: 100 * SWEEP_READ_BUDGET_BYTES_24H},+ )+ self.assertEqual(self.client.get(f"{self.scanners_url}{scanner.id}/").json()["sweep_throttle_factor"], 3)++ ReplayScanner.objects.filter(pk=scanner.pk).update(sweep_throttle_factor_override=1)+ self.assertEqual(self.client.get(f"{self.scanners_url}{scanner.id}/").json()["sweep_throttle_factor"], 1)+def test_limit_fields_are_per_row_on_the_list_endpoint(self) -> None:# The page's budgets are computed once and cached on the shared serializer context, so a lookup# keyed on the wrong scanner would give every row the first row's answer.@@ -5131,7 +5149,18 @@ class TestScannerSelfDrivingStatsAPI(_VisionAPITestCase):# Wiring guard: the endpoint must query the signals facade for this scanner's slice and# serialize the outcome counts; a dropped extra filter would return team-wide numbers.scanner = self._create_scanner()- outcomes = SignalSourceSliceOutcomes(signal_count=5, report_count=2, pr_count=1, merged_pr_count=1)+ created_at = datetime(2026, 5, 1, tzinfo=UTC)+ outcomes = SignalSourceSliceOutcomes(+ signal_count=5,+ report_count=2,+ pr_count=1,+ merged_pr_count=1,+ reports=[+ SignalSourceSliceReport(id="r-new", title="Checkout stalls", status="ready", created_at=created_at),+ SignalSourceSliceReport(id="r-old", title=None, status="potential", created_at=created_at),+ ],+ pull_requests=[SignalSourceSlicePullRequest(url="https://github.com/example/app/pull/1", merged=True)],+ )with patch("products.replay_vision.backend.api.scanners.get_outcomes_for_signal_source_slice",return_value=outcomes,@@ -5144,12 +5173,29 @@ class TestScannerSelfDrivingStatsAPI(_VisionAPITestCase):"reports_contributed": 2,"prs_opened": 1,"prs_merged": 1,+ "reports": [+ {"id": "r-new", "title": "Checkout stalls", "status": "ready"},+ {"id": "r-old", "title": None, "status": "potential"},+ ],+ "pull_requests": [{"url": "https://github.com/example/app/pull/1", "merged": True}],}kwargs = mock_outcomes.call_args.kwargsassert kwargs["source_product"] == "replay_vision"assert kwargs["source_type"] == "scanner_finding"assert kwargs["extra_equals"] == {"scanner_id": str(scanner.id)}+ def test_denied_without_inbox_read_access(self) -> None:+ # Scopes only gate API keys, so a session member denied inbox access must not read the+ # report titles and PR links this response carries.+ scanner = self._create_scanner()+ with patch(+ "products.access_control.backend.facade.user_access_control.UserAccessControl.check_access_level_for_resource",+ side_effect=lambda resource, required_level=None, **_: resource != "task",+ ):+ response = self.client.get(f"{self.scanners_url}{scanner.id}/self_driving_stats/")++ assert response.status_code == 403, response.json()+class TestObservationSignalReportsAPI(_VisionAPITestCase):def test_returns_the_reports_this_observations_signals_landed_in(self) -> None:diff --git a/products/replay_vision/backend/tests/test_impact.py b/products/replay_vision/backend/tests/test_impact.pyindex 581888118470..779876b22cce 100644--- a/products/replay_vision/backend/tests/test_impact.py+++ b/products/replay_vision/backend/tests/test_impact.py@@ -10,10 +10,11 @@ from django.utils import timezonefrom parameterized import parameterizedfrom products.cohorts.backend.models.cohort import Cohort-from products.replay_vision.backend.impact import compute_scanner_impact, create_affected_cohort+from products.replay_vision.backend.impact import affected_observations, compute_scanner_impact, create_affected_cohortfrom products.replay_vision.backend.models.replay_observation import (ObservationStatus,ObservationTrigger,+ ObservationVerdict,ReplayObservation,)from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType@@ -63,16 +64,29 @@ class _ImpactTestCase(APIBaseTest):class TestComputeScannerImpact(_ImpactTestCase):- def test_monitor_counts_only_verdict_yes(self) -> None:+ @parameterized.expand(+ [+ ("defaults_to_yes", None, "u-yes"),+ ("yes", ObservationVerdict.YES, "u-yes"),+ ("no", ObservationVerdict.NO, "u-no"),+ ("inconclusive", ObservationVerdict.INCONCLUSIVE, "u-inc"),+ ]+ )+ def test_monitor_counts_only_the_requested_verdict(+ self, _name: str, verdict: ObservationVerdict | None, expected_user: str+ ) -> None:scanner = self._make_scanner(ScannerType.MONITOR)- self._make_observation(scanner, session_id="s-yes", distinct_id="u1", verdict="yes")- self._make_observation(scanner, session_id="s-no", distinct_id="u2", verdict="no")- self._make_observation(scanner, session_id="s-inc", distinct_id="u3", verdict="inconclusive")+ self._make_observation(scanner, session_id="s-yes", distinct_id="u-yes", verdict="yes")+ self._make_observation(scanner, session_id="s-no", distinct_id="u-no", verdict="no")+ self._make_observation(scanner, session_id="s-inc", distinct_id="u-inc", verdict="inconclusive")- impact = compute_scanner_impact(scanner)+ impact = compute_scanner_impact(scanner, verdict=verdict)assert impact.affected_sessions == 1assert impact.affected_users == 1+ assert list(affected_observations(scanner, 30, verdict=verdict).values_list("distinct_id", flat=True)) == [+ expected_user+ ]def test_classifier_counts_only_sessions_with_the_tag(self) -> None:scanner = self._make_scanner(ScannerType.CLASSIFIER)@@ -98,6 +112,7 @@ class TestComputeScannerImpact(_ImpactTestCase):@parameterized.expand([("monitor_rejects_tag", ScannerType.MONITOR, {"tag": "bug"}),+ ("classifier_rejects_verdict", ScannerType.CLASSIFIER, {"tag": "bug", "verdict": ObservationVerdict.NO}),("classifier_requires_tag", ScannerType.CLASSIFIER, {}),("scorer_requires_bound", ScannerType.SCORER, {}),("summarizer_unsupported", ScannerType.SUMMARIZER, {}),diff --git a/products/replay_vision/frontend/components/LabeledRow.tsx b/products/replay_vision/frontend/components/LabeledRow.tsxindex f145b15746e4..62c9062768d1 100644--- a/products/replay_vision/frontend/components/LabeledRow.tsx+++ b/products/replay_vision/frontend/components/LabeledRow.tsx@@ -1,9 +1,27 @@+import { IconInfo } from '@posthog/icons'+import { Tooltip } from '@posthog/lemon-ui'+/** A label-above-content row used across the readonly config and observation detail cards. */-export function LabeledRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {+export function LabeledRow({+ label,+ tooltip,+ children,+}: {+ label: string+ tooltip?: string+ children: React.ReactNode+}): JSX.Element {return (<div>- <div className="text-xs text-muted mb-0.5">{label}</div>- <div className="text-sm">{children}</div>+ <div className="flex items-center gap-1 text-xs text-muted mb-0.5">+ {label}+ {tooltip && (+ <Tooltip title={tooltip}>+ <IconInfo className="text-sm" />+ </Tooltip>+ )}+ </div>+ <div className="text-sm min-w-0">{children}</div></div>)}diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 9e10b3fe2fb8..d0e621efd424 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -1021,6 +1021,8 @@ export interface ReplayScannerApi {readonly credits_used_against_limit: number/** Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is set and the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set. */readonly limit_reached: boolean+ /** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */+ readonly sweep_throttle_factor: number/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at: stringreadonly created_at: string@@ -1145,6 +1147,8 @@ export interface PatchedReplayScannerApi {readonly credits_used_against_limit?: number/** Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is set and the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set. */readonly limit_reached?: boolean+ /** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */+ readonly sweep_throttle_factor?: number/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at?: stringreadonly created_at?: string@@ -1160,6 +1164,19 @@ export interface PatchedReplayScannerApi {readonly user_access_level?: string | null}+/**+ * * `yes` - Yes+ * * `no` - No+ * * `inconclusive` - Inconclusive+ */+export type ObservationVerdictEnumApi = (typeof ObservationVerdictEnumApi)[keyof typeof ObservationVerdictEnumApi]++export const ObservationVerdictEnumApi = {+ Yes: 'yes',+ No: 'no',+ Inconclusive: 'inconclusive',+} as const+/*** Body of POST /vision/scanners/:id/affected_cohort/. Same qualifiers as the impact GET.*/@@ -1170,6 +1187,12 @@ export interface AffectedCohortRequestApi {* @maximum 90*/window_days?: number+ /** Monitor scanners only: count sessions with this verdict. Defaults to `yes`. Not applicable to other scanner types.+ *+ * * `yes` - Yes+ * * `no` - No+ * * `inconclusive` - Inconclusive */+ verdict?: ObservationVerdictEnumApi | null/*** Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.* @maxLength 100@@ -1267,7 +1290,7 @@ export interface BulkObserveResponseApi {* Who this scanner's findings affected in the window; counted from observations, not estimated.*/export interface ScannerImpactApi {- /** Distinct sessions with an affected observation in the window. For monitors only verdict-yes observations count; for other scanner types every succeeded observation counts. */+ /** Distinct sessions with an affected observation in the window. For monitors only observations with the requested verdict count (yes by default); for other scanner types every succeeded observation counts. */readonly affected_sessions: number/** Distinct users behind the affected sessions, by distinct ID. May include anonymous device IDs when the recorded sessions were not identified. */readonly affected_users: number@@ -1304,6 +1327,25 @@ export interface ObserveResponseApi {workflow_id: string}+export interface SelfDrivingReportApi {+ /** Signal report ID, for linking to it in the inbox. */+ id: string+ /**+ * Report title. Null until the report is summarized.+ * @nullable+ */+ title: string | null+ /** The report's inbox status. */+ status: string+}++export interface SelfDrivingPullRequestApi {+ /** URL of the implementation pull request. */+ url: string+ /** Whether the pull request has merged. */+ merged: boolean+}+/*** Response of GET /vision/scanners/:id/self_driving_stats/.*/@@ -1316,6 +1358,10 @@ export interface ScannerSelfDrivingStatsApi {prs_opened: number/** Of the opened PRs, how many have merged. */prs_merged: number+ /** The newest reports counted in `reports_contributed`, at most 20. */+ reports: SelfDrivingReportApi[]+ /** The newest PRs counted in `prs_opened`, at most 20. */+ pull_requests: SelfDrivingPullRequestApi[]}/**@@ -2775,6 +2821,15 @@ export type VisionScannersImpactRetrieveParams = {* @nullable*/tag?: string | null+ /**+ * Monitor scanners only: count sessions with this verdict. Defaults to `yes`. Not applicable to other scanner types.+ *+ * * `yes` - Yes+ * * `no` - No+ * * `inconclusive` - Inconclusive+ * @nullable+ */+ verdict?: VisionScannersImpactRetrieveVerdict/*** Trailing window of observations to count. Defaults to 30 days.* @minimum 1@@ -2783,6 +2838,16 @@ export type VisionScannersImpactRetrieveParams = {window_days?: number}+export type VisionScannersImpactRetrieveVerdict =+ | (typeof VisionScannersImpactRetrieveVerdict)[keyof typeof VisionScannersImpactRetrieveVerdict]+ | null++export const VisionScannersImpactRetrieveVerdict = {+ Yes: 'yes',+ No: 'no',+ Inconclusive: 'inconclusive',+} as const+export type VisionScannersBackfillsListParams = {/*** Number of results to return per page.diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex 6d47cfaffe2a..da75dd0a65d4 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -796,6 +796,17 @@ export const VisionScannersAffectedCohortCreateBody = /* @__PURE__ */ zod.max(visionScannersAffectedCohortCreateBodyWindowDaysMax).default(visionScannersAffectedCohortCreateBodyWindowDaysDefault).describe('Trailing window of observations to count. Defaults to 30 days.'),+ verdict: zod+ .union([+ zod+ .enum(['yes', 'no', 'inconclusive'])+ .describe('\* `yes` - Yes\n\* `no` - No\n\* `inconclusive` - Inconclusive'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Monitor scanners only: count sessions with this verdict. Defaults to `yes`. Not applicable to other scanner types.\n\n\* `yes` - Yes\n\* `no` - No\n\* `inconclusive` - Inconclusive'+ ),tag: zod.string().max(visionScannersAffectedCohortCreateBodyTagMax)diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.test.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.test.tsxindex 7d8c3d6dfda5..5fbfba2a0fc1 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.test.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.test.tsx@@ -15,21 +15,9 @@ const mockImportedTabs: string[] = []jest.mock('./components/ScannerOverview', () => ({ ScannerOverview: () => <div>Overview content</div> }))jest.mock('./components/ScannerScoutCard', () => ({ ScannerScoutCard: () => null }))-jest.mock('./components/ScannerRunTab', () => {- mockImportedTabs.push('On-demand')- return { ScannerRunTab: ({ scannerId }: { scannerId: string }) => <div>On-demand content {scannerId}</div> }-})-jest.mock('./components/ScannerBackfillsTab', () => {- mockImportedTabs.push('Backfills')- return { ScannerBackfillsTab: ({ scannerId }: { scannerId: string }) => <div>Backfills content {scannerId}</div> }-})-jest.mock('./components/ScannerConfigReadonly', () => {- mockImportedTabs.push('Configuration')- return {- ScannerConfigReadonly: ({ scanner }: { scanner: { id: string } }) => (- <div>Configuration content {scanner.id}</div>- ),- }+jest.mock('./components/ScannerScanTab', () => {+ mockImportedTabs.push('Run')+ return { ScannerScanTab: ({ scannerId }: { scannerId: string }) => <div>Run content {scannerId}</div> }})jest.mock('./components/ScannerCalibrationTab', () => {mockImportedTabs.push('Calibration')@@ -96,20 +84,26 @@ describe('ReplayScanner', () => {expect(observationRequests[0].get('backfill_id')).toBe(backfillId)expect(mockImportedTabs).toEqual([])- const tabs = ['On-demand', 'Backfills', 'Configuration', 'Calibration', 'Scouts', 'Alerts']- for (const [index, tab] of tabs.entries()) {+ const tabKeys: [string, string][] = [+ ['Run', 'run'],+ ['Calibration', 'calibration'],+ ['Scouts', 'scouts'],+ ['Alerts', 'alerts'],+ ]+ const tabs = tabKeys.map(([label]) => label)+ for (const [index, [tab, key]] of tabKeys.entries()) {fireEvent.click(screen.getByText(tab, { exact: true }))expect(screen.getByText('Observations', { exact: true })).toBeInTheDocument()await screen.findByText(`${tab} content scanner-example`)expect(mockImportedTabs).toEqual(tabs.slice(0, index + 1))- expect(router.values.searchParams.tab).toBe(tab.toLowerCase())+ expect(router.values.searchParams.tab).toBe(key)expect(logic.values.observationsActive).toBe(false)}fireEvent.click(screen.getByText('Observations', { exact: true }))await waitFor(() => expect(logic.values.observationsActive).toBe(true))- fireEvent.click(screen.getByText('Configuration', { exact: true }))- await screen.findByText('Configuration content scanner-example')+ fireEvent.click(screen.getByText('Calibration', { exact: true }))+ await screen.findByText('Calibration content scanner-example')expect(logic.values.observationsActive).toBe(false)expect(mockImportedTabs).toEqual(tabs)diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsxindex 41f2453e7ca9..f456d37cc5cd 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx@@ -2,11 +2,10 @@ import { useActions, useValues } from 'kea'import { Suspense } from 'react'import { IconSparkles } from '@posthog/icons'-import { LemonBanner, LemonButton, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonTag, Spinner } from '@posthog/lemon-ui'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'-import { percentage } from 'lib/utils/numbers'import { lazyWithRetry } from 'lib/utils/retryImport'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -24,26 +23,17 @@ import { quotaBannerState } from '../utils/quotaProjection'import { calibrationActivationLogic } from './calibrationActivationLogic'import { ScannerObservationsTable } from './components/ScannerObservationsTable'import { ScannerOverview } from './components/ScannerOverview'-import { ScannerScoutCard } from './components/ScannerScoutCard'import { replayScannerLogic } from './replayScannerLogic'import { ReplayScannerTab, replayScannerSceneLogic } from './replayScannerSceneLogic'-import { scanDrought } from './scanDrought'-import { LIMIT_REACHED_TOOLTIP } from './scannerCopy'const ScannerAlertsTab = lazyWithRetry(() =>import('./components/ScannerAlertsTab').then((module) => ({ default: module.ScannerAlertsTab })))-const ScannerBackfillsTab = lazyWithRetry(() =>- import('./components/ScannerBackfillsTab').then((module) => ({ default: module.ScannerBackfillsTab }))-)const ScannerCalibrationTab = lazyWithRetry(() =>import('./components/ScannerCalibrationTab').then((module) => ({ default: module.ScannerCalibrationTab })))-const ScannerConfigReadonly = lazyWithRetry(() =>- import('./components/ScannerConfigReadonly').then((module) => ({ default: module.ScannerConfigReadonly }))-)-const ScannerRunTab = lazyWithRetry(() =>- import('./components/ScannerRunTab').then((module) => ({ default: module.ScannerRunTab }))+const ScannerScanTab = lazyWithRetry(() =>+ import('./components/ScannerScanTab').then((module) => ({ default: module.ScannerScanTab })))const ScannerScoutsTab = lazyWithRetry(() =>import('./components/ScannerScoutsTab').then((module) => ({ default: module.ScannerScoutsTab }))@@ -80,13 +70,6 @@ export function ReplayScannerSceneComponent(): JSX.Element {<SceneContent><SceneTitleSectionname={scanner.name || 'Untitled scanner'}- nameSuffix={- scanner.limit_reached ? (- <Tooltip title={LIMIT_REACHED_TOOLTIP}>- <LemonTag type="danger">Limit reached</LemonTag>- </Tooltip>- ) : undefined- }description={scanner.description}resourceType={{ type: 'replay_vision' }}actions={@@ -120,7 +103,6 @@ export function ReplayScannerSceneComponent(): JSX.Element {<IngestionLimitBanner /><QuotaBanner />- <ScanDroughtBanner scannerId={scannerId} /><LemonTabsactiveKey={activeTab}@@ -152,7 +134,6 @@ export function ReplayScannerSceneComponent(): JSX.Element {</LemonButton></div>)}- <ScannerScoutCard scannerId={scannerId} scannerName={scanner.name || ''} /><ScannerOverview scannerId={scannerId} /></div>),@@ -163,19 +144,9 @@ export function ReplayScannerSceneComponent(): JSX.Element {content: <ScannerObservationsTable scannerId={scannerId} />,},{- key: ReplayScannerTab.OnDemand,- label: 'On-demand',- content: <ScannerRunTab scannerId={scannerId} />,- },- {- key: ReplayScannerTab.Backfills,- label: 'Backfills',- content: <ScannerBackfillsTab scannerId={scannerId} />,- },- {- key: ReplayScannerTab.Configuration,- label: 'Configuration',- content: <ScannerConfigReadonly scanner={scanner} />,+ key: ReplayScannerTab.Run,+ label: 'Run',+ content: <ScannerScanTab scannerId={scannerId} />,},{key: ReplayScannerTab.Calibration,@@ -238,33 +209,4 @@ function QuotaBanner(): JSX.Element | null {)}-// Silence after a config change reads as "the product is broken", so name the real cause: filters that-// match nothing, or sampling skipping the few sessions that do match.-function ScanDroughtBanner({ scannerId }: { scannerId: string }): JSX.Element | null {- const { scanner, observationStatsApi } = useValues(replayScannerLogic({ id: scannerId }))- const { quota } = useValues(visionQuotaLogic)- // An exhausted quota already explains the silence in its own banner above.- if (!scanner || quotaBannerState(quota).kind === 'exhausted') {- return null- }- const drought = scanDrought(scanner, observationStatsApi?.labels.version_markers ?? null, new Date())- if (!drought) {- return null- }- const samplingNote =- drought.samplingRate < 1- ? `, and sampling only scans ${percentage(drought.samplingRate)} of the sessions that do`- : ''- return (- <LemonBanner- type="warning"- action={{ children: 'Review filters', to: urls.replayVisionScannerTriggers(scannerId) }}- >- {drought.everScanned- ? `No sessions have been scanned since this scanner's configuration last changed, even though sweeps have run since. The filters may match no recordings${samplingNote}.`- : `This scanner hasn't scanned any sessions yet, even though sweeps have run. The filters may match no recordings${samplingNote}.`}- </LemonBanner>- )-}-export default ReplayScannerSceneComponentdiff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex 8cd611732f3c..1e288dddcf2e 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -11,11 +11,14 @@ import { RecordingsQuery } from '~/queries/schema/schema-general'import { StartupProgramLabel } from '~/types'import type {+ BackfillEstimateResponseApi,DraftScannerResponseApi,ObservationStatsApi,ReplayObservationApi,ReplayScannerApi,+ ReplayScannerBackfillApi,ReplayScannerPromptSuggestionApi,+ ScannerSelfDrivingStatsApi,ScannerStatsResponseApi,UserBasicApi,VisionQuotaApi,@@ -69,6 +72,7 @@ const scanner = (overrides: Partial<ReplayScannerApi> = {}): ReplayScannerApi =>estimated_monthly_credits: null,estimated_at: null,user_access_level: 'editor',+ sweep_throttle_factor: 1,...overrides,}) as ReplayScannerApi@@ -179,13 +183,188 @@ const summarizerStats: ObservationStatsApi = {scorer: null,} as ObservationStatsApi-const scannerImpact = {- affected_sessions: 1284,- affected_users: 967,- sessions_without_user: 41,- window_days: 30,+// One finished backfill and one still running, so the history table renders both states.+const backfills: ReplayScannerBackfillApi[] = [+ {+ id: '00000000-0000-0000-0000-0000000000f7',+ status: 'running',+ window_start: '2026-05-05T00:00:00Z',+ window_end: '2026-05-12T00:00:00Z',+ total_count: 420,+ dispatched_count: 260,+ skipped_count: 12,+ credits_per_observation: 1,+ succeeded_count: 231,+ failed_count: 4,+ ineligible_count: 9,+ in_flight_count: 16,+ created_by: alice,+ created_at: '2026-05-11T20:00:00Z',+ finished_at: null,+ },+ {+ id: '00000000-0000-0000-0000-0000000000f8',+ status: 'completed',+ window_start: '2026-04-20T00:00:00Z',+ window_end: '2026-04-27T00:00:00Z',+ total_count: 186,+ dispatched_count: 180,+ skipped_count: 6,+ credits_per_observation: 1,+ succeeded_count: 168,+ failed_count: 2,+ ineligible_count: 4,+ in_flight_count: 0,+ created_by: bob,+ created_at: '2026-04-28T10:00:00Z',+ finished_at: '2026-04-28T11:30:00Z',+ },+] as ReplayScannerBackfillApi[]++const backfillEstimate: BackfillEstimateResponseApi = {+ total_sessions: 312,+ total_credits: 312,+ credits_per_observation: 1,+ credits_remaining: 7600,+ window_start: '2026-05-05T00:00:00Z',+ window_end: '2026-05-12T00:00:00Z',+}++const noSelfDrivingStats: ScannerSelfDrivingStatsApi = {+ signals_emitted: 0,+ reports_contributed: 0,+ prs_opened: 0,+ prs_merged: 0,+ reports: [],+ pull_requests: [],+}++const activeSelfDrivingStats: ScannerSelfDrivingStatsApi = {+ signals_emitted: 64,+ reports_contributed: 9,+ prs_opened: 4,+ prs_merged: 2,+ reports: [+ {+ id: '00000000-0000-0000-0000-0000000000e1',+ title: 'Shipping step stalls after address reset',+ status: 'ready',+ },+ { id: '00000000-0000-0000-0000-0000000000e2', title: 'Coupon field rejects valid codes', status: 'ready' },+ ],+ pull_requests: [+ { url: 'https://github.com/example/shop/pull/412', merged: true },+ { url: 'https://github.com/example/shop/pull/409', merged: true },+ { url: 'https://github.com/example/shop/pull/405', merged: false },+ { url: 'https://github.com/example/shop/pull/398', merged: false },+ ],}+const monitorOverviewScanner: ReplayScannerApi = {+ ...scanners.results[0],+ scanner_config: {+ prompt: [+ 'Did the user struggle to complete checkout?',+ '',+ 'Answer yes if the user shows clear friction on the cart, shipping, or payment steps. Friction includes',+ 'retrying the payment form, going back to an earlier step, rage-clicking a disabled button, or leaving',+ 'the page within a minute of seeing an error message.',+ '',+ 'Answer no if the user completes the order without backtracking, or never reaches the cart.',+ '',+ 'Ignore sessions from internal staff accounts and sessions shorter than ten seconds.',+ ].join('\n'),+ },+ emits_signals: true,+ credit_limit: 5000,+ credits_used_against_limit: 3400,+ query: {+ kind: 'RecordingsQuery',+ events: [{ id: '$pageview', type: 'events', name: '$pageview', order: 0 }],+ properties: [+ { type: 'recording', key: 'visited_page', value: ['/checkout'], operator: 'icontains' },+ { type: 'person', key: 'plan', value: ['growth'], operator: 'exact' },+ ],+ having_predicates: [{ type: 'recording', key: 'active_seconds', value: 30, operator: 'gt' }],+ filter_test_accounts: true,+ },+ experiment_targeting: { experiment_id: 11, variant: 'test' },+}++const monitorOverviewStats: ObservationStatsApi = {+ ...summarizerStats,+ monitor: { yes_total: 38, no_total: 97, inconclusive_total: 7 },+}++const classifierOverviewScanner: ReplayScannerApi = {+ ...scanners.results[1],+ enabled: true,+ query: {+ kind: 'RecordingsQuery',+ properties: [{ type: 'event', key: '$browser', value: ['Safari'], operator: 'exact' }],+ },+ scanner_config: {+ prompt: 'Tag session.',+ tags: ['rage-click', 'dead-end', 'slow-load', 'form-error'],+ multi_label: true,+ allow_freeform_tags: true,+ },+}++const classifierOverviewStats: ObservationStatsApi = {+ ...summarizerStats,+ available_tags: ['rage-click', 'dead-end', 'slow-load', 'form-error', 'coupon-confusion', 'modal-trap'],+ classifier: {+ fixed_ranked: [+ { tag: 'rage-click', count: 54 },+ { tag: 'slow-load', count: 31 },+ { tag: 'dead-end', count: 18 },+ { tag: 'form-error', count: 9 },+ ],+ freeform_ranked: [+ { tag: 'coupon-confusion', count: 6 },+ { tag: 'modal-trap', count: 2 },+ ],+ total_with_tags: 97,+ },+}++const scorerOverviewScanner: ReplayScannerApi = {+ ...scanners.results[3],+ credit_limit: 400,+ credits_used_against_limit: 399,+ limit_reached: true,+}++const scorerOverviewStats: ObservationStatsApi = {+ ...summarizerStats,+ scorer: {+ summary: { min: 0.5, p25: 3.2, median: 5.1, mean: 5.3, p75: 7.4, max: 9.8, count: 142 },+ histogram: {+ labels: ['0-1', '1-2', '2-3', '3-4', '4-5', '5-6', '6-7', '7-8', '8-9', '9-10'],+ counts: [2, 5, 11, 19, 27, 30, 22, 14, 8, 4],+ },+ },+}++const overviewDecorator = (+ scannerResponse: ReplayScannerApi,+ stats: ObservationStatsApi,+ selfDrivingStats: ScannerSelfDrivingStatsApi = noSelfDrivingStats+): ReturnType<typeof mswDecorator> =>+ mswDecorator({+ get: {+ '/api/projects/:team_id/vision/scanners/:id/': scannerResponse,+ '/api/projects/:team_id/vision/scanners/:id/observations/stats/': stats,+ '/api/projects/:team_id/vision/scanners/:id/self_driving_stats/': selfDrivingStats,+ '/api/projects/:team_id/experiments/:id/': {+ id: 11,+ name: 'New shipping step',+ feature_flag_key: 'new-shipping-step',+ },+ },+ })+const observation = (overrides: Partial<ReplayObservationApi> = {}): ReplayObservationApi =>({id: '00000000-0000-0000-0000-0000000000b1',@@ -272,6 +451,7 @@ const observations = {recording_subject_email: '[email protected]',distinct_id: 'user_2m1x9d',label: { is_correct: false, feedback: 'Missed the failed payment retry entirely.' },+ viewed: true,}),],}@@ -599,7 +779,7 @@ const meta: Meta = {'/api/projects/:team_id/vision/quota/': quota,'/api/projects/:team_id/vision/quota/spend_series/': spendSeries,'/api/projects/:team_id/vision/scanners/:id/': summarizerScanner,- '/api/projects/:team_id/vision/scanners/:id/impact/': scannerImpact,+ '/api/projects/:team_id/vision/scanners/:id/self_driving_stats/': noSelfDrivingStats,'/api/projects/:team_id/vision/scanners/:id/observations/': observations,'/api/projects/:team_id/vision/scanners/:id/observations/stats/': summarizerStats,'/api/projects/:team_id/vision/scanners/:scannerId/prompt_suggestions/': {@@ -627,6 +807,12 @@ const meta: Meta = {'/api/projects/:team_id/signals/scout/metadata/current/': {},'/api/projects/:team_id/vision/scanners/:scannerId/scout_reports/': [],'/api/projects/:team_id/vision/alerts/': { count: 0, next: null, previous: null, results: [] },+ '/api/projects/:team_id/vision/scanners/:scannerId/backfills/': {+ count: backfills.length,+ next: null,+ previous: null,+ results: backfills,+ },// The three namespaces the pinned-properties picker offers.'/api/environments/:team_id/sessions/property_definitions/': paginated(['$entry_referring_domain',@@ -650,6 +836,7 @@ const meta: Meta = {: observationsTrend},'/api/projects/:team_id/vision/scanners/estimate/': estimate,+ '/api/projects/:team_id/vision/scanners/:scannerId/backfills/estimate/': backfillEstimate,},}),],@@ -728,6 +915,27 @@ export const SummarizerOverview: StoryObj = {parameters: { pageUrl: urls.replayVision(summarizerScanner.id) },}+export const MonitorOverview: StoryObj = {+ parameters: { pageUrl: urls.replayVision(monitorOverviewScanner.id) },+ decorators: [overviewDecorator(monitorOverviewScanner, monitorOverviewStats, activeSelfDrivingStats)],+}++// Expensive filters stretch the sweep to its hourly ceiling, so the status strip reports it as throttled.+export const ScannerStatusThrottled: StoryObj = {+ parameters: { pageUrl: urls.replayVision(summarizerScanner.id) },+ decorators: [overviewDecorator({ ...summarizerScanner, sweep_throttle_factor: 12 }, summarizerStats)],+}++export const ClassifierOverview: StoryObj = {+ parameters: { pageUrl: urls.replayVision(classifierOverviewScanner.id) },+ decorators: [overviewDecorator(classifierOverviewScanner, classifierOverviewStats)],+}++export const ScorerOverview: StoryObj = {+ parameters: { pageUrl: urls.replayVision(scorerOverviewScanner.id) },+ decorators: [overviewDecorator(scorerOverviewScanner, scorerOverviewStats)],+}+// The scan-drought banner: current version 4 has no marker, and the sweep watermark sits past the// last config change, so the page warns that the filters matched nothing. No other story renders it.export const ScannerScanDrought: StoryObj = {@@ -780,26 +988,112 @@ export const ScannerObservations: StoryObj = {parameters: { pageUrl: `${urls.replayVision(summarizerScanner.id)}?tab=observations` },}-export const ScannerOnDemand: StoryObj = {- parameters: { pageUrl: `${urls.replayVision(summarizerScanner.id)}?tab=on-demand` },+// The shared list rows rebuilt for another scanner type: same sessions, people and statuses, with each+// succeeded row carrying that type's output. The failed row keeps its null result.+const observationsFor = (+ scannerResponse: ReplayScannerApi,+ outputs: Record<string, unknown>[]+): typeof observations => {+ let next = 0+ return {+ ...observations,+ results: observations.results.map((row) => ({+ ...row,+ scanner_id: scannerResponse.id,+ scanner_snapshot: {+ ...row.scanner_snapshot,+ name: scannerResponse.name,+ scanner_type: scannerResponse.scanner_type,+ scanner_config: scannerResponse.scanner_config,+ },+ scanner_result: row.scanner_result+ ? {+ ...row.scanner_result,+ model_output: { scanner_type: scannerResponse.scanner_type, ...outputs[next++ % outputs.length] },+ }+ : null,+ })) as ReplayObservationApi[],+ }+}++const observationsTabDecorator = (+ scannerResponse: ReplayScannerApi,+ stats: ObservationStatsApi,+ outputs: Record<string, unknown>[]+): ReturnType<typeof mswDecorator>[] => [+ overviewDecorator(scannerResponse, stats),+ mswDecorator({+ get: {+ '/api/projects/:team_id/vision/scanners/:id/observations/': observationsFor(scannerResponse, outputs),+ },+ }),+]++export const MonitorObservations: StoryObj = {+ parameters: { pageUrl: `${urls.replayVision(monitorOverviewScanner.id)}?tab=observations` },+ decorators: observationsTabDecorator(monitorOverviewScanner, monitorOverviewStats, [+ {+ verdict: 'yes',+ confidence: 0.91,+ reasoning: 'Retried the payment form twice and left the page before completing the order.',+ },+ {+ verdict: 'no',+ confidence: 0.84,+ reasoning: 'Moved through checkout in under a minute without errors or backtracking.',+ },+ {+ verdict: 'inconclusive',+ confidence: 0.4,+ reasoning: 'The recording ends on the shipping step, so the outcome is unclear.',+ },+ ]),+}++export const ClassifierObservations: StoryObj = {+ parameters: { pageUrl: `${urls.replayVision(classifierOverviewScanner.id)}?tab=observations` },+ decorators: observationsTabDecorator(classifierOverviewScanner, classifierOverviewStats, [+ {+ tags: ['rage-click', 'slow-load'],+ tags_freeform: ['coupon-confusion'],+ confidence: 0.88,+ reasoning: 'Clicked the disabled submit button repeatedly while the shipping rates loaded.',+ },+ {+ tags: ['dead-end'],+ tags_freeform: [],+ confidence: 0.79,+ reasoning: 'Opened the returns page from the footer and found no way back to the cart.',+ },+ { tags: [], tags_freeform: [], confidence: 0.72, reasoning: 'A short browse with no friction.' },+ ]),}-export const ScannerConfiguration: StoryObj = {- parameters: { pageUrl: `${urls.replayVision(summarizerScanner.id)}?tab=configuration` },+export const ScorerObservations: StoryObj = {+ parameters: { pageUrl: `${urls.replayVision(scorerOverviewScanner.id)}?tab=observations` },+ decorators: observationsTabDecorator(scorerOverviewScanner, scorerOverviewStats, [+ { score: 8.5, confidence: 0.86, reasoning: 'Compared plans, opened billing and invited a teammate.' },+ { score: 2, confidence: 0.8, reasoning: 'Bounced from the pricing page after a few seconds.' },+ { score: 5.5, confidence: 0.7, reasoning: 'Read the docs at length but never started a trial.' },+ ]),+}++export const ScannerOnDemand: StoryObj = {+ parameters: { pageUrl: `${urls.replayVision(summarizerScanner.id)}?tab=run` },}// Test arms of the model tier-naming experiment: models labeled by capability tier instead of-// provider names.-export const ScannerConfigurationTierNames: StoryObj = {+// provider names, as the Overview's Setup card shows them.+export const ScannerSetupTierNames: StoryObj = {parameters: {- pageUrl: `${urls.replayVision(summarizerScanner.id)}?tab=configuration`,+ pageUrl: urls.replayVision(summarizerScanner.id),featureFlags: { [FEATURE_FLAGS.REPLAY_VISION_MODEL_TIER_NAMING_EXPERIMENT]: 'test' },},}-export const ScannerConfigurationLiteStandardPro: StoryObj = {+export const ScannerSetupLiteStandardPro: StoryObj = {parameters: {- pageUrl: `${urls.replayVision(summarizerScanner.id)}?tab=configuration`,+ pageUrl: urls.replayVision(summarizerScanner.id),featureFlags: {[FEATURE_FLAGS.REPLAY_VISION_MODEL_TIER_NAMING_EXPERIMENT]: 'lite-standard-pro',},@@ -880,10 +1174,80 @@ const scoutReport = {title: 'Daily digest confused checkout: 2026-05-12',summary: '**TL;DR:** Checkout friction held steady; coupon box confusion dominated.',skill_name: digestScoutConfig.skill_name,+ filed_at: '2026-05-12T09:00:00Z',+ charts: [],created_at: '2026-05-12T09:03:00Z',updated_at: '2026-05-12T09:03:00Z',}+// A realistic multi-section digest in the Overview's side column, so its clamp and "Show full report" render.+export const MonitorOverviewWithScoutReport: StoryObj = {+ parameters: { pageUrl: urls.replayVision(monitorOverviewScanner.id) },+ decorators: [+ overviewDecorator(monitorOverviewScanner, monitorOverviewStats, activeSelfDrivingStats),+ mswDecorator({+ get: {+ '/api/projects/:team_id/signals/scout/configs/': [+ { ...digestScoutConfig, source_id: monitorOverviewScanner.id },+ ],+ '/api/projects/:team_id/vision/scanners/:scannerId/scout_reports/': [+ {+ ...scoutReport,+ summary: [+ '**TL;DR:** Yes verdicts rose from 22% to 27% this week, driven by the new shipping step.',+ '',+ '**What changed**',+ '',+ '[Yes verdicts by day](chart:yes-by-day)',+ '',+ '- 14 sessions stalled on the shipping options screen after the address form reset.',+ '- Coupon errors fell to 3 sessions, down from 11 before the validation fix.',+ '- Mobile Safari accounts for 9 of the 14 shipping stalls.',+ '',+ '**Worth a look**',+ '- The address form clears the postcode when the user goes back a step.',+ '- Two sessions retried payment four times before giving up.',+ '',+ '**Unchanged**',+ '- Card declines stayed flat at about 2% of checkouts.',+ ].join('\n'),+ charts: [+ {+ chart_id: 'yes-by-day',+ title: 'Yes verdicts by day',+ caption: 'The rise starts the day the new shipping step shipped.',+ query: {+ kind: 'InsightVizNode',+ source: {+ kind: 'TrendsQuery',+ series: [+ { kind: 'EventsNode', event: '$recording_observed', name: 'Yes verdicts' },+ ],+ dateRange: { date_from: '2026-04-29', date_to: '2026-05-12' },+ },+ },+ },+ {+ chart_id: 'stalls-by-browser',+ title: 'Shipping stalls by browser',+ query: {+ kind: 'InsightVizNode',+ source: {+ kind: 'TrendsQuery',+ series: [{ kind: 'EventsNode', event: '$recording_observed', name: 'Stalls' }],+ trendsFilter: { display: 'ActionsBarValue' },+ dateRange: { date_from: '2026-04-29', date_to: '2026-05-12' },+ },+ },+ },+ ],+ },+ ],+ },+ }),+ ],+}+export const ScannerScouts: StoryObj = {parameters: {pageUrl: `${urls.replayVision(summarizerScanner.id)}?tab=scouts`,diff --git a/products/replay_vision/frontend/replay_scanners/backfillsLogic.ts b/products/replay_vision/frontend/replay_scanners/backfillsLogic.tsindex 246e68f332ed..acf412f87680 100644--- a/products/replay_vision/frontend/replay_scanners/backfillsLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/backfillsLogic.ts@@ -1,7 +1,9 @@import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'import { ApiError } from 'lib/api-error'+import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { dateStringToDayJs } from 'lib/utils/dateFilters'import { teamLogic } from 'scenes/teamLogic'import {@@ -24,6 +26,14 @@ export function isBackfillActive(backfill: ReplayScannerBackfillApi): boolean {return backfill.status === 'running' || backfill.status === 'paused_quota'}+/** Converts a DateFilter token (`-30d`, an ISO date, or null) into an ISO instant for the API. */+function resolveWindowBound(value: string | null, fallback: dayjs.Dayjs): string {+ return ((value && dateStringToDayJs(value)) || fallback).toISOString()+}++// Re-scanning the last day after a prompt fix is the common case, so a new backfill starts there.+const DEFAULT_WINDOW_FROM = '-24h'+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface backfillsLogicValues {backfills: ReplayScannerBackfillApi[]@@ -62,8 +72,10 @@ export interface backfillsLogicActions {}requestEstimate: (windowStart: string,- windowEnd: string+ windowEnd: string,+ quiet?: boolean) => {+ quiet: booleanwindowEnd: stringwindowStart: string}@@ -109,7 +121,11 @@ export const backfillsLogic = kea<backfillsLogicType>([loadBackfills: (background = false) => ({ background }),loadBackfillsSuccess: (backfills: ReplayScannerBackfillApi[]) => ({ backfills }),loadBackfillsFailure: true,- requestEstimate: (windowStart: string, windowEnd: string) => ({ windowStart, windowEnd }),+ requestEstimate: (windowStart: string, windowEnd: string, quiet: boolean = false) => ({+ windowStart,+ windowEnd,+ quiet,+ }),requestEstimateSuccess: (estimate: BackfillEstimateResponseApi) => ({ estimate }),requestEstimateFailure: true,createBackfill: (windowStart: string, windowEnd: string) => ({ windowStart, windowEnd }),@@ -158,7 +174,7 @@ export const backfillsLogic = kea<backfillsLogicType>([createBackfillDone: () => false,},],- windowDateFrom: [null as string | null, { setWindowRange: (_, { dateFrom }) => dateFrom }],+ windowDateFrom: [DEFAULT_WINDOW_FROM as string | null, { setWindowRange: (_, { dateFrom }) => dateFrom }],windowDateTo: [null as string | null, { setWindowRange: (_, { dateTo }) => dateTo }],transitioningIds: [[] as string[],@@ -203,7 +219,22 @@ export const backfillsLogic = kea<backfillsLogicType>([lemonToast.error('Couldn’t load backfills. Refresh the page to try again.')}},+ setWindowRange: ({ dateFrom, dateTo }) => {+ actions.requestEstimate(+ resolveWindowBound(dateFrom, dayjs().subtract(30, 'day')),+ resolveWindowBound(dateTo, dayjs())+ )+ },loadBackfillsSuccess: () => {+ // The default window's estimate waits for the list, so it is skipped while a backfill already runs.+ if (!cache.defaultEstimateRequested && !values.backfills.some(isBackfillActive)) {+ cache.defaultEstimateRequested = true+ actions.requestEstimate(+ resolveWindowBound(values.windowDateFrom, dayjs().subtract(30, 'day')),+ resolveWindowBound(values.windowDateTo, dayjs()),+ true+ )+ }if (values.backfills.some((b) => b.status === 'running')) {cache.disposables.add(() => {const timerId = window.setTimeout(() => actions.loadBackfills(true), ACTIVE_POLL_INTERVAL_MS)@@ -213,7 +244,7 @@ export const backfillsLogic = kea<backfillsLogicType>([cache.disposables.dispose('backfillPoll')}},- requestEstimate: async ({ windowStart, windowEnd }, breakpoint) => {+ requestEstimate: async ({ windowStart, windowEnd, quiet }, breakpoint) => {const teamId = teamLogic.values.currentTeamIdif (!teamId) {return@@ -229,7 +260,9 @@ export const backfillsLogic = kea<backfillsLogicType>([} catch (error: any) {breakpoint()actions.requestEstimateFailure()- lemonToast.error(apiErrorMessage(error))+ if (!quiet) {+ lemonToast.error(apiErrorMessage(error))+ }}},createBackfill: async ({ windowStart, windowEnd }) => {diff --git a/products/replay_vision/frontend/replay_scanners/components/BackfillDateRange.tsx b/products/replay_vision/frontend/replay_scanners/components/BackfillDateRange.tsxnew file mode 100644index 000000000000..89b24095817f--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/BackfillDateRange.tsx@@ -0,0 +1,82 @@+import { useActions, useValues } from 'kea'++import { LemonButton } from '@posthog/lemon-ui'++import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'++import { DateMappingOption } from '~/types'++import { backfillsLogic, isBackfillActive } from '../backfillsLogic'+import { BackfillCostEstimate } from './BackfillCostEstimate'+import { BackfillHistoryTable } from './BackfillHistoryTable'++// Hour-scale presets matter as much as day-scale ones: a common case is re-scanning the last couple+// of hours after fixing a prompt, not re-scanning a month.+const BACKFILL_DATE_OPTIONS: DateMappingOption[] = [+ { key: CUSTOM_OPTION_KEY, values: [] },+ { key: 'Last 3 hours', values: ['-3h'] },+ { key: 'Last 6 hours', values: ['-6h'] },+ { key: 'Last 24 hours', values: ['-24h'] },+ { key: 'Last 7 days', values: ['-7d'] },+ { key: 'Last 30 days', values: ['-30d'] },+ { key: 'Last 90 days', values: ['-90d'] },+]++export function BackfillDateRange({ scannerId }: { scannerId: string }): JSX.Element {+ const logic = backfillsLogic({ scannerId })+ const { backfills, estimate, estimateLoading, creatingBackfill, windowDateFrom, windowDateTo } = useValues(logic)+ const { createBackfill, setWindowRange } = useActions(logic)++ const activeBackfill = backfills.find(isBackfillActive)++ const startDisabledReason = activeBackfill+ ? 'This scanner already has an active backfill'+ : !estimate+ ? 'Pick a time range to see the cost first'+ : estimate.total_sessions === 0+ ? 'No eligible sessions in this time range'+ : undefined++ return (+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-5">+ <p className="text-muted text-sm m-0">+ Scan every recording in a date range that matches this scanner's filters, including ones from before+ you created it. Recordings it already scanned are skipped, so you aren't charged twice. It uses the+ scanner's settings as they are now, so editing the scanner later won't change a backfill that's+ already running.+ </p>+ <div className="flex items-center gap-2 flex-wrap">+ <DateFilter+ size="small"+ dateFrom={windowDateFrom}+ dateTo={windowDateTo}+ dateOptions={BACKFILL_DATE_OPTIONS}+ onChange={(dateFrom, dateTo) => setWindowRange(dateFrom, dateTo)}+ allowTimePrecision+ allowFixedRangeWithTime+ allowedRollingDateOptions={['hours', 'days', 'weeks', 'months']}+ data-attr="vision-backfill-date-filter"+ />+ <LemonButton+ type="primary"+ size="small"+ onClick={() => estimate && createBackfill(estimate.window_start, estimate.window_end)}+ loading={creatingBackfill}+ disabledReason={startDisabledReason}+ data-attr="vision-backfill-start"+ >+ Start backfill+ </LemonButton>+ </div>+ <BackfillCostEstimate estimate={estimate} loading={estimateLoading} />+ </div>++ <div className="flex flex-col gap-2">+ <h3 className="text-sm font-medium m-0">Backfill history</h3>+ <BackfillHistoryTable scannerId={scannerId} />+ </div>+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/BackfillHistoryTable.tsxsimilarity index 61%rename from products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsxrename to products/replay_vision/frontend/replay_scanners/components/BackfillHistoryTable.tsxindex 1a4b2709e12c..264c27e48aff 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/BackfillHistoryTable.tsx@@ -4,18 +4,13 @@ import { combineUrl } from 'kea-router'import { LemonButton, LemonTable, LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'-import { DateFilter } from 'lib/components/DateFilter/DateFilter'-import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'import { TZLabel } from 'lib/components/TZLabel'-import { dayjs } from 'lib/dayjs'import { More } from 'lib/lemon-ui/LemonButton/More'+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'-import { dateStringToDayJs } from 'lib/utils/dateFilters'import { urls } from 'scenes/urls'-import { DateMappingOption } from '~/types'-import { VisionDocsLink } from '../../components/DocsLink'import type { BackfillStatusEnumApi, ReplayScannerBackfillApi } from '../../generated/api.schemas'import { formatCreditCount, formatCredits } from '../../utils/credits'@@ -23,19 +18,6 @@ import { backfillsLogic, isBackfillActive } from '../backfillsLogic'import { replayScannerLogic } from '../replayScannerLogic'import { ReplayScannerTab } from '../replayScannerSceneLogic'import type { ScannerCreatedBy } from '../types'-import { BackfillCostEstimate } from './BackfillCostEstimate'--// Hour-scale presets matter as much as day-scale ones: a common case is re-scanning the last couple-// of hours after fixing a prompt, not re-scanning a month.-const BACKFILL_DATE_OPTIONS: DateMappingOption[] = [- { key: CUSTOM_OPTION_KEY, values: [] },- { key: 'Last 3 hours', values: ['-3h'] },- { key: 'Last 6 hours', values: ['-6h'] },- { key: 'Last 24 hours', values: ['-24h'] },- { key: 'Last 7 days', values: ['-7d'] },- { key: 'Last 30 days', values: ['-30d'] },- { key: 'Last 90 days', values: ['-90d'] },-]const BACKFILL_STATUS_TAG: Record<BackfillStatusEnumApi, { label: string; type: LemonTagType }> = {running: { label: 'Running', type: 'success' },@@ -47,28 +29,13 @@ const BACKFILL_STATUS_TAG: Record<BackfillStatusEnumApi, { label: string; type:/** Raw instant, so two window bounds can be compared at a glance. */const WINDOW_TIME_FORMAT = { formatDate: 'MMM D, YYYY', formatTime: 'HH:mm' }-/** Convert a DateFilter token (`-30d`, an ISO date, or null) into an ISO instant for the API. */-export function resolveWindowBound(value: string | null, fallback: dayjs.Dayjs): string {- return ((value && dateStringToDayJs(value)) || fallback).toISOString()-}--export function ScannerBackfillsTab({ scannerId }: { scannerId: string }): JSX.Element {+/** Every backfill this scanner has run, with its progress, spend, and pause or cancel controls. */+export function BackfillHistoryTable({ scannerId }: { scannerId: string }): JSX.Element {const logic = backfillsLogic({ scannerId })- const {- backfills,- backfillsLoading,- estimate,- estimateLoading,- creatingBackfill,- transitioningIds,- windowDateFrom,- windowDateTo,- } = useValues(logic)- const { requestEstimate, createBackfill, cancelBackfill, resumeBackfill, setWindowRange } = useActions(logic)+ const { backfills, backfillsLoading, transitioningIds } = useValues(logic)+ const { cancelBackfill, resumeBackfill } = useActions(logic)const { scanner } = useValues(replayScannerLogic({ id: scannerId }))- const activeBackfill = backfills.find(isBackfillActive)-// A capped or disabled scanner holds its running backfill without changing the row's status, so// the row itself has to say why nothing is progressing.const runningHold = scanner?.limit_reached@@ -84,19 +51,6 @@ export function ScannerBackfillsTab({ scannerId }: { scannerId: string }): JSX.E}: null- const estimateWindow = (dateFrom: string | null, dateTo: string | null): void => {- setWindowRange(dateFrom, dateTo)- requestEstimate(resolveWindowBound(dateFrom, dayjs().subtract(30, 'day')), resolveWindowBound(dateTo, dayjs()))- }-- const startDisabledReason = activeBackfill- ? 'This scanner already has an active backfill'- : !estimate- ? 'Pick a time range to see the cost first'- : estimate.total_sessions === 0- ? 'No eligible sessions in this time range'- : undefined-const columns: LemonTableColumns<ReplayScannerBackfillApi> = [{title: 'ID',@@ -151,16 +105,20 @@ export function ScannerBackfillsTab({ scannerId }: { scannerId: string }): JSX.E// Both count as done: dispatched by this backfill, or taken over by the sweep while it ran.const handled = backfill.dispatched_count + backfill.skipped_countconst nothingToDo = backfill.status === 'completed' && handled === 0- const progress = nothingToDo- ? 'Nothing left to scan'- : `${handled.toLocaleString('en-US')} of ${backfill.total_count.toLocaleString(- 'en-US'- )} scanned${settled > 0 ? ` (${settled.toLocaleString('en-US')} settled)` : ''}`+ if (nothingToDo) {+ return <span className="text-muted">Nothing left to scan</span>+ }+ const percent = backfill.total_count > 0 ? Math.min(100, (handled / backfill.total_count) * 100) : 0return (<Tooltip- title={`${backfill.succeeded_count} succeeded, ${backfill.failed_count} failed, ${backfill.ineligible_count} ineligible, ${backfill.in_flight_count} in flight${skippedNote}`}+ title={`${settled.toLocaleString('en-US')} settled: ${backfill.succeeded_count} succeeded, ${backfill.failed_count} failed, ${backfill.ineligible_count} ineligible. ${backfill.in_flight_count} in flight${skippedNote}.`}>- <span className={nothingToDo ? 'text-muted' : undefined}>{progress}</span>+ <div className="flex items-center gap-2 min-w-40">+ <LemonProgress percent={percent} className="flex-1" />+ <span className="text-xs text-muted tabular-nums whitespace-nowrap">+ {handled.toLocaleString('en-US')} / {backfill.total_count.toLocaleString('en-US')}+ </span>+ </div></Tooltip>)},@@ -242,58 +200,20 @@ export function ScannerBackfillsTab({ scannerId }: { scannerId: string }): JSX.E]return (- <div className="flex flex-col gap-4">- <div className="rounded border p-4 flex flex-col gap-3">- <div>- <h3 className="mb-1">Scan historical recordings</h3>- <p className="text-muted mb-0">- Run this scanner over older recordings, including ones from before you created it. The backfill- skips recordings it has already scanned, so you're not billed twice. It uses the scanner's- settings as they are now, so editing the scanner later won't change a backfill that's already- running.- </p>- </div>- <div className="flex items-center gap-2 flex-wrap">- <DateFilter- size="small"- dateFrom={windowDateFrom}- dateTo={windowDateTo}- dateOptions={BACKFILL_DATE_OPTIONS}- onChange={(dateFrom, dateTo) => estimateWindow(dateFrom, dateTo)}- allowTimePrecision- allowFixedRangeWithTime- allowedRollingDateOptions={['hours', 'days', 'weeks', 'months']}- data-attr="vision-backfill-date-filter"- />- <LemonButton- type="primary"- size="small"- onClick={() => estimate && createBackfill(estimate.window_start, estimate.window_end)}- loading={creatingBackfill}- disabledReason={startDisabledReason}- data-attr="vision-backfill-start"- >- Start backfill- </LemonButton>- </div>- <BackfillCostEstimate estimate={estimate} loading={estimateLoading} />- </div>-- <LemonTable- dataSource={backfills}- columns={columns}- loading={backfillsLoading}- rowKey="id"- emptyState={- <>- No backfills yet. Pick a time range above to scan historical recordings.{' '}- <VisionDocsLink page="running-scanners" dataAttr="vision-empty-docs-link-backfills">- Learn how backfills work- </VisionDocsLink>- </>- }- data-attr="vision-backfills-table"- />- </div>+ <LemonTable+ dataSource={backfills}+ columns={columns}+ loading={backfillsLoading}+ rowKey="id"+ emptyState={+ <>+ No backfills yet. Pick a time range above to scan historical recordings.{' '}+ <VisionDocsLink page="running-scanners" dataAttr="vision-empty-docs-link-backfills">+ Learn how backfills work+ </VisionDocsLink>+ </>+ }+ data-attr="vision-backfills-table"+ />)}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx b/products/replay_vision/frontend/replay_scanners/components/BatchScanRecordings.tsxsimilarity index 76%rename from products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsxrename to products/replay_vision/frontend/replay_scanners/components/BatchScanRecordings.tsxindex 9d03cd075c72..9196530bab6b 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/BatchScanRecordings.tsx@@ -1,8 +1,8 @@import { BindLogic, useActions, useValues } from 'kea'-import { useEffect, useRef, useState } from 'react'+import { useEffect, useState } from 'react'import { IconEye, IconPlay } from '@posthog/icons'-import { LemonButton, LemonInput, LemonTable, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'+import { LemonButton, LemonTable, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'@@ -23,69 +23,13 @@ import { PersonDisplay } from 'products/persons/frontend/components/PersonDisplaimport { ObservationStatusTag } from '../../components/ObservationCard'import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'+import { formatCreditCount } from '../../utils/credits'import { recordingScanBlock } from '../../utils/scanEligibility'import { replayScannerLogic } from '../replayScannerLogic'import { IN_PROGRESS_STATUSES, scannerRunTabLogic } from '../scannerRunTabLogic'-/** Manual entry: scan one session by pasting its recording ID. */-function ScanBySessionId({ scannerId }: { scannerId: string }): JSX.Element {- const { scanner, triggeringOnDemandObservation, onDemandObservationSuccessCount } = useValues(- replayScannerLogic({ id: scannerId })- )- const { triggerOnDemandObservation } = useActions(replayScannerLogic({ id: scannerId }))- const [sessionId, setSessionId] = useState('')- const lastSeenSuccessCount = useRef(onDemandObservationSuccessCount)- const editDisabledReason = getReplayVisionEditDisabledReason(scanner?.user_access_level)-- useEffect(() => {- if (onDemandObservationSuccessCount > lastSeenSuccessCount.current) {- lastSeenSuccessCount.current = onDemandObservationSuccessCount- setSessionId('')- }- }, [onDemandObservationSuccessCount])-- const trimmed = sessionId.trim()- const submit = (): void => {- if (!trimmed || triggeringOnDemandObservation) {- return- }- triggerOnDemandObservation(trimmed)- }-- return (- <div className="border rounded p-4 bg-surface-primary space-y-3">- <div>- <h3 className="text-sm font-medium mb-1">Scan a session by ID</h3>- <p className="text-muted text-sm m-0">- Run this scanner against a specific session recording right now, without waiting for the schedule.- Paste the recording's session ID below.- </p>- </div>- <div className="flex flex-col gap-2 sm:flex-row sm:items-center">- <LemonInput- value={sessionId}- onChange={setSessionId}- onPressEnter={submit}- placeholder="Session ID"- fullWidth- data-attr="vision-scanner-scan-session-input"- />- <LemonButton- type="primary"- icon={<IconPlay />}- onClick={submit}- loading={triggeringOnDemandObservation}- disabledReason={editDisabledReason ?? (!trimmed ? 'Paste a session ID first' : undefined)}- data-attr="vision-scanner-scan-session-submit"- >- Scan recording- </LemonButton>- </div>- </div>- )-}-function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {+ const [selectionBarTarget, setSelectionBarTarget] = useState<HTMLElement | null>(null)const { filters, totalFiltersCount, sessionRecordings, sessionRecordingsResponseLoading, hasNext } =useValues(sessionRecordingsPlaylistLogic)const { setFilters, resetFilters, maybeLoadSessionRecordings } = useActions(sessionRecordingsPlaylistLogic)@@ -240,6 +184,12 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {compactActions/></div>+ {/* A fixed-height row right above the table: the selection bar renders into it, so selecting rows+ moves nothing, and the hint keeps it from reading as empty space before anything is selected. */}+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 min-h-9">+ <span className="text-muted text-sm">Select recordings to scan them together.</span>+ <div ref={setSelectionBarTarget} />+ </div><LemonTablecolumns={columns}dataSource={sessionRecordings}@@ -249,6 +199,7 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {data-attr="vision-run-recordings-table"bulkSelection={{noun: ['recording', 'recordings'],+ barPortalTarget: selectionBarTarget,// Only not-yet-scanned rows are selectable — a scanned or in-flight session has nothing// to (re)scan, matching the per-row button that swaps to "View observation". Rows the// gate would refuse are out too, so a bulk run can't spend scans on them.@@ -273,6 +224,8 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {data-attr="vision-run-bulk-scan">Scan {selectedCount} selected+ {scanner?.credits_per_observation != null &&+ ` · ${formatCreditCount(selectedCount * scanner.credits_per_observation)}`}</LemonButton>),}}@@ -293,8 +246,8 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {)}-/** Browse and filter recordings, then fire this scanner against any of them. */-function ScanFromRecordings({ scannerId }: { scannerId: string }): JSX.Element {+/** Browse and filter recordings, then scan the ones you select. */+export function BatchScanRecordings({ scannerId }: { scannerId: string }): JSX.Element {// Seed the picker from the scanner's saved triggers so it opens scoped to the sessions this scanner cares about.// originalScanner is null until loaded, and the playlist logic reads filters only at mount, so gate on it.const { originalScanner } = useValues(replayScannerLogic({ id: scannerId }))@@ -310,15 +263,11 @@ function ScanFromRecordings({ scannerId }: { scannerId: string }): JSX.Element {: nullreturn (- <div className="border rounded p-4 bg-surface-primary space-y-3">- <div>- <h3 className="text-sm font-medium mb-1">Pick from your recordings</h3>- <p className="text-muted text-sm m-0">- Filter your session recordings and run this scanner against any of them. Filters start from this- scanner's triggers, so adjust them to backfill or scan un-sampled sessions. Each scan produces one- observation.- </p>- </div>+ <div className="flex flex-col gap-5">+ <p className="text-muted text-sm m-0">+ Filter your recordings, select the ones you want, and scan them together. Each scan produces one+ observation.+ </p>{logicProps ? (<BindLogic logic={sessionRecordingsPlaylistLogic} props={logicProps}><RecordingsList scannerId={scannerId} />@@ -331,23 +280,3 @@ function ScanFromRecordings({ scannerId }: { scannerId: string }): JSX.Element {</div>)}--function OrDivider(): JSX.Element {- return (- <div className="flex items-center justify-center gap-4 text-muted text-base font-semibold uppercase tracking-wide">- <div className="w-24 border-t-2" />- or- <div className="w-24 border-t-2" />- </div>- )-}--export function ScannerRunTab({ scannerId }: { scannerId: string }): JSX.Element {- return (- <div className="flex flex-col gap-8">- <ScanBySessionId scannerId={scannerId} />- <OrDivider />- <ScanFromRecordings scannerId={scannerId} />- </div>- )-}diff --git a/products/replay_vision/frontend/replay_scanners/components/ClippedPreview.tsx b/products/replay_vision/frontend/replay_scanners/components/ClippedPreview.tsxnew file mode 100644index 000000000000..87dfbe5fcdb7--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ClippedPreview.tsx@@ -0,0 +1,45 @@+import { Link } from '@posthog/lemon-ui'++import { useResizeObserver } from 'lib/hooks/useResizeObserver'++// Tailwind needs literal class names, so each clip height pairs its class with the pixel value it measures against.+const CLIPS = {+ short: { className: 'max-h-20', px: 80 },+ tall: { className: 'max-h-60', px: 240 },+} as const++export function ClippedPreview({+ clip,+ buttonLabel,+ children,+ onOpenFull,+ dataAttr,+}: {+ clip: keyof typeof CLIPS+ buttonLabel: string+ children: React.ReactNode+ onOpenFull: () => void+ dataAttr: string+}): JSX.Element {+ const { ref, height } = useResizeObserver()+ const { className, px } = CLIPS[clip]+ const overflows = (height ?? 0) > px++ return (+ <div className="flex flex-col gap-1">+ <div+ className={`${className} overflow-hidden ${+ overflows ? '[mask-image:linear-gradient(to_bottom,black_60%,transparent)]' : ''+ }`}+ >+ {/* Measured unclipped (the parent's overflow doesn't shrink it), so the button shows only when there's more. */}+ <div ref={ref}>{children}</div>+ </div>+ {overflows && (+ <Link className="self-start text-xs" onClick={onOpenFull} data-attr={dataAttr}>+ {buttonLabel}+ </Link>+ )}+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ObservationRowResult.tsx b/products/replay_vision/frontend/replay_scanners/components/ObservationRowResult.tsxnew file mode 100644index 000000000000..99b868a069a6--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ObservationRowResult.tsx@@ -0,0 +1,12 @@+import { ObservationResultSummary } from '../../components/ObservationCard'+import type { ReplayObservationApi } from '../../generated/api.schemas'+import { unsuccessfulScanReason } from '../types'++export function ObservationRowResult({ observation }: { observation: ReplayObservationApi }): JSX.Element {+ const reason = unsuccessfulScanReason(observation.status, observation.error_reason)+ return reason ? (+ <span className="text-sm text-secondary line-clamp-2">{reason}</span>+ ) : (+ <ObservationResultSummary observation={observation} />+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScanSingleRecording.tsx b/products/replay_vision/frontend/replay_scanners/components/ScanSingleRecording.tsxnew file mode 100644index 000000000000..997936aec17f--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScanSingleRecording.tsx@@ -0,0 +1,73 @@+import { useActions, useValues } from 'kea'+import { useEffect, useRef, useState } from 'react'++import { IconPlay } from '@posthog/icons'+import { LemonButton, LemonInput } from '@posthog/lemon-ui'++import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'+import { formatCreditCount } from '../../utils/credits'+import { sessionIdFromInput } from '../../utils/sessionIdInput'+import { replayScannerLogic } from '../replayScannerLogic'++export function ScanSingleRecording({ scannerId }: { scannerId: string }): JSX.Element {+ const { scanner, triggeringOnDemandObservation, onDemandObservationSuccessCount } = useValues(+ replayScannerLogic({ id: scannerId })+ )+ const { triggerOnDemandObservation } = useActions(replayScannerLogic({ id: scannerId }))+ const [sessionId, setSessionId] = useState('')+ const lastSeenSuccessCount = useRef(onDemandObservationSuccessCount)+ const editDisabledReason = getReplayVisionEditDisabledReason(scanner?.user_access_level)++ useEffect(() => {+ if (onDemandObservationSuccessCount > lastSeenSuccessCount.current) {+ lastSeenSuccessCount.current = onDemandObservationSuccessCount+ setSessionId('')+ }+ }, [onDemandObservationSuccessCount])++ const parsedId = sessionIdFromInput(sessionId)+ const submit = (): void => {+ if (!parsedId || triggeringOnDemandObservation) {+ return+ }+ triggerOnDemandObservation(parsedId)+ }+ const creditsPerScan = scanner?.credits_per_observation++ return (+ <div className="flex flex-col gap-5">+ <p className="text-muted text-sm m-0">+ Run this scanner on one recording right now, without waiting for the schedule. Paste its session ID or a+ link to the recording.+ {creditsPerScan != null && ` Each scan uses ${formatCreditCount(creditsPerScan)}.`}+ </p>+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">+ <LemonInput+ value={sessionId}+ onChange={setSessionId}+ onPressEnter={submit}+ placeholder="Session ID or recording link"+ fullWidth+ data-attr="vision-scanner-scan-session-input"+ />+ <LemonButton+ type="primary"+ icon={<IconPlay />}+ onClick={submit}+ loading={triggeringOnDemandObservation}+ disabledReason={+ editDisabledReason ??+ (!sessionId.trim()+ ? 'Paste a session ID or a recording link first'+ : !parsedId+ ? "This link doesn't point at a recording"+ : undefined)+ }+ data-attr="vision-scanner-scan-session-submit"+ >+ Scan recording+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerCalibrationTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerCalibrationTab.tsxindex c024ef4d1f4b..b5932e176238 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerCalibrationTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerCalibrationTab.tsx@@ -42,7 +42,6 @@ import { formatCreditCount, formatCreditsRange } from '../../utils/credits'import { buildChartDayFormatter, fillLabelDays, versionAccuracyStrip } from '../../utils/labelStats'import { readConfidence } from '../../utils/observation'import { replayScannerLogic } from '../replayScannerLogic'-import { ReplayScannerTab, replayScannerSceneLogic } from '../replayScannerSceneLogic'import {LABEL_CHART_DAYS,CALIBRATION_PAGE_SIZE,@@ -620,7 +619,6 @@ const CHART_MODE_OPTIONS: { value: ChartMode; label: string; tooltip: string; 'dfunction RatingsOverTimePanel({ scannerId }: { scannerId: string }): JSX.Element {const { labelStats, labelStatsLoading } = useValues(scannerCalibrationLogic({ scannerId }))const { scanner } = useValues(replayScannerLogic({ id: scannerId }))- const { setActiveTab } = useActions(replayScannerSceneLogic)const { isDarkModeOn } = useValues(themeLogic)// buildTheme snapshots the current CSS vars, so rebuild when the app theme flips.// eslint-disable-next-line react-hooks/exhaustive-deps@@ -740,14 +738,12 @@ function RatingsOverTimePanel({ scannerId }: { scannerId: string }): JSX.Element: badge.prompt}</div>)}- <div className="text-muted">Click to view all prompt versions</div></div>}><div- className="absolute top-0 -translate-x-1/2 inline-flex cursor-pointer items-center justify-center rounded border bg-surface-secondary px-1.5 py-0.5 text-[10px] font-mono leading-none text-muted hover:text-default"+ className="absolute top-0 -translate-x-1/2 inline-flex items-center justify-center rounded border bg-surface-secondary px-1.5 py-0.5 text-[10px] font-mono leading-none text-muted"style={{ left: badge.x }}- onClick={() => setActiveTab(ReplayScannerTab.Configuration)}data-attr="vision-calibration-version-badge">v{badge.version}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsxdeleted file mode 100644index 287eafec60a4..000000000000--- a/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx+++ /dev/null@@ -1,583 +0,0 @@-import { useActions, useValues } from 'kea'-import { Fragment } from 'react'--import {- IconBolt,- IconClock,- IconGraph,- IconInfo,- IconPencil,- IconPeople,- IconThumbsDownFilled,- IconThumbsUpFilled,-} from '@posthog/icons'-import { LemonCard, LemonCollapse, LemonSwitch, LemonTag } from '@posthog/lemon-ui'--import { PropertyFilterButton } from 'lib/components/PropertyFilters/components/PropertyFilterButton'-import { TZLabel } from 'lib/components/TZLabel'-import { UniversalFilterButton } from 'lib/components/UniversalFilters/UniversalFilterButton'-import { isEntityFilter } from 'lib/components/UniversalFilters/utils'-import { FEATURE_FLAGS } from 'lib/constants'-import { dayjs } from 'lib/dayjs'-import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { themeLogic } from 'lib/logic/themeLogic'-import { humanFriendlyDurationFilter } from 'scenes/session-recordings/filters/DurationFilter'-import {- deriveOperand,- recordingsQueryToUniversalFilters,-} from 'scenes/session-recordings/filters/recordingsQueryConversions'-import { filtersFromUniversalFilterGroups } from 'scenes/session-recordings/utils'--import { RecordingsQuery } from '~/queries/schema/schema-general'-import { FilterLogicalOperator, UniversalFilterValue } from '~/types'--import { BooleanTag } from '../../components/BooleanTag'-import { CardHeader } from '../../components/CardHeader'-import { LabeledRow } from '../../components/LabeledRow'-import { CreditPriceNote } from '../../components/PricingLink'-import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'-import { visionQuotaLogic } from '../../logics/visionQuotaLogic'-import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'-import { formatCreditsMaybeUsd } from '../../utils/credits'-import { replayScannerLogic } from '../replayScannerLogic'-import {- ReplayScanner,- SAMPLING_MODE_OPTIONS,- ScannerType,- getModelOptions,- modelLabel,- modelNamingVariant,- scannerTypeLabel,-} from '../types'-import { FieldCurrentValue } from './ConfigChangeCards'-import { fieldEditor } from './configChanges'-import { PromptDiffButton } from './PromptDiff'-import {- VersionChanges,- VersionConfig,- versionChangesByVersion,- versionConfigFromMarker,- versionConfigFromScanner,-} from './versionChanges'--const SUMMARY_LENGTHS = [- { value: 'short', label: 'Short' },- { value: 'medium', label: 'Medium' },- { value: 'long', label: 'Long' },-] as const--const SCANNER_TYPES: ScannerType[] = ['monitor', 'classifier', 'scorer', 'summarizer']--/** The recording filters a query selects on: events, actions, properties, console logs, duration, test accounts. */-function RecordingFilters({ query }: { query: unknown }): JSX.Element {- // Read every filter dimension, not just top-level properties.- const universal = recordingsQueryToUniversalFilters((query ?? null) as RecordingsQuery | null)- const filters = filtersFromUniversalFilterGroups(universal)- if (filters.length === 0 && universal.duration.length === 0 && !universal.filter_test_accounts) {- return <span className="text-muted">No filters</span>- }- const matchWord = deriveOperand(universal.filter_group) === FilterLogicalOperator.Or ? 'any' : 'all'- return (- <div className="flex flex-col gap-2">- {filters.length > 0 && (- <div className="flex flex-wrap items-center gap-1.5">- {filters.length > 1 && <span className="text-xs">Match {matchWord} of</span>}- {filters.map((filter, i) => (- <ReadonlyFilter key={i} filter={filter} />- ))}- </div>- )}- {(universal.duration.length > 0 || universal.filter_test_accounts) && (- <div className="flex flex-wrap items-center gap-1.5">- {universal.duration.map((duration, i) => (- <LemonTag key={i} type="default" icon={<IconClock />}>- {humanFriendlyDurationFilter(duration, duration.key)}- </LemonTag>- ))}- {universal.filter_test_accounts && (- <LemonTag type="default" icon={<IconPeople />}>- No internal/test users- </LemonTag>- )}- </div>- )}- </div>- )-}--function Multiline({ value }: { value: string | null | undefined }): JSX.Element {- return <div className="whitespace-pre-wrap text-sm">{value || <span className="text-muted">—</span>}</div>-}--/** Renders an option set as tags with the chosen value emphasized and the rest greyed/struck through. */-function OptionTags({- options,- selected,-}: {- options: readonly { value: string; label: string }[]- selected: string | null | undefined-}): JSX.Element {- return (- <div className="flex flex-wrap gap-1">- {options.map((option) => {- const isSelected = selected === option.value- return (- <LemonTag- key={option.value}- size="medium"- type={isSelected ? 'option' : 'default'}- className={isSelected ? undefined : 'opacity-50 line-through'}- >- {option.label}- </LemonTag>- )- })}- </div>- )-}--/** One recording filter, read-only. An event or action filter carries its own property filters, which the- * editable UI keeps behind a popover — there's nothing to open here, so show them alongside the event. */-function ReadonlyFilter({ filter }: { filter: UniversalFilterValue }): JSX.Element {- const properties = isEntityFilter(filter) ? (filter.properties ?? []) : []- return (- <div className="flex flex-wrap items-center gap-1.5">- <UniversalFilterButton filter={filter} />- {properties.length > 0 && (- <>- <span className="text-xs">where</span>- {properties.map((property, i) => (- <PropertyFilterButton key={i} item={property} compact />- ))}- </>- )}- </div>- )-}--function BehaviorCardContent({ scanner }: { scanner: ReplayScanner }): JSX.Element {- return (- <>- <LabeledRow label="Prompt">- {scanner.scanner_config.prompt ? (- <div className="whitespace-pre-wrap text-sm bg-surface-secondary border rounded p-2">- {scanner.scanner_config.prompt}- </div>- ) : (- <span className="text-muted">—</span>- )}- </LabeledRow>- {scanner.scanner_type === 'summarizer' && (- <LabeledRow label="Summary length">- <OptionTags options={SUMMARY_LENGTHS} selected={scanner.scanner_config.length} />- </LabeledRow>- )}- {scanner.scanner_type === 'monitor' && (- <LabeledRow label="Allow inconclusive verdicts">- <BooleanTag value={!!scanner.scanner_config.allow_inconclusive} />- </LabeledRow>- )}- {scanner.scanner_type === 'classifier' && (- <>- <LabeledRow label="Categories">- {scanner.scanner_config.tags.length ? (- <div className="flex flex-wrap gap-1">- {scanner.scanner_config.tags.map((tag) => (- <LemonTag key={tag} type="option">- {tag}- </LemonTag>- ))}- </div>- ) : (- <span className="text-muted">—</span>- )}- </LabeledRow>- <LabeledRow label="Multiple categories per session">- <BooleanTag value={!!scanner.scanner_config.multi_label} />- </LabeledRow>- <LabeledRow label="Freeform categories">- <BooleanTag value={!!scanner.scanner_config.allow_freeform_tags} />- </LabeledRow>- </>- )}- {scanner.scanner_type === 'scorer' && (- <LabeledRow label="Scale">- {scanner.scanner_config.scale.min} – {scanner.scanner_config.scale.max}- {scanner.scanner_config.scale.label ? ` (${scanner.scanner_config.scale.label})` : ''}- </LabeledRow>- )}- <LabeledRow label="Emit signals">- <BooleanTag value={scanner.emits_signals} />- </LabeledRow>- </>- )-}--/** What a version changed, field by field. Versions bump on any tracked change, so without this a bump the- * reader can't spot (a flag, the model, sampling) reads as a no-op. */-function VersionChangeSummary({- changes,- version,- isDarkModeOn,-}: {- changes: VersionChanges- version: number- isDarkModeOn: boolean-}): JSX.Element {- const comparedWith = changes.previous.version- return (- <div className="rounded bg-surface-secondary px-3 py-2 space-y-1">- <div className="text-xs font-medium">- {changes.changes.length > 0- ? `Changed since v${comparedWith}`- : `Nothing recorded for v${version} differs from v${comparedWith}`}- </div>- {changes.changes.map((change) => (- <div key={change.field} className="flex flex-wrap items-baseline gap-x-2 text-xs">- <span className="text-muted">{change.label}</span>- {change.kind === 'value' ? (- <span>- <span className="text-muted line-through">{change.before}</span>- <span className="text-muted mx-1">→</span>- {change.after}- </span>- ) : (- <span className="flex items-center gap-2">- <span>edited</span>- {change.kind === 'prompt' && (- <PromptDiffButton- original={change.before}- modified={change.after}- originalTitle={`v${comparedWith}`}- modifiedTitle={`v${version}`}- isDarkModeOn={isDarkModeOn}- />- )}- </span>- )}- </div>- ))}- {changes.notRecorded.length > 0 && (- <div className="text-xs text-muted">- {changes.notRecorded.join(', ')} weren't recorded for these versions, so a change there isn't shown.- </div>- )}- </div>- )-}--/** Every version-tracked field the version ran with, so the reader sees the whole config, not only the diff. */-function VersionFields({ config, changed }: { config: VersionConfig; changed: Set<string> }): JSX.Element {- // A field the run snapshots never carried must say so, not render a default that reads as a real value.- const recorded = (value: unknown, render: () => JSX.Element): JSX.Element =>- value == null ? <span className="text-muted">Not recorded</span> : render()- const rows: { field: string; label: string; value: JSX.Element }[] = [- {- field: 'prompt',- label: 'Prompt',- value: (- <div className="whitespace-pre-wrap">- {String(config.scannerConfig.prompt ?? '') || <span className="text-muted">—</span>}- </div>- ),- },- {- field: 'scannerType',- label: 'Type',- value: recorded(config.scannerType, () => (- <span>{scannerTypeLabel(config.scannerType as ScannerType)}</span>- )),- },- {- field: 'model',- label: 'Model',- value: recorded(config.model, () => <span>{modelLabel(config.model)}</span>),- },- {- field: 'provider',- label: 'Provider',- value: recorded(config.provider, () => <span>{config.provider}</span>),- },- {- field: 'emitsSignals',- label: 'Emit signals',- value: recorded(config.emitsSignals, () => <BooleanTag value={!!config.emitsSignals} />),- },- {- field: 'samplingMode',- label: 'Session coverage',- value: recorded(config.samplingMode, () => (- <span>- {SAMPLING_MODE_OPTIONS.find((option) => option.value === config.samplingMode)?.label ??- config.samplingMode}- </span>- )),- },- {- field: 'samplingRate',- label: 'Sampling',- value: recorded(config.samplingRate, () => (- <span>{Math.round((config.samplingRate ?? 0) * 1000) / 10}%</span>- )),- },- ...Object.keys(config.scannerConfig)- .filter((key) => key !== 'prompt')- .map((key) => {- const { kind, label } = fieldEditor(key, config.scannerConfig[key])- return { field: key, label, value: <FieldCurrentValue kind={kind} value={config.scannerConfig[key]} /> }- }),- {- field: 'query',- label: 'Recording filters',- value: recorded(config.query, () => <RecordingFilters query={config.query} />),- },- ]- return (- <div className="grid grid-cols-[auto_1fr] items-baseline gap-x-3 gap-y-1.5 text-xs">- {rows.map((row) => (- <Fragment key={row.field}>- <span className="text-muted">{row.label}</span>- {/* Emphasis suits a short value, not a whole prompt. The change summary flags that one. */}- <span className={changed.has(row.field) && row.field !== 'prompt' ? 'font-medium' : undefined}>- {row.value}- </span>- </Fragment>- ))}- </div>- )-}--function ConfigVersionHistory({ scanner }: { scanner: ReplayScanner }): JSX.Element | null {- const { observationStatsApi } = useValues(replayScannerLogic({ id: scanner.id }))- const { isDarkModeOn } = useValues(themeLogic)- const markers = observationStatsApi?.labels.version_markers ?? []- const currentVersion = scanner.scanner_version- const hasCurrentMarker = markers.some((marker) => marker.version === currentVersion)- if (markers.length === 0 && !hasCurrentMarker && !scanner.scanner_config.prompt) {- return null- }- const byVersion = new Map(markers.map((marker) => [marker.version, marker]))- // A version saved but not yet scanned has no marker, so the live scanner stands in for it.- const configs = markers.map(versionConfigFromMarker)- if (!hasCurrentMarker) {- configs.push(versionConfigFromScanner(scanner))- }- const changesByVersion = versionChangesByVersion(configs)- const newestFirst = [...configs].sort((a, b) => b.version - a.version)- return (- <LemonCard className="p-4" hoverEffect={false}>- <CardHeader icon={<IconPencil />} title="Config versions" />- <div className="flex flex-col gap-3">- {newestFirst.map((config) => {- const marker = byVersion.get(config.version)- const changes = changesByVersion.get(config.version)- return (- <div- key={config.version}- className="border rounded p-3 space-y-2"- id={`prompt-v${config.version}`}- >- <div className="flex flex-wrap items-center gap-2 text-xs text-muted">- <LemonTag- type={config.version === currentVersion ? 'warning' : 'muted'}- className="font-mono"- >- v{config.version}- </LemonTag>- {marker ? (- <>- <span>from {dayjs(marker.date).format('MMM D, YYYY')}</span>- <span className="flex items-center gap-1">- <IconThumbsUpFilled className="text-success" /> {marker.up}- </span>- <span className="flex items-center gap-1">- <IconThumbsDownFilled className="text-danger" /> {marker.down}- </span>- </>- ) : (- <span>current · no scans yet</span>- )}- </div>- {changes ? (- <VersionChangeSummary- changes={changes}- version={config.version}- isDarkModeOn={isDarkModeOn}- />- ) : (- <div className="text-xs text-muted">Oldest version with scans.</div>- )}- {/* Collapsed by default: the summary above already names what changed, so the- full config is only needed when someone wants the rest of it. */}- <LemonCollapse- embedded- size="xsmall"- panels={[- {- key: 'config',- header: 'Full config',- content: (- <VersionFields- config={config}- changed={- new Set((changes?.changes ?? []).map((change) => change.field))- }- />- ),- },- ]}- />- </div>- )- })}- </div>- </LemonCard>- )-}--export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }): JSX.Element {- const { observationStats, togglingEnabled } = useValues(replayScannerLogic({ id: scanner.id }))- const { showUsd } = useValues(visionQuotaLogic)- const { toggleEnabled } = useActions(replayScannerLogic({ id: scanner.id }))- const { featureFlags } = useValues(featureFlagLogic)- const namingVariant = modelNamingVariant(featureFlags[FEATURE_FLAGS.REPLAY_VISION_MODEL_TIER_NAMING_EXPERIMENT])- const samplingPercent = Math.round((scanner.sampling_rate ?? 0) * 1000) / 10-- return (- <div className="flex flex-col gap-4">- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- <div className="flex flex-col gap-4">- <div className="rounded border p-4 bg-bg-light flex flex-col gap-2">- <LemonSwitch- checked={scanner.enabled}- onChange={() => toggleEnabled()}- loading={togglingEnabled}- disabledReason={getReplayVisionEditDisabledReason(scanner.user_access_level)}- label="Enable scanner"- bordered- fullWidth- data-attr="vision-scanner-toggle-enabled"- data-ph-capture-attribute-scanner-type={scanner.scanner_type}- data-ph-capture-attribute-will-be-enabled={!scanner.enabled}- />- <span className="text-muted text-xs">- {scanner.enabled ? 'Runs automatically on a schedule' : 'Runs on-demand only'}- </span>- </div>- <LemonCard className="p-4 flex-1" hoverEffect={false}>- <CardHeader icon={<IconInfo />} title="Overview" />- <div className="flex flex-col gap-3">- <LabeledRow label="Type">- <div className="flex flex-wrap gap-1">- {SCANNER_TYPES.map((scannerType) => (- <ScannerTypeBadge- key={scannerType}- scannerType={scannerType}- variant={scanner.scanner_type === scannerType ? 'default' : 'deemphasized'}- />- ))}- </div>- </LabeledRow>- <LabeledRow label="Description">- <Multiline value={scanner.description} />- </LabeledRow>- <LabeledRow label="Model">- <OptionTags options={getModelOptions(namingVariant)} selected={scanner.model} />- </LabeledRow>- </div>- </LemonCard>- </div>-- <LemonCard className="p-4 h-full" hoverEffect={false}>- <CardHeader icon={<IconPencil />} title="Behavior" />- <div className="flex flex-col gap-3">- <BehaviorCardContent scanner={scanner} />- </div>- </LemonCard>- </div>-- <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">- <LemonCard className="p-4" hoverEffect={false}>- <CardHeader icon={<IconBolt />} title="Scan conditions" />- <div className="flex flex-col gap-3">- <LabeledRow label="Session coverage">- {SAMPLING_MODE_OPTIONS.find((o) => o.value === scanner.sampling_mode)?.label ??- scanner.sampling_mode}- </LabeledRow>- <LabeledRow label="Sampling">{samplingPercent}%</LabeledRow>- <LabeledRow label="Recording filters">- <RecordingFilters query={scanner.query} />- </LabeledRow>- </div>- </LemonCard>-- <LemonCard className="p-4" hoverEffect={false}>- <CardHeader icon={<IconClock />} title="Lifecycle" />- <div className="flex flex-col gap-3">- <LabeledRow label="Created by">- {scanner.created_by ? (- <ProfilePicture- user={{- first_name: scanner.created_by.first_name,- last_name: scanner.created_by.last_name,- email: scanner.created_by.email,- }}- size="md"- showName- />- ) : (- <span className="text-muted">—</span>- )}- </LabeledRow>- <LabeledRow label="Created">- <TZLabel time={scanner.created_at} />- </LabeledRow>- <LabeledRow label="Last updated">- <TZLabel time={scanner.updated_at} />- </LabeledRow>- <LabeledRow label="Last scheduled scan">- {scanner.last_swept_at ? (- <TZLabel time={scanner.last_swept_at} />- ) : (- <span className="text-muted">Never</span>- )}- </LabeledRow>- </div>- </LemonCard>-- <LemonCard className="p-4" hoverEffect={false}>- <CardHeader icon={<IconGraph />} title="Usage" />- <div className="flex flex-col gap-3">- <LabeledRow label="Estimated monthly cost">- {scanner.estimated_monthly_credits != null ? (- <span className="tabular-nums">- {formatCreditsMaybeUsd(scanner.estimated_monthly_credits, showUsd)}{' '}- <span className="text-muted">- · {(scanner.estimated_monthly_observations ?? 0).toLocaleString()} observations- </span>- </span>- ) : (- <span className="text-muted">—</span>- )}- </LabeledRow>- <LabeledRow label="Total observations">- <span className="tabular-nums">{observationStats.total.toLocaleString()}</span>- </LabeledRow>- <LabeledRow label="Outcomes">- <span className="text-sm">- {observationStats.succeeded.toLocaleString()} succeeded ·{' '}- {observationStats.failed.toLocaleString()} failed ·{' '}- {observationStats.ineligible.toLocaleString()} ineligible- </span>- </LabeledRow>- <div className="text-xs text-muted">- <CreditPriceNote dataAttr="vision-pricing-link-scanner-usage" />- </div>- </div>- </LemonCard>- </div>- <ConfigVersionHistory scanner={scanner} />- </div>- )-}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsxindex cbf2e1df1b9f..12dff1e79b63 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsx@@ -1,8 +1,6 @@import { useActions, useValues } from 'kea'import { useCallback, useMemo } from 'react'-import { Spinner } from '@posthog/lemon-ui'-import { InsightVizNode, NodeKind, ProductKey, TrendsQuery } from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'import {@@ -157,9 +155,7 @@ export function ScannerInsightsChart({}): JSX.Element {// Date comes from the Overview tab's shared filter bar (scannerOverviewLogic), so the chart and the// stat panels move together; the chart no longer carries its own date picker.- const { overviewDateFrom, overviewDateTo, coverageStats, overviewStatsApiLoading } = useValues(- scannerOverviewLogic({ scannerId })- )+ const { overviewDateFrom, overviewDateTo } = useValues(scannerOverviewLogic({ scannerId }))// Memoized so a re-render (e.g. stats arriving) can't churn the query and abort an in-flight load.// `tags.productKey` is required for ClickHouse query tagging; without it the runner aborts.const chartQuery = useMemo<InsightVizNode>(@@ -187,25 +183,8 @@ export function ScannerInsightsChart({// The Observations tab requires session_recording read access; without it the chart stays static.const canDrillIntoObservations = !getReplayVisionRecordingViewDisabledReason()return (- <div className="border rounded p-4 bg-surface-primary space-y-3">- <div className="flex items-baseline justify-between gap-2">- <div>- <div className="text-sm font-medium">{chartTitle(scannerType)}</div>- {coverageStats.totalSessions > 0 ? (- <div className="text-xs text-muted tabular-nums mt-0.5">- Scanned <span className="font-semibold text-default">{coverageStats.recentSessions}</span>{' '}- session- {coverageStats.recentSessions === 1 ? '' : 's'} in the last {coverageStats.recentDays} day- {coverageStats.recentDays === 1 ? '' : 's'} ·{' '}- <span className="font-semibold text-default">{coverageStats.totalSessions}</span> total- </div>- ) : overviewStatsApiLoading ? (- <div className="text-xs text-muted mt-0.5 flex items-center gap-1.5">- <Spinner /> Loading coverage…- </div>- ) : null}- </div>- </div>+ <div className="flex flex-col gap-2">+ <div className="text-sm font-medium">{chartTitle(scannerType)}</div><VisionInsightChartquery={chartQuery}insightProps={chartInsightProps}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsxindex 4d85cafbabcf..f587ef4b611e 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx@@ -15,13 +15,15 @@ import { DateMappingOption } from '~/types'import { VisionDocsLink } from '../../components/DocsLink'import { FilterPill } from '../../components/FilterPill'import { NumericRangeFilterPill } from '../../components/NumericRangeFilterPill'-import { ObservationResultSummary, ObservationStatusTag } from '../../components/ObservationCard'+import { 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 { markSimilarSearchIntent, searchTabUrl, similarSearchUrl } from '../../search/observationQueries'import { shortBackfillId } from '../../utils/backfills'+import { citedTextToPlainText } from '../../utils/citations'+import { readModelOutput, readReasoning } from '../../utils/observation'import {OBSERVATIONS_PAGE_SIZE,ObservationStatusValue,@@ -29,7 +31,8 @@ import {ObservationVerdictValue,replayScannerLogic,} from '../replayScannerLogic'-import { OBSERVATION_TRIGGER_TAG } from '../types'+import { OBSERVATION_TRIGGER_TAG, unsuccessfulScanReason } from '../types'+import { ObservationRowResult } from './ObservationRowResult'const STATUS_OPTIONS: { value: ObservationStatusValue; label: string }[] = [{ value: 'succeeded', label: 'Succeeded' },@@ -135,41 +138,44 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):const scannerType = scanner?.scanner_typeconst tagFilterOptions = availableTags.map((tag) => ({ value: tag, label: tag }))const scoreScale = scanner?.scanner_type === 'scorer' ? scanner.scanner_config.scale : undefined+ const hasReasoningColumn = scannerType === 'scorer' || scannerType === 'monitor'const columns: LemonTableColumns<ReplayObservationApi> = [{title: '',key: 'thumbnail',- width: 96,+ width: 1,render: (_, obs) => (<Linkto={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',- width: 300,- render: (_, obs) => (- <div className="flex items-center gap-2 min-w-0">- <span className="flex w-2 shrink-0">- {!obs.viewed && (- <Tooltip title="You haven't opened this observation yet.">- <span className="size-2 rounded-full bg-danger" />- </Tooltip>- )}- </span>- <Link- to={observationDetailUrl(obs.id, observationDetailLinkParams)}- className="font-mono text-xs text-primary truncate block"+ <Tooltip+ title={+ (obs.media ?? []).some((entry) => entry.kind === 'thumbnail') ? (+ <ObservationThumbnail observation={obs} className="w-128 border-0" />+ ) : undefined+ }+ placement="right"+ delayMs={300}+ containerClassName="max-w-none p-1">- {obs.session_id}- </Link>- </div>+ <div className="relative">+ <ObservationThumbnail observation={obs} className="w-40 @7xl/observations:w-52" />+ {!obs.viewed && (+ <LemonTag+ type="primary"+ size="small"+ // The primary tag is transparent by default, which lets the frame show through.+ className="absolute top-1 left-1 shadow-sm bg-surface-primary!"+ title="You haven't opened this observation yet."+ >+ New+ </LemonTag>+ )}+ </div>+ </Tooltip>+ </Link>),},{@@ -179,12 +185,16 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):render: (_, obs) =>obs.recording_subject_email ? (<Tooltip title={obs.distinct_id ?? undefined}>- <span className="truncate block max-w-[16rem]">{obs.recording_subject_email}</span>+ <span className="truncate block max-w-64 @7xl/observations:max-w-md">+ {obs.recording_subject_email}+ </span></Tooltip>) : obs.distinct_id ? (- <span className="font-mono text-xs text-muted truncate block max-w-[16rem]">{obs.distinct_id}</span>+ <span className="font-mono text-xs truncate block max-w-64 @7xl/observations:max-w-md">+ {obs.distinct_id}+ </span>) : (- <span className="text-muted">—</span>+ <span className="text-muted">Unknown person</span>),},{@@ -210,31 +220,48 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):key: 'result',render: (_, obs) => (<Link to={observationDetailUrl(obs.id, observationDetailLinkParams)} className="block">- <div className="min-w-[18rem] max-w-xl">- <ObservationResultSummary observation={obs} />+ {/* The shared compact view truncates to one line, which sizes the column to the whole summary and+ pushes the table past the page. Two wrapped lines let the column shrink with the page instead. */}+ <div+ className={`[&_.truncate]:whitespace-normal [&_.truncate]:line-clamp-2 ${+ hasReasoningColumn ? '' : 'min-w-60'+ }`}+ >+ {hasReasoningColumn && obs.status !== 'succeeded' ? (+ <span className="text-muted">—</span>+ ) : (+ <ObservationRowResult observation={obs} />+ )}</div></Link>),- sorter: scannerType === 'scorer' || scannerType === 'monitor' ? true : undefined,- },- {- title: 'Version',- key: 'version',- render: (_, obs) => {- const tag = versionTag(obs.scanner_snapshot?.scanner_version, scanner?.scanner_version)- if (!tag) {- return <span className="text-muted">—</span>- }- return (- <Tooltip title={tag.tooltip}>- <LemonTag type={tag.type} className="font-mono">- {tag.label}- </LemonTag>- </Tooltip>- )- },- sorter: true,+ sorter: hasReasoningColumn ? true : undefined,+ // The text column takes the spare width on wide screens, so short columns like Person stay compact.+ width: hasReasoningColumn ? undefined : '100%',},+ ...(hasReasoningColumn+ ? [+ {+ title: 'Reasoning',+ key: 'reasoning',+ width: '100%',+ render: (_: unknown, obs: ReplayObservationApi) => {+ const failure = unsuccessfulScanReason(obs.status, obs.error_reason)+ if (failure) {+ return <span className="min-w-44 text-sm text-secondary line-clamp-2">{failure}</span>+ }+ const reasoning = obs.status === 'succeeded' ? readReasoning(obs) : null+ return reasoning ? (+ <span className="min-w-44 text-sm text-secondary line-clamp-2">+ {citedTextToPlainText(reasoning, readModelOutput(obs)?.reasoning_segments)}+ </span>+ ) : (+ <span className="text-muted">—</span>+ )+ },+ },+ ]+ : []),{title: 'Triggered by',key: 'triggered_by',@@ -263,11 +290,22 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):type="secondary"icon={<IconEye />}to={observationDetailUrl(obs.id, observationDetailLinkParams)}- className="whitespace-nowrap"+ className="hidden @7xl/observations:flex whitespace-nowrap"data-attr="vision-observation-view-details">View details</LemonButton>+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconEye />}+ to={observationDetailUrl(obs.id, observationDetailLinkParams)}+ tooltip="View details"+ // A `to` renders a Link, which skips LemonButton's tooltip-to-aria-label fallback.+ aria-label="View details"+ className="@7xl/observations:hidden"+ data-attr="vision-observation-view-details"+ /><LemonButtonsize="small"type="secondary"@@ -287,150 +325,150 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):]return (- <div className="space-y-2">- {/* The one-line toolbar needs ~1120px of viewport, so it only stops wrapping at xl. */}- <div className="flex flex-wrap items-center gap-3 xl:flex-nowrap">- <h3 className="font-semibold text-base m-0">Observation history</h3>- <span className="text-muted text-sm xl:whitespace-nowrap">+ <div className="@container/observations space-y-2">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">+ <h3 className="font-semibold text-base m-0 whitespace-nowrap">Observation history</h3>+ <span className="text-muted text-sm whitespace-nowrap">{observationStats.total.toLocaleString()} total ·{' '}<span className={observationStats.failed > 0 ? 'text-danger' : undefined}>{observationStats.failed.toLocaleString()} failed</span>{' '}· {observationStats.inFlight.toLocaleString()} in flight</span>- <div className="ml-auto flex flex-wrap items-center gap-3 xl:flex-nowrap">- <LemonButton- type="secondary"- size="small"- icon={<IconSearch />}- to={searchTabUrl({ scanner: scannerId })}- data-attr="vision-observations-search"- >- Search observations- </LemonButton>- <div className="flex flex-wrap items-center gap-2 xl:flex-nowrap">- {(observationStats.total > 0 || hasActiveObservationFilters) && (- <>- <LemonInput- type="search"- size="small"- placeholder="Person email"- value={observationSubjectFilter}- onChange={setObservationSubjectFilter}- className="w-full sm:w-56"- />- <DateFilter- size="small"- dateFrom={observationDateFrom}- dateTo={observationDateTo}- dateOptions={OBSERVATION_DATE_OPTIONS}- onChange={(dateFrom, dateTo) => setObservationDateRange(dateFrom, dateTo)}+ <div className="order-3 basis-full flex flex-wrap items-center gap-2 @[100rem]/observations:order-2 @[100rem]/observations:basis-auto">+ {(observationStats.total > 0 || hasActiveObservationFilters) && (+ <>+ <LemonInput+ type="search"+ size="small"+ placeholder="Person email"+ value={observationSubjectFilter}+ onChange={setObservationSubjectFilter}+ className="w-full sm:w-56"+ />+ <DateFilter+ size="small"+ dateFrom={observationDateFrom}+ dateTo={observationDateTo}+ dateOptions={OBSERVATION_DATE_OPTIONS}+ onChange={(dateFrom, dateTo) => setObservationDateRange(dateFrom, dateTo)}+ />+ <FilterPill<ObservationStatusValue>+ label="Status"+ options={STATUS_OPTIONS}+ value={observationStatusFilter}+ onChange={setObservationStatusFilter}+ />+ <FilterPill<ObservationTriggeredByValue>+ label="Triggered by"+ options={TRIGGERED_BY_OPTIONS}+ value={observationTriggeredByFilter}+ onChange={setObservationTriggeredByFilter}+ />+ {scannerType === 'monitor' && (+ <FilterPill<ObservationVerdictValue>+ label="Verdict"+ options={VERDICT_OPTIONS}+ value={observationVerdictFilter}+ onChange={setObservationVerdictFilter}/>- <FilterPill<ObservationStatusValue>- label="Status"- options={STATUS_OPTIONS}- value={observationStatusFilter}- onChange={setObservationStatusFilter}+ )}+ {scannerType === 'scorer' && (+ <NumericRangeFilterPill+ label="Score"+ min={observationMinScoreFilter}+ max={observationMaxScoreFilter}+ scaleMin={scoreScale?.min}+ scaleMax={scoreScale?.max}+ onChange={setObservationScoreRange}+ dataAttr="vision-observations-score-filter"/>- <FilterPill<ObservationTriggeredByValue>- label="Triggered by"- options={TRIGGERED_BY_OPTIONS}- value={observationTriggeredByFilter}- onChange={setObservationTriggeredByFilter}+ )}+ {scannerType === 'classifier' && tagFilterOptions.length > 0 && (+ <FilterPill<string>+ label="Category"+ searchPlaceholder="Search categories"+ options={tagFilterOptions}+ value={observationTagFilter}+ onChange={setObservationTagFilter}+ searchable/>- {scannerType === 'monitor' && (- <FilterPill<ObservationVerdictValue>- label="Verdict"- options={VERDICT_OPTIONS}- value={observationVerdictFilter}- onChange={setObservationVerdictFilter}- />- )}- {scannerType === 'scorer' && (- <NumericRangeFilterPill- label="Score"- min={observationMinScoreFilter}- max={observationMaxScoreFilter}- scaleMin={scoreScale?.min}- scaleMax={scoreScale?.max}- onChange={setObservationScoreRange}- dataAttr="vision-observations-score-filter"- />- )}- {scannerType === 'classifier' && tagFilterOptions.length > 0 && (- <FilterPill<string>- label="Category"- searchPlaceholder="Search categories"- options={tagFilterOptions}- value={observationTagFilter}- onChange={setObservationTagFilter}- searchable- />- )}- {observationBackfillFilter && (- // Same secondary/small button the FilterPills next to it render, so- // the row stays visually uniform. It carries a clear action rather- // than a dropdown, because this filter arrives from a link and has- // nothing to choose between.- <LemonButton- type="secondary"- size="small"- tooltip={`Backfill ${observationBackfillFilter}`}- sideAction={{- icon: <IconX />,- onClick: () => setObservationBackfillFilter(null),- tooltip: 'Clear backfill filter',- }}- data-attr="vision-observations-backfill-filter"- >- Backfill {shortBackfillId(observationBackfillFilter)}- </LemonButton>- )}+ )}+ {observationBackfillFilter && (+ // Same secondary/small button the FilterPills next to it render, so+ // the row stays visually uniform. It carries a clear action rather+ // than a dropdown, because this filter arrives from a link and has+ // nothing to choose between.<LemonButton- type="tertiary"+ type="secondary"size="small"- onClick={() => clearObservationFilters()}- disabledReason={hasActiveObservationFilters ? undefined : 'No active filters'}+ tooltip={`Backfill ${observationBackfillFilter}`}+ sideAction={{+ icon: <IconX />,+ onClick: () => setObservationBackfillFilter(null),+ tooltip: 'Clear backfill filter',+ }}+ data-attr="vision-observations-backfill-filter">- Clear filters+ Backfill {shortBackfillId(observationBackfillFilter)}</LemonButton>- </>- )}- {scannerType === 'summarizer' && observationStats.total > 0 && (+ )}<LemonButton+ type="tertiary"size="small"- type="secondary"- icon={<IconCopy />}- onClick={() => copyAllObservations()}- loading={copyingAllObservations}- tooltip="Copies the filtered summaries as plain text, ready to paste into a doc or an LLM"- data-attr="vision-observations-copy-all"+ onClick={() => clearObservationFilters()}+ disabledReason={hasActiveObservationFilters ? undefined : 'No active filters'}>- Copy all+ Clear filters</LemonButton>- )}- <Tooltip- title={- hasObservationsInFlight- ? 'Auto-refreshing while observations are in flight'- : 'Refresh observations'- }+ </>+ )}+ </div>+ <div className="order-2 ml-auto flex flex-wrap items-center gap-2 @[100rem]/observations:order-3">+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconSearch />}+ to={searchTabUrl({ scanner: scannerId })}+ data-attr="vision-observations-search"+ >+ Search observations+ </LemonButton>+ {scannerType === 'summarizer' && observationStats.total > 0 && (+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconCopy />}+ onClick={() => copyAllObservations()}+ loading={copyingAllObservations}+ tooltip="Copies the filtered summaries as plain text, ready to paste into a doc or an LLM"+ data-attr="vision-observations-copy-all">- <LemonButton- size="small"- type="secondary"- icon={<IconRefresh />}- onClick={() => refreshObservations()}- loading={observationsLoading}- data-attr="vision-observations-refresh"- >- Refresh- </LemonButton>- </Tooltip>- </div>+ Copy all+ </LemonButton>+ )}+ <Tooltip+ title={+ hasObservationsInFlight+ ? 'Auto-refreshing while observations are in flight'+ : 'Refresh observations'+ }+ >+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconRefresh />}+ onClick={() => refreshObservations()}+ loading={observationsLoading}+ data-attr="vision-observations-refresh"+ >+ Refresh+ </LemonButton>+ </Tooltip></div></div><LemonTable+ rowRibbonColor={(obs) => (obs.viewed ? null : 'var(--color-accent)')}columns={columns}dataSource={observations}loading={!observationsActive || triggeringOnDemandObservation || observationsLoading}@@ -461,7 +499,7 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):<LemonButtontype="primary"icon={<IconPlay />}- to={`${urls.replayVision(scannerId)}?tab=on-demand`}+ to={`${urls.replayVision(scannerId)}?tab=run`}data-attr="vision-observations-empty-scan-now">Scan a recording nowdiff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsxindex eae979e89ca7..1ac1b763ed32 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx@@ -1,42 +1,35 @@import { useActions, useValues } from 'kea'import { IconPeople } from '@posthog/icons'-import { LemonButton, LemonTag, Link, Spinner } from '@posthog/lemon-ui'+import { LemonButton, LemonTag, LemonTagType, Spinner } from '@posthog/lemon-ui'import { BarChart } from '@posthog/quill-charts'import { useChartConfig, useChartTheme } from 'lib/charts/hooks'import { LemonProgress } from 'lib/lemon-ui/LemonProgress'import { pluralize } from 'lib/utils/strings'-import { urls } from 'scenes/urls'-import { creditsToUsd, formatCreditsRange } from '../../utils/credits'-import { replayScannerLogic } from '../replayScannerLogic'+import { type AffectedCohortQualifier, type ObservationVerdictValue, replayScannerLogic } from '../replayScannerLogic'import { ReplayScannerTab, replayScannerSceneLogic } from '../replayScannerSceneLogic'import { scannerOverviewLogic } from '../scannerOverviewLogic'-import { scannerSelfDrivingStatsLogic } from '../scannerSelfDrivingStatsLogic'import { ScannerType } from '../types'import { ScannerInsightsChart } from './ScannerInsightsChart'import { ScannerOverviewFilters } from './ScannerOverviewFilters'+import { ScannerScoutCard } from './ScannerScoutCard'+import { ScannerSelfDrivingCard } from './ScannerSelfDrivingCard'+import { ScannerSetupCard } from './ScannerSetupCard'+import { ScannerStatusStrip } from './ScannerStatusStrip'-function OverviewPanel({+function FindingsSection({title,subtitle,- disabled,- fill,children,}: {title: stringsubtitle?: React.ReactNode- disabled?: boolean- fill?: booleanchildren: React.ReactNode}): JSX.Element {return (- <div- className={`border rounded p-4 space-y-3 ${fill ? 'h-full flex flex-col' : ''} ${- disabled ? 'bg-surface-secondary opacity-60' : 'bg-surface-primary'- }`}- >+ <div className="min-w-0 flex flex-col gap-3"><div className="flex items-baseline justify-between gap-2"><span className="text-sm font-medium">{title}</span>{subtitle && <span className="text-xs text-muted tabular-nums">{subtitle}</span>}@@ -106,202 +99,118 @@ function RankedTermList({)}-function ImpactOverview({ scannerId }: { scannerId: string }): JSX.Element | null {- const { scanner, overviewImpact, overviewImpactLoading } = useValues(scannerOverviewLogic({ scannerId }))- // Cohort creation is a scanner-level action, independent of the overview's filter set.- const { affectedCohortLoading } = useValues(replayScannerLogic({ id: scannerId }))- const { saveAffectedCohort } = useActions(replayScannerLogic({ id: scannerId }))+const VERDICT_ROWS: { verdict: ObservationVerdictValue; label: string; tagType: LemonTagType }[] = [+ { verdict: 'yes', label: 'Yes', tagType: 'highlight' },+ { verdict: 'no', label: 'No', tagType: 'default' },+ { verdict: 'inconclusive', label: 'Inconclusive', tagType: 'muted' },+]- // Impact needs a per-type predicate; only the monitor one (verdict-yes) exists without a qualifier.- if (scanner?.scanner_type !== 'monitor') {- return null- }- if (!overviewImpact || overviewImpact.affected_sessions === 0) {- return (- <OverviewPanel title="Impact" fill>- <PanelEmpty- loading={overviewImpactLoading}- message={- overviewImpact- ? `No affected sessions in the last ${overviewImpact.window_days} days.`- : "Couldn't load impact counts."- }- />- </OverviewPanel>- )- }- return (- <OverviewPanel title="Impact" subtitle={`last ${overviewImpact.window_days} days`} fill>- <div className="flex flex-wrap items-center justify-between gap-4">- <div className="text-sm">- Matched{' '}- <strong className="tabular-nums">{overviewImpact.affected_sessions.toLocaleString()}</strong>{' '}- session{overviewImpact.affected_sessions === 1 ? '' : 's'} from{' '}- <strong className="tabular-nums">{overviewImpact.affected_users.toLocaleString()}</strong> user- {overviewImpact.affected_users === 1 ? '' : 's'}- {overviewImpact.sessions_without_user > 0 && (- <span className="text-muted"> ({overviewImpact.sessions_without_user} without a user)</span>- )}- </div>- <LemonButton- type="secondary"- size="small"- icon={<IconPeople />}- onClick={() => saveAffectedCohort()}- loading={affectedCohortLoading}- disabledReason={overviewImpact.affected_users === 0 ? 'No users to save' : undefined}- data-attr="vision-save-affected-cohort"- className="shrink-0"- >- Save as cohort- </LemonButton>- </div>- </OverviewPanel>- )-}--// One stage of the self-driving funnel: a big count over a muted label, matching the panel grid density.-function SelfDrivingStage({ count, label }: { count: number; label: string }): JSX.Element {- return (- <div className="flex flex-col">- <span className="text-lg font-semibold tabular-nums">{count.toLocaleString()}</span>- <span className="text-xs text-muted">{label}</span>- </div>- )-}--function SelfDrivingOverview({ scannerId }: { scannerId: string }): JSX.Element {- const { scanner } = useValues(replayScannerLogic({ id: scannerId }))- const { selfDrivingStats, selfDrivingStatsLoading } = useValues(scannerSelfDrivingStatsLogic({ scannerId }))-- // Unresolved data renders as loading, never as the off-state nudge or the empty state.- if (!scanner || (selfDrivingStatsLoading && !selfDrivingStats)) {- return (- <OverviewPanel title="Self-driving" fill>- <PanelEmpty loading message="" />- </OverviewPanel>- )- }- // Historical signals from before the toggle was turned off still count, so the off-state- // nudge only replaces the funnel when there is nothing to show.- if (!scanner.emits_signals && (!selfDrivingStats || selfDrivingStats.signals_emitted === 0)) {- return (- <OverviewPanel title="Self-driving" disabled fill>- <div className="text-muted text-sm">- This scanner doesn't emit signals. Turn on self-driving in the{' '}- <Link to={urls.replayVisionScannerConfigure(scannerId)}>scanner's configuration</Link> to feed its- findings into Signals, where agents investigate and draft pull requests.- </div>- </OverviewPanel>- )- }- if (!selfDrivingStats || selfDrivingStats.signals_emitted === 0) {- return (- <OverviewPanel title="Self-driving" fill>- <PanelEmpty- loading={selfDrivingStatsLoading}- message={- selfDrivingStats- ? 'No signals emitted yet. Findings flow into Signals as sessions are scanned.'- : "Couldn't load self-driving stats."- }- />- </OverviewPanel>- )- }+function SaveCohortButton({+ scannerId,+ qualifier,+ cohortKey,+ tooltip,+ ariaLabel,+ emptyReason,+ dataAttr,+ children,+}: {+ scannerId: string+ qualifier: AffectedCohortQualifier+ cohortKey: string+ tooltip: string+ ariaLabel?: string+ emptyReason?: string+ dataAttr: string+ children?: React.ReactNode+}): JSX.Element {+ const { cohortDisabledReason } = useValues(scannerOverviewLogic({ scannerId }))+ const { saveCohort } = useActions(scannerOverviewLogic({ scannerId }))+ const { affectedCohortLoading, savingCohortKey } = useValues(replayScannerLogic({ id: scannerId }))return (- <OverviewPanel title="Self-driving" subtitle="all time" fill>- {/* Two up in a narrow panel, four across once there is room. */}- <div- className="@container/funnel grid grid-cols-2 @sm/funnel:grid-cols-4 gap-4"- data-attr="vision-self-driving-funnel"- >- <SelfDrivingStage- count={selfDrivingStats.signals_emitted}- label={pluralize(selfDrivingStats.signals_emitted, 'signal emitted', 'signals emitted', false)}- />- <SelfDrivingStage- count={selfDrivingStats.reports_contributed}- label={pluralize(- selfDrivingStats.reports_contributed,- 'report contributed to',- 'reports contributed to',- false- )}- />- <SelfDrivingStage- count={selfDrivingStats.prs_opened}- label={pluralize(selfDrivingStats.prs_opened, 'PR opened', 'PRs opened', false)}- />- <SelfDrivingStage- count={selfDrivingStats.prs_merged}- label={pluralize(selfDrivingStats.prs_merged, 'PR merged', 'PRs merged', false)}- />- </div>- <div className="text-xs text-muted">- A report can combine signals from several scanners and other sources, so these are contributions, not- sole causes.- </div>- </OverviewPanel>+ <LemonButton+ type="secondary"+ size="xsmall"+ icon={<IconPeople />}+ tooltip={tooltip}+ aria-label={ariaLabel}+ onClick={() => saveCohort(qualifier)}+ loading={affectedCohortLoading && savingCohortKey === cohortKey}+ disabledReason={+ emptyReason ??+ cohortDisabledReason ??+ (affectedCohortLoading && savingCohortKey !== cohortKey ? 'Another cohort is being created' : undefined)+ }+ data-attr={dataAttr}+ >+ {children}+ </LemonButton>)}-function MonitorOverview({ scannerId }: { scannerId: string }): JSX.Element {- const { monitorStats, hasActiveOverviewFilters, overviewStatsApiLoading } = useValues(+function VerdictMixOverview({ scannerId }: { scannerId: string }): JSX.Element {+ const { monitorStats, hasActiveOverviewFilters, overviewStatsApiLoading, cohortWindowDays } = useValues(scannerOverviewLogic({ scannerId }))- const { yesTotal, noTotal, inconclusiveTotal } = monitorStats- const total = yesTotal + noTotal + inconclusiveTotal+ const counts: Record<ObservationVerdictValue, number> = {+ yes: monitorStats.yesTotal,+ no: monitorStats.noTotal,+ inconclusive: monitorStats.inconclusiveTotal,+ }+ const total = counts.yes + counts.no + counts.inconclusiveif (total === 0) {return (- <OverviewPanel title="Verdict mix" fill>+ <FindingsSection title="Verdict mix"><PanelEmptyloading={overviewStatsApiLoading}message={hasActiveOverviewFilters ? 'No verdicts match the current filter.' : 'No verdicts yet.'}/>- </OverviewPanel>+ </FindingsSection>)}- const yesPct = Math.round((yesTotal / total) * 100)- const noPct = Math.round((noTotal / total) * 100)- const inconclusivePct = Math.max(0, 100 - yesPct - noPct)+ const rows = VERDICT_ROWS.filter(({ verdict }) => verdict !== 'inconclusive' || counts.inconclusive > 0)return (- <OverviewPanel title="Verdict mix" subtitle={`${total} verdict${total === 1 ? '' : 's'}`} fill>- <LemonProgress percent={yesPct} />- <div className="flex flex-wrap items-center gap-4 text-sm">- <span className="flex items-center gap-2">- <LemonTag type="highlight">Yes</LemonTag>- <span className="tabular-nums">- {yesTotal} ({yesPct}%)- </span>- </span>- <span className="flex items-center gap-2">- <LemonTag type="default">No</LemonTag>- <span className="tabular-nums">- {noTotal} ({noPct}%)- </span>- </span>- {inconclusiveTotal > 0 && (- <span className="flex items-center gap-2">- <LemonTag type="muted">Inconclusive</LemonTag>- <span className="tabular-nums">- {inconclusiveTotal} ({inconclusivePct}%)- </span>- </span>- )}+ <FindingsSection title="Verdict mix" subtitle={pluralize(total, 'verdict')}>+ <div className="space-y-1.5">+ {rows.map(({ verdict, label, tagType }) => {+ const count = counts[verdict]+ const percent = Math.round((count / total) * 100)+ return (+ <div key={verdict} className="flex items-center gap-2">+ <div className="w-24 shrink-0">+ <LemonTag type={tagType}>{label}</LemonTag>+ </div>+ <LemonProgress percent={percent} className="flex-1" />+ <span className="text-xs text-muted tabular-nums text-right whitespace-nowrap shrink-0 w-20">+ {count.toLocaleString()} ({percent}%)+ </span>+ <SaveCohortButton+ scannerId={scannerId}+ qualifier={{ verdict }}+ cohortKey={verdict}+ tooltip={`Save users with a ${label.toLowerCase()} verdict from the last ${pluralize(cohortWindowDays, 'day')} as a cohort`}+ emptyReason={count === 0 ? 'No sessions with this verdict' : undefined}+ // pinned: the yes row keeps the data-attr the single cohort button shipped with.+ dataAttr={+ verdict === 'yes'+ ? 'vision-save-affected-cohort'+ : `vision-save-verdict-cohort-${verdict}`+ }+ >+ Save as cohort+ </SaveCohortButton>+ </div>+ )+ })}</div>- </OverviewPanel>+ </FindingsSection>)}function ClassifierOverview({ scannerId }: { scannerId: string }): JSX.Element | null {- const { scanner, classifierTagStats, hasActiveOverviewFilters, overviewStatsApiLoading } = useValues(- scannerOverviewLogic({ scannerId })- )- // Cohort creation is a scanner-level action, independent of the overview's filter set.- const { affectedCohortLoading, savingCohortTag } = useValues(replayScannerLogic({ id: scannerId }))- const { saveAffectedCohort } = useActions(replayScannerLogic({ id: scannerId }))+ const { scanner, classifierTagStats, hasActiveOverviewFilters, overviewStatsApiLoading, cohortWindowDays } =+ useValues(scannerOverviewLogic({ scannerId }))const { fixedRanked, freeformRanked } = classifierTagStats// Wait for the scanner config — without it `freeformAllowed` defaults to `false` and the panel flashes the// "disabled" copy while the config is still loading.@@ -317,38 +226,30 @@ function ClassifierOverview({ scannerId }: { scannerId: string }): JSX.Element |: 'No freeform categories emitted yet.'const cohortAction = (tag: string): JSX.Element => (- <LemonButton- type="secondary"- size="xsmall"- icon={<IconPeople />}- tooltip={`Save users in category "${tag}" from the last 30 days as a cohort`}- onClick={() => saveAffectedCohort(tag)}- loading={affectedCohortLoading && savingCohortTag === tag}- disabledReason={- affectedCohortLoading && savingCohortTag !== tag ? 'Another cohort is being created' : undefined- }- data-attr="vision-save-tag-cohort"- >- Save as cohort- </LemonButton>+ <SaveCohortButton+ scannerId={scannerId}+ qualifier={{ tag }}+ cohortKey={tag}+ tooltip="Save as cohort"+ ariaLabel={`Save users in category "${tag}" from the last ${pluralize(cohortWindowDays, 'day')} as a cohort`}+ dataAttr="vision-save-tag-cohort"+ />)return (- <div className="grid grid-cols-1 @2xl:grid-cols-2 gap-4">- <OverviewPanel title="Top configured categories" subtitle="from the categories you defined" fill>+ <div className="grid grid-cols-1 @2xl:grid-cols-2 gap-x-8 gap-y-6">+ <FindingsSection title="Top configured categories" subtitle="from the categories you defined"><RankedTermListranked={fixedRanked}loading={overviewStatsApiLoading}emptyMessage={fixedEmpty}renderAction={cohortAction}/>- </OverviewPanel>+ </FindingsSection>- <OverviewPanel+ <FindingsSectiontitle="Top freeform categories"subtitle={freeformAllowed ? 'outside the categories you defined' : 'disabled'}- disabled={!freeformAllowed}- fill>{freeformAllowed ? (<RankedTermList@@ -364,56 +265,11 @@ function ClassifierOverview({ scannerId }: { scannerId: string }): JSX.Element |propose new ones.</div>)}- </OverviewPanel>+ </FindingsSection></div>)}-function CreditLimitOverview({ scannerId }: { scannerId: string }): JSX.Element {- const { scanner } = useValues(replayScannerLogic({ id: scannerId }))- const { creditLimitStats } = useValues(scannerOverviewLogic({ scannerId }))- // An unloaded scanner is not a scanner without a limit, so it waits rather than claiming one way.- if (!scanner) {- return (- <OverviewPanel title="Spend against limit" fill>- <PanelEmpty loading message="" />- </OverviewPanel>- )- }- if (!creditLimitStats) {- return (- <OverviewPanel title="Spend against limit" disabled fill>- <div className="text-muted text-sm">- This scanner has no spending limit. Set one in the{' '}- <Link to={urls.replayVisionScannerConfigure(scannerId)}>scanner's configuration</Link> to cap what- it can spend each billing period.- </div>- </OverviewPanel>- )- }- const { used, limit, usedPct, limitReached } = creditLimitStats- return (- <OverviewPanel- title="Spend against limit"- subtitle={limitReached ? <LemonTag type="danger">Limit reached</LemonTag> : `${usedPct}%`}- fill- >- <LemonProgress percent={usedPct} strokeColor={limitReached ? 'var(--danger)' : undefined} />- <div className="text-sm tabular-nums">- {formatCreditsRange(used, limit)} (≈ {creditsToUsd(limit)} per period)- </div>- {limitReached && (- // The tag can appear below 100%: a scanner stops as soon as what's left can't cover a whole- // scan, so the copy has to explain that rather than claim the budget is fully spent.- <div className="text-xs text-muted">- What's left won't cover another scan, so this scanner has stopped until its limit resets at the- start of the next billing period. Sessions skipped while capped are not scanned later.- </div>- )}- </OverviewPanel>- )-}-function ScorerOverview({ scannerId }: { scannerId: string }): JSX.Element {const { scorerSummary, scorerHistogram, hasActiveOverviewFilters, overviewStatsApiLoading } = useValues(scannerOverviewLogic({ scannerId })@@ -422,7 +278,7 @@ function ScorerOverview({ scannerId }: { scannerId: string }): JSX.Element {const config = useChartConfig(() => ({ showGrid: false }), [])if (!scorerSummary || !scorerHistogram) {return (- <OverviewPanel title="Score distribution">+ <FindingsSection title="Score distribution"><PanelEmptyloading={overviewStatsApiLoading}message={@@ -431,12 +287,12 @@ function ScorerOverview({ scannerId }: { scannerId: string }): JSX.Element {: 'No scored observations yet.'}/>- </OverviewPanel>+ </FindingsSection>)}return (- <OverviewPanel title="Score distribution" subtitle={`${scorerSummary.count} scored`} fill>- <div className="flex-1 min-h-40 flex flex-col">+ <FindingsSection title="Score distribution" subtitle={`${scorerSummary.count} scored`}>+ <div className="h-64 flex flex-col"><BarChartlabels={scorerHistogram.labels}series={[{ key: 'count', label: 'Sessions', color: theme.colors[0], data: scorerHistogram.counts }]}@@ -450,10 +306,32 @@ function ScorerOverview({ scannerId }: { scannerId: string }): JSX.Element {<span>avg {scorerSummary.mean.toFixed(1)}</span><span>max {scorerSummary.max.toFixed(1)}</span></div>- </OverviewPanel>+ </FindingsSection>)}+function FindingsCoverage({ scannerId }: { scannerId: string }): JSX.Element | null {+ const { coverageStats, overviewStatsApiLoading } = useValues(scannerOverviewLogic({ scannerId }))+ if (coverageStats.totalSessions > 0) {+ return (+ <div className="text-xs text-muted tabular-nums mt-0.5">+ Scanned <span className="font-semibold text-default">{coverageStats.recentSessions}</span>{' '}+ {pluralize(coverageStats.recentSessions, 'session', 'sessions', false)} in the last{' '}+ {pluralize(coverageStats.recentDays, 'day')} ·{' '}+ <span className="font-semibold text-default">{coverageStats.totalSessions}</span> total+ </div>+ )+ }+ if (overviewStatsApiLoading) {+ return (+ <div className="text-xs text-muted mt-0.5 flex items-center gap-1.5">+ <Spinner /> Loading coverage…+ </div>+ )+ }+ return null+}+// The interstitial a just-created scanner shows instead of the filters + charts, whose "no matching// events" empty state would wrongly suggest the user's setup is broken while the first sweep runs.// It also hides the overview's reload buttons, so when the background checks keep failing it has to@@ -488,7 +366,7 @@ function FirstScanPendingPanel({ scannerId }: { scannerId: string }): JSX.Elemen<LemonButtontype="secondary"size="small"- onClick={() => setActiveTab(ReplayScannerTab.OnDemand)}+ onClick={() => setActiveTab(ReplayScannerTab.Run)}data-attr="vision-first-scan-pending-scan-now">Scan a recording now@@ -503,61 +381,58 @@ export function ScannerOverview({ scannerId }: { scannerId: string }): JSX.Elemeif (!scanner) {return null}- if (firstScanPending) {- return <FirstScanPendingPanel scannerId={scannerId} />- }const scannerType: ScannerType = scanner.scanner_typeconst typeOverview =scannerType === 'monitor' ? (- <MonitorOverview scannerId={scannerId} />+ <VerdictMixOverview scannerId={scannerId} />) : scannerType === 'classifier' ? (<ClassifierOverview scannerId={scannerId} />) : scannerType === 'scorer' ? (<ScorerOverview scannerId={scannerId} />) : null- // Scorer puts its line chart and score-distribution histogram side by side to reclaim vertical space.- let body: JSX.Element- if (scannerType === 'scorer') {- body = (- <div className="grid grid-cols-1 @2xl:grid-cols-2 gap-4">- {/* min-w-0 lets the canvas charts shrink inside their grid tracks instead of overflowing */}- <div className="min-w-0">- <ScannerInsightsChart scannerId={scannerId} scannerType={scannerType} />+ const body = (+ <>+ <ScannerInsightsChart scannerId={scannerId} scannerType={scannerType} />+ {typeOverview && <div className="border-t pt-4">{typeOverview}</div>}+ </>+ )++ return (+ <div className="@container">+ {/* The second row takes any extra height, so a side column taller than the main one can't open a gap under the status. */}+ <div className="grid grid-cols-1 @5xl:grid-cols-[minmax(0,1fr)_22rem] @5xl:grid-rows-[auto_1fr] gap-4 items-start">+ <div className="min-w-0 order-1 @5xl:col-start-1 @5xl:row-start-1">+ <ScannerStatusStrip scannerId={scannerId} /></div>- {/* The histogram fills to match the taller line chart, so the row has no dead space (stretch is the grid default). */}- <div className="min-w-0">{typeOverview}</div>- </div>- )- } else if (scannerType !== 'monitor') {- // Impact only exists for monitors; other types keep their overview at full width.- body = (- <div className="space-y-4">- <ScannerInsightsChart scannerId={scannerId} scannerType={scannerType} />- {typeOverview}- </div>- )- } else {- body = (- <div className="space-y-4">- <ScannerInsightsChart scannerId={scannerId} scannerType={scannerType} />- <div className="grid grid-cols-1 @2xl:grid-cols-2 gap-4">- {typeOverview && <div className="min-w-0">{typeOverview}</div>}- <div className="min-w-0">- <ImpactOverview scannerId={scannerId} />+ {/* Its own column when wide. When stacked it dissolves, so the digest follows the status and self-driving drops below the findings. */}+ <div className="contents @5xl:flex @5xl:flex-col @5xl:gap-4 @5xl:col-start-2 @5xl:row-start-1 @5xl:row-span-2">+ <div className="min-w-0 order-2">+ <ScannerScoutCard scannerId={scannerId} scannerName={scanner.name || ''} />+ </div>+ <div className="min-w-0 order-5 @5xl:order-3">+ <ScannerSetupCard scannerId={scannerId} />+ </div>+ <div className="min-w-0 order-4">+ <ScannerSelfDrivingCard scannerId={scannerId} /></div></div>- </div>- )- }-- return (- <div className="@container flex flex-col gap-4">- <ScannerOverviewFilters scannerId={scannerId} />- {body}- <div className="grid grid-cols-1 @2xl:grid-cols-2 gap-4">- <SelfDrivingOverview scannerId={scannerId} />- <CreditLimitOverview scannerId={scannerId} />+ <div className="@container min-w-0 flex flex-col gap-4 order-3 @5xl:col-start-1 @5xl:row-start-2">+ {firstScanPending ? (+ <FirstScanPendingPanel scannerId={scannerId} />+ ) : (+ <div className="border rounded bg-surface-primary p-4 flex flex-col gap-4">+ <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2 border-b pb-3">+ <div>+ <div className="text-sm font-medium">Findings</div>+ <FindingsCoverage scannerId={scannerId} />+ </div>+ <ScannerOverviewFilters scannerId={scannerId} />+ </div>+ {body}+ </div>+ )}+ </div></div></div>)diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerRecordingFilters.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerRecordingFilters.tsxnew file mode 100644index 000000000000..090eff5c0f10--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerRecordingFilters.tsx@@ -0,0 +1,71 @@+import { IconClock, IconPeople } from '@posthog/icons'+import { LemonTag } from '@posthog/lemon-ui'++import { PropertyFilterButton } from 'lib/components/PropertyFilters/components/PropertyFilterButton'+import { UniversalFilterButton } from 'lib/components/UniversalFilters/UniversalFilterButton'+import { isEntityFilter } from 'lib/components/UniversalFilters/utils'+import { humanFriendlyDurationFilter } from 'scenes/session-recordings/filters/DurationFilter'+import {+ deriveOperand,+ recordingsQueryToUniversalFilters,+} from 'scenes/session-recordings/filters/recordingsQueryConversions'+import { filtersFromUniversalFilterGroups } from 'scenes/session-recordings/utils'++import { RecordingsQuery } from '~/queries/schema/schema-general'+import { FilterLogicalOperator, UniversalFilterValue } from '~/types'++/** One recording filter, read-only. An event or action filter carries its own property filters, which the+ * editable UI keeps behind a popover — there's nothing to open here, so show them alongside the event. */+function ReadonlyFilter({ filter }: { filter: UniversalFilterValue }): JSX.Element {+ const properties = isEntityFilter(filter) ? (filter.properties ?? []) : []+ return (+ <div className="flex flex-wrap items-center gap-1.5">+ <UniversalFilterButton filter={filter} />+ {properties.length > 0 && (+ <>+ <span className="text-xs">where</span>+ {properties.map((property, i) => (+ <PropertyFilterButton key={i} item={property} compact />+ ))}+ </>+ )}+ </div>+ )+}++/** The recording filters a query selects on: events, actions, properties, console logs, duration, test accounts. */+export function ScannerRecordingFilters({ query }: { query: unknown }): JSX.Element {+ // Read every filter dimension, not just top-level properties.+ const universal = recordingsQueryToUniversalFilters((query ?? null) as RecordingsQuery | null)+ const filters = filtersFromUniversalFilterGroups(universal)+ if (filters.length === 0 && universal.duration.length === 0 && !universal.filter_test_accounts) {+ return <span className="text-muted">No filters</span>+ }+ const matchWord = deriveOperand(universal.filter_group) === FilterLogicalOperator.Or ? 'any' : 'all'+ return (+ <div className="flex flex-col gap-2">+ {filters.length > 0 && (+ <div className="flex flex-wrap items-center gap-1.5">+ {filters.length > 1 && <span className="text-xs">Match {matchWord} of</span>}+ {filters.map((filter, i) => (+ <ReadonlyFilter key={i} filter={filter} />+ ))}+ </div>+ )}+ {(universal.duration.length > 0 || universal.filter_test_accounts) && (+ <div className="flex flex-wrap items-center gap-1.5">+ {universal.duration.map((duration, i) => (+ <LemonTag key={i} type="default" icon={<IconClock />}>+ {humanFriendlyDurationFilter(duration, duration.key)}+ </LemonTag>+ ))}+ {universal.filter_test_accounts && (+ <LemonTag type="default" icon={<IconPeople />}>+ No internal/test users+ </LemonTag>+ )}+ </div>+ )}+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerScanTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerScanTab.tsxnew file mode 100644index 000000000000..52fadbbe89e7--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerScanTab.tsx@@ -0,0 +1,49 @@+import { useMountedLogic } from 'kea'++import { LemonCollapse } from '@posthog/lemon-ui'++import { backfillsLogic } from '../backfillsLogic'+import { BackfillDateRange } from './BackfillDateRange'+import { BatchScanRecordings } from './BatchScanRecordings'+import { ScanSingleRecording } from './ScanSingleRecording'++type ScanMode = 'single' | 'batch' | 'backfill'++function PanelHeader({ title, hint }: { title: string; hint: string }): JSX.Element {+ return (+ <span className="flex flex-wrap items-baseline gap-x-2">+ <span className="font-semibold">{title}</span>+ <span className="text-xs text-muted font-normal">{hint}</span>+ </span>+ )+}++export function ScannerScanTab({ scannerId }: { scannerId: string }): JSX.Element {+ // Held for the whole tab, so reopening the backfill panel reuses the list and the default estimate.+ useMountedLogic(backfillsLogic({ scannerId }))+ return (+ <LemonCollapse<ScanMode>+ defaultActiveKey="single"+ panels={[+ {+ key: 'single',+ header: <PanelHeader title="Scan a single recording" hint="By session ID or link" />,+ content: <ScanSingleRecording scannerId={scannerId} />,+ dataAttr: 'vision-run-panel-single',+ },+ {+ key: 'batch',+ header: <PanelHeader title="Batch scan recordings" hint="Pick from a filtered list" />,+ content: <BatchScanRecordings scannerId={scannerId} />,+ dataAttr: 'vision-run-panel-batch',+ },+ {+ key: 'backfill',+ header: <PanelHeader title="Backfill a date range" hint="Every matching recording in a range" />,+ content: <BackfillDateRange scannerId={scannerId} />,+ dataAttr: 'vision-run-panel-backfill',+ },+ ]}+ />+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerScoutCard.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerScoutCard.tsxindex c0068af38123..f507d525cb78 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerScoutCard.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerScoutCard.tsx@@ -7,7 +7,6 @@ import { IconPlus } from '@posthog/icons'import { LemonBanner, LemonButton } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'-import { useResizeObserver } from 'lib/hooks/useResizeObserver'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'@@ -19,10 +18,15 @@ import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { replayScannerLogic } from '../replayScannerLogic'import { ReplayScannerTab } from '../replayScannerSceneLogic'import { scannerScoutLogic } from '../scannerScoutLogic'+import { ClippedPreview } from './ClippedPreview'+import { ScannerScoutReportModal } from './ScannerScoutReportModal'function CardShell({ children }: { children: React.ReactNode }): JSX.Element {return (- <div className="border rounded p-4 flex flex-col gap-2" data-attr="vision-scanner-scout-card">+ <div+ className="border rounded bg-surface-primary p-4 flex flex-col gap-2 min-h-38"+ data-attr="vision-scanner-scout-card"+ >{children}</div>)@@ -40,10 +44,6 @@ function CardHeader({ meta, actions }: { meta?: React.ReactNode; actions?: React)}-/** `max-h-60` in pixels: where a collapsed digest is cut, and so the height above which there is- * more to read. */-const DIGEST_CLIP_PX = 240-// The scanner page's hero: what this scanner's scouts most recently reported. Shows the latest// report when one exists, otherwise the state that gets the user there (add one / paused / quiet).export function ScannerScoutCard({@@ -62,16 +62,12 @@ export function ScannerScoutCard({scoutReportsFailed,scoutConfigsForScanner,latestReportRow,- expanded,latestRun,runningRun,manualRunScoutIds,enrolled,} = useValues(logic)- const { runScoutNow, loadScoutConfigs, loadScoutReports, toggleExpanded } = useActions(logic)- const { ref: digestRef, height: digestHeight } = useResizeObserver()- const overflows = (digestHeight ?? 0) > DIGEST_CLIP_PX- const clipped = overflows && !expanded+ const { runScoutNow, loadScoutConfigs, loadScoutReports, openReport } = useActions(logic)// Running a scout spends credits and pausing one changes what the scanner watches, so every// mutating control here sits behind the scanner's own edit bar, like the digest and alert flows.@@ -84,7 +80,13 @@ export function ScannerScoutCard({if (scoutConfigs === null) {if (scoutConfigsLoading) {- return null+ // Holds the card's place at the height of its common no-scout row, so the overview below doesn't jump when the configs arrive.+ return (+ <CardShell>+ <CardHeader />+ <LemonSkeleton className="h-8 w-full" />+ </CardShell>+ )}return (<CardShell>@@ -179,41 +181,20 @@ export function ScannerScoutCard({</LemonButton></div>) : latestReportRow ? (- <>- {/* The surface stays on the outer element: masking it too would fade the panel's- own background, not just the text it clips. */}- <div className="rounded bg-surface-secondary px-3 py-2">- <div- className={- clipped- ? 'max-h-60 overflow-hidden [mask-image:linear-gradient(to_bottom,black_12rem,transparent_15rem)]'- : undefined- }- >- {/* Measured unclipped (the parent's overflow doesn't shrink it), so the toggle- below appears only when there is really more to read. */}- <div ref={digestRef}>- {/* Agent-written content derived from recordings: render non-PostHog images- as links, not auto-fetched <img>s. */}- <LemonMarkdown className="ScannerSummaryMarkdown text-sm" disableImages>- {latestReportRow.summary || latestReportRow.title || ''}- </LemonMarkdown>- </div>- </div>- </div>- {overflows && (- <div className="border-t pt-2">- <LemonButton- size="xsmall"- type="tertiary"- onClick={toggleExpanded}- data-attr="vision-scanner-scout-expand"- >- {expanded ? 'Show less' : 'Show more'}- </LemonButton>- </div>- )}- </>+ // Boxed like the Configuration card's prompt. Agent-written content derived from recordings:+ // render non-PostHog images as links, not auto-fetched <img>s.+ <div className="bg-surface-secondary border rounded p-2">+ <ClippedPreview+ clip="tall"+ buttonLabel="Show full report"+ onOpenFull={() => openReport(latestReportRow.report_id)}+ dataAttr="vision-scanner-scout-expand"+ >+ <LemonMarkdown className="ScannerSummaryMarkdown text-sm" disableImages>+ {latestReportRow.summary || latestReportRow.title || ''}+ </LemonMarkdown>+ </ClippedPreview>+ </div>) : (<div className="flex flex-wrap items-center justify-between gap-2"><span className="text-sm text-muted">@@ -245,6 +226,7 @@ export function ScannerScoutCard({)}</div>)}+ <ScannerScoutReportModal scannerId={scannerId} scannerName={scannerName} /></CardShell>)}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerSelfDrivingCard.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerSelfDrivingCard.tsxnew file mode 100644index 000000000000..fdda78ce254d--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerSelfDrivingCard.tsx@@ -0,0 +1,199 @@+import { useActions, useValues } from 'kea'++import { IconBolt, IconChevronDown } from '@posthog/icons'+import { LemonButton, LemonMenu, LemonMenuItem, LemonTag } from '@posthog/lemon-ui'++import { IconArrowDown } from 'lib/lemon-ui/icons'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { pluralize } from 'lib/utils/strings'+import { urls } from 'scenes/urls'++import type { ScannerSelfDrivingStatsApi, SelfDrivingPullRequestApi } from '../../generated/api.schemas'+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'+import { replayScannerLogic } from '../replayScannerLogic'+import { scannerSelfDrivingStatsLogic } from '../scannerSelfDrivingStatsLogic'++// Each stage is narrower than the one above it, so the four read as a funnel.+const STAGE_WIDTHS = ['w-full', 'w-11/12', 'w-5/6', 'w-3/4']++const REPORTS_TOOLTIP =+ 'A report can combine signals from several scanners and other sources, so this counts contributions, not sole causes.'++/** `owner/repo#123` for a GitHub pull request URL, or the URL itself for anything else. */+function pullRequestLabel(url: string): string {+ const match = url.match(/github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)/)+ return match ? `${match[1]}#${match[2]}` : url+}++function pullRequestItems(pullRequests: SelfDrivingPullRequestApi[]): LemonMenuItem[] {+ return pullRequests.map((pr) => ({+ label: (+ <span className="flex items-center gap-2">+ {pullRequestLabel(pr.url)}+ {pr.merged && (+ <LemonTag type="completion" size="small">+ Merged+ </LemonTag>+ )}+ </span>+ ),+ to: pr.url,+ targetBlank: true,+ }))+}++function CardShell({ children }: { children: React.ReactNode }): JSX.Element {+ return (+ <div className="border rounded bg-surface-primary p-4 flex flex-col gap-3" data-attr="vision-self-driving-card">+ <div className="border-b border-primary pb-2">+ <span className="text-sm font-medium">Self-driving</span>+ </div>+ {children}+ </div>+ )+}++function FunnelStage({+ index,+ count,+ label,+ items,+ emptyReason,+ tooltip,+}: {+ index: number+ count: number+ label: string+ items?: LemonMenuItem[]+ emptyReason?: string+ tooltip?: string+}): JSX.Element {+ const content = (+ <span className="flex w-full items-baseline justify-between gap-2">+ <span>{label}</span>+ <span className="font-semibold tabular-nums">{count.toLocaleString()}</span>+ </span>+ )+ return (+ <div className={`${STAGE_WIDTHS[index]} mx-auto`}>+ {items ? (+ <LemonMenu items={items} placement="bottom-end">+ <LemonButton+ type="secondary"+ size="small"+ fullWidth+ sideIcon={<IconChevronDown />}+ tooltip={tooltip}+ disabledReason={count === 0 ? emptyReason : undefined}+ >+ {content}+ </LemonButton>+ </LemonMenu>+ ) : (+ <div className="border rounded px-2 py-1 text-sm">{content}</div>+ )}+ </div>+ )+}++function FunnelArrow(): JSX.Element {+ return <IconArrowDown className="mx-auto text-muted text-sm" aria-hidden />+}++function Funnel({ stats }: { stats: ScannerSelfDrivingStatsApi }): JSX.Element {+ const reportItems: LemonMenuItem[] = stats.reports.map((report) => ({+ label: report.title || 'Untitled report',+ to: urls.inboxReport('reports', report.id),+ }))+ return (+ <div className="flex flex-col gap-0.5" data-attr="vision-self-driving-funnel">+ <FunnelStage index={0} count={stats.signals_emitted} label="Signals emitted" />+ <FunnelArrow />+ <FunnelStage+ index={1}+ count={stats.reports_contributed}+ label={pluralize(stats.reports_contributed, 'Report', 'Reports', false)}+ items={reportItems}+ emptyReason="No reports include this scanner's signals yet"+ tooltip={REPORTS_TOOLTIP}+ />+ <FunnelArrow />+ <FunnelStage+ index={2}+ count={stats.prs_opened}+ label="PRs opened"+ items={pullRequestItems(stats.pull_requests)}+ emptyReason="No pull requests opened yet"+ />+ <FunnelArrow />+ <FunnelStage+ index={3}+ count={stats.prs_merged}+ label="PRs merged"+ items={pullRequestItems(stats.pull_requests.filter((pr) => pr.merged))}+ emptyReason="No pull requests merged yet"+ />+ </div>+ )+}++export function ScannerSelfDrivingCard({ scannerId }: { scannerId: string }): JSX.Element {+ const { scanner, turningOnSelfDriving } = useValues(replayScannerLogic({ id: scannerId }))+ const { turnOnSelfDriving } = useActions(replayScannerLogic({ id: scannerId }))+ const { selfDrivingStats, selfDrivingStatsLoading } = useValues(scannerSelfDrivingStatsLogic({ scannerId }))++ // Unresolved data renders as loading, never as the off state or the empty state.+ if (!scanner || (selfDrivingStatsLoading && !selfDrivingStats)) {+ return (+ <CardShell>+ <LemonSkeleton className="h-24 w-full" />+ </CardShell>+ )+ }+ const on = scanner.emits_signals+ // Signals sent before self-driving was turned off still count, so the off copy only+ // replaces the funnel when there is nothing to show.+ if (!on && (!selfDrivingStats || selfDrivingStats.signals_emitted === 0)) {+ return (+ <CardShell>+ <div className="flex flex-wrap items-center justify-between gap-2">+ <span className="text-sm text-muted">+ Send this scanner's findings to Signals, where agents investigate them and open pull requests.+ </span>+ <LemonButton+ type="primary"+ size="small"+ icon={<IconBolt />}+ onClick={() => turnOnSelfDriving()}+ loading={turningOnSelfDriving}+ disabledReason={getReplayVisionEditDisabledReason(scanner.user_access_level) ?? undefined}+ data-attr="vision-self-driving-turn-on"+ >+ Turn on self-driving+ </LemonButton>+ </div>+ </CardShell>+ )+ }+ if (!selfDrivingStats) {+ return (+ <CardShell>+ <div className="text-sm text-muted">Couldn't load what self-driving did with this scanner.</div>+ </CardShell>+ )+ }+ if (selfDrivingStats.signals_emitted === 0) {+ return (+ <CardShell>+ <div className="text-sm text-muted">+ No signals yet. Findings go to Signals as sessions are scanned.+ </div>+ </CardShell>+ )+ }+ return (+ <CardShell>+ <Funnel stats={selfDrivingStats} />+ </CardShell>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsxnew file mode 100644index 000000000000..96248542503b--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx@@ -0,0 +1,178 @@+import { useValues } from 'kea'+import { useState } from 'react'++import { LemonButton, LemonModal, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { FEATURE_FLAGS } from 'lib/constants'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { percentage } from 'lib/utils/numbers'+import { urls } from 'scenes/urls'++import { LabeledRow } from '../../components/LabeledRow'+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'+import { formatCreditCount } from '../../utils/credits'+import { replayScannerLogic } from '../replayScannerLogic'+import { SCANNER_TYPE_OPTIONS, modelName, modelNamingVariant, scannerTypeLabel } from '../types'+import { ClippedPreview } from './ClippedPreview'+import { ScannerRecordingFilters } from './ScannerRecordingFilters'++function EnabledText({ enabled }: { enabled: boolean }): JSX.Element {+ return <span>{enabled ? 'Enabled' : 'Disabled'}</span>+}++export function ScannerSetupCard({ scannerId }: { scannerId: string }): JSX.Element | null {+ const { scanner, experimentContext } = useValues(replayScannerLogic({ id: scannerId }))+ const { featureFlags } = useValues(featureFlagLogic)+ const [promptOpen, setPromptOpen] = useState(false)+ if (!scanner) {+ return null+ }+ const namingVariant = modelNamingVariant(featureFlags[FEATURE_FLAGS.REPLAY_VISION_MODEL_TIER_NAMING_EXPERIMENT])+ const config = scanner.scanner_config+ const targeting = scanner.experiment_targeting++ return (+ <div+ className="border rounded bg-surface-primary p-4 flex flex-col gap-3"+ data-attr="vision-scanner-setup-card"+ >+ <div className="flex items-center justify-between gap-2 border-b border-primary pb-2">+ <span className="text-sm font-medium">Configuration</span>+ <LemonButton+ size="xsmall"+ type="secondary"+ to={urls.replayVisionScannerConfigure(scannerId)}+ disabledReason={getReplayVisionEditDisabledReason(scanner.user_access_level)}+ data-attr="vision-setup-edit"+ >+ Edit scanner+ </LemonButton>+ </div>++ <div className="flex flex-col gap-0.5">+ <span className="text-sm font-semibold">+ <Tooltip+ title={+ SCANNER_TYPE_OPTIONS.find((option) => option.value === scanner.scanner_type)?.description+ }+ >+ <span className="underline decoration-dotted underline-offset-2 cursor-help">+ {scannerTypeLabel(scanner.scanner_type)}+ </span>+ </Tooltip>{' '}+ · {modelName(scanner.model, namingVariant)}+ </span>+ {scanner.credits_per_observation != null && (+ <span className="text-xs text-muted">+ {formatCreditCount(scanner.credits_per_observation)} per scan+ </span>+ )}+ </div>++ <LabeledRow label="Prompt">+ {config.prompt ? (+ <div className="bg-surface-secondary border rounded p-2">+ <ClippedPreview+ clip="short"+ buttonLabel="Show full prompt"+ dataAttr="vision-setup-show-prompt"+ onOpenFull={() => setPromptOpen(true)}+ >+ <div className="whitespace-pre-wrap text-sm">{config.prompt}</div>+ </ClippedPreview>+ <LemonModal isOpen={promptOpen} onClose={() => setPromptOpen(false)} title="Prompt" width={720}>+ <div className="whitespace-pre-wrap font-mono text-sm bg-surface-tertiary border rounded p-3">+ {config.prompt}+ </div>+ </LemonModal>+ </div>+ ) : (+ <span className="text-muted">—</span>+ )}+ </LabeledRow>++ {scanner.scanner_type === 'monitor' && (+ <LabeledRow+ label="Inconclusive verdicts"+ tooltip="When enabled, the model can answer 'inconclusive' instead of yes or no when a recording doesn't show enough to decide."+ >+ <EnabledText enabled={!!scanner.scanner_config.allow_inconclusive} />+ </LabeledRow>+ )}+ {scanner.scanner_type === 'classifier' && (+ <>+ <LabeledRow label="Categories">+ {scanner.scanner_config.tags.length ? (+ <div className="flex flex-wrap gap-1">+ {scanner.scanner_config.tags.map((tag) => (+ <LemonTag key={tag} type="option">+ {tag}+ </LemonTag>+ ))}+ </div>+ ) : (+ <span className="text-muted">—</span>+ )}+ </LabeledRow>+ <LabeledRow label="Multiple categories per recording">+ <EnabledText enabled={!!scanner.scanner_config.multi_label} />+ </LabeledRow>+ <LabeledRow label="Freeform categories">+ <EnabledText enabled={!!scanner.scanner_config.allow_freeform_tags} />+ </LabeledRow>+ </>+ )}+ {scanner.scanner_type === 'scorer' && (+ <LabeledRow label="Scale">+ {scanner.scanner_config.scale.min} to {scanner.scanner_config.scale.max}+ {scanner.scanner_config.scale.label ? ` (${scanner.scanner_config.scale.label})` : ''}+ </LabeledRow>+ )}+ {scanner.scanner_type === 'summarizer' && scanner.scanner_config.length && (+ <LabeledRow label="Summary length">+ <span className="capitalize">{scanner.scanner_config.length}</span>+ </LabeledRow>+ )}++ <LabeledRow label="Recordings">+ Scans {percentage(scanner.sampling_rate ?? 0, 1)} of matching recordings+ </LabeledRow>+ {targeting && (+ <LabeledRow label="Experiment">+ {/* The name loads with the scanner; until then, or for an experiment the viewer can't open, the ID stands in. */}+ <Link to={urls.experiment(targeting.experiment_id)}>+ {experimentContext?.experiment.id === targeting.experiment_id+ ? experimentContext.experiment.name+ : `Experiment ${targeting.experiment_id}`}+ </Link>+ <span className="text-muted">+ {' · '}+ {targeting.variant ? `${targeting.variant} variant` : 'every variant'}+ </span>+ </LabeledRow>+ )}+ <LabeledRow label="Filters">+ <div className="[&_.PropertyFilterButton]:h-6 [&_.PropertyFilterButton]:text-xs [&_.UniversalFilterButton]:h-6 [&_.UniversalFilterButton]:text-xs">+ <ScannerRecordingFilters query={scanner.query} />+ </div>+ </LabeledRow>++ {(scanner.created_by || scanner.updated_at) && (+ <div className="border-t pt-2 flex flex-col gap-1 text-xs text-muted">+ {scanner.created_by && (+ <span className="flex items-center gap-1.5">+ Created by <ProfilePicture user={scanner.created_by} size="xs" showName />+ </span>+ )}+ {scanner.updated_at && (+ <span>+ Updated <TZLabel time={scanner.updated_at} />+ </span>+ )}+ </div>+ )}+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerStatusStrip.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerStatusStrip.tsxnew file mode 100644index 000000000000..59f77d15b4d6--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerStatusStrip.tsx@@ -0,0 +1,215 @@+import { useActions, useValues } from 'kea'++import { LemonSwitch, Link } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'+import { percentage } from 'lib/utils/numbers'+import { pluralize } from 'lib/utils/strings'+import { urls } from 'scenes/urls'++import { visionQuotaLogic } from '../../logics/visionQuotaLogic'+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'+import { formatCreditsRange } from '../../utils/credits'+import { quotaBannerState } from '../../utils/quotaProjection'+import { replayScannerLogic } from '../replayScannerLogic'+import { scanDrought } from '../scanDrought'+import { LIMIT_REACHED_TOOLTIP } from '../scannerCopy'+import { ScannerStatus, SWEEP_INTERVAL_MINUTES, scannerStatus, spendAgainstLimit } from '../scannerStatus'++type StatusTone = 'success' | 'warning' | 'danger' | 'muted'++// Green and yellow mean the scanner is still sweeping, so their dot pulses. Tailwind's own pulse runs at 2s,+// which reads as urgent, so this slows it to 3s; reduced-motion users get a still dot.+const ACTIVE_PULSE = 'animate-[pulse_3s_cubic-bezier(0.4,0,0.6,1)_infinite] motion-reduce:animate-none'++const TONE_DOT: Record<StatusTone, string> = {+ success: 'bg-success',+ warning: 'bg-warning',+ danger: 'bg-danger',+ muted: 'bg-muted',+}++function formatInterval(minutes: number): string {+ // The throttle factor is any integer, so only whole hours read better in hours.+ if (minutes < 60 || minutes % 60 !== 0) {+ return pluralize(minutes, 'minute')+ }+ return minutes === 60 ? 'hour' : pluralize(minutes / 60, 'hour')+}++function statusCopy(+ status: ScannerStatus,+ resetsOn: string | null+): { label: string; tone: StatusTone; detail: React.ReactNode } {+ switch (status.kind) {+ case 'off':+ return {+ label: 'Off',+ tone: 'muted',+ detail:+ status.reason === 'no_sampling'+ ? 'Sampling is set to 0%, so no recordings are scanned.'+ : "This scanner doesn't scan new recordings.",+ }+ case 'limit_reached':+ return { label: 'Stopped', tone: 'danger', detail: LIMIT_REACHED_TOOLTIP }+ case 'quota_exhausted':+ return {+ label: 'Stopped',+ tone: 'danger',+ detail: `Your organization's Replay Vision credits are used up${resetsOn ? ` until ${resetsOn}` : ''}.`,+ }+ case 'starting':+ return {+ label: 'Starting',+ tone: 'warning',+ detail: 'The first scan is running. Results usually appear within 15 minutes.',+ }+ case 'delayed':+ return {+ label: 'Delayed',+ tone: 'warning',+ detail: (+ <>+ Last checked for new recordings <TZLabel time={status.lastCheckedAt} />. Checks resume on their+ own. If this lasts, contact support.+ </>+ ),+ }+ case 'no_matches':+ return {+ label: 'No matches',+ tone: 'warning',+ detail: `${+ status.drought.everScanned+ ? 'Nothing has matched since the last configuration change.'+ : 'Nothing has matched yet.'+ } The filters may match no recordings${+ status.drought.samplingRate < 1+ ? `, or ${percentage(status.drought.samplingRate)} sampling skipped them`+ : ''+ }.`,+ }+ case 'throttled':+ return {+ label: 'Throttled',+ tone: 'warning',+ detail: (+ <>+ Its filters read a lot of data, so it checks for new recordings every{' '}+ {formatInterval(status.intervalMinutes)} instead of every{' '}+ {formatInterval(SWEEP_INTERVAL_MINUTES)}. Last checked <TZLabel time={status.lastCheckedAt} />.+ </>+ ),+ }+ case 'running':+ return {+ label: 'Running',+ tone: 'success',+ detail: (+ <>+ Checks for new recordings every {formatInterval(status.intervalMinutes)}. Last checked{' '}+ <TZLabel time={status.lastCheckedAt} />.+ </>+ ),+ }+ }+}++export function ScannerStatusStrip({ scannerId }: { scannerId: string }): JSX.Element | null {+ const { scanner, observationStatsApi, togglingEnabled } = useValues(replayScannerLogic({ id: scannerId }))+ const { toggleEnabled } = useActions(replayScannerLogic({ id: scannerId }))+ const { quota } = useValues(visionQuotaLogic)+ if (!scanner) {+ return null+ }+ const quotaState = quotaBannerState(quota)+ const status = scannerStatus(scanner, {+ quotaExhausted: quotaState.kind === 'exhausted',+ drought: scanDrought(scanner, observationStatsApi?.labels.version_markers ?? null, new Date()),+ })+ const { label, tone, detail } = statusCopy(status, quotaState.kind ? quotaState.resetsOn : null)+ const editDisabledReason = getReplayVisionEditDisabledReason(scanner.user_access_level)+ const spend = spendAgainstLimit(scanner)++ return (+ // min-h-38 matches the empty scout card beside it, so the two line up when there is no report yet.+ <div+ className="@container border rounded bg-surface-primary p-4 flex flex-col gap-3 min-h-38"+ data-attr="vision-scanner-status-strip"+ data-status={status.kind}+ >+ <div className="flex items-center justify-between gap-2 border-b border-primary pb-2">+ <span className="text-sm font-medium">Scanner status</span>+ <LemonSwitch+ checked={scanner.enabled}+ onChange={() => toggleEnabled()}+ loading={togglingEnabled}+ disabledReason={editDisabledReason}+ label="Enabled"+ size="small"+ data-attr="vision-scanner-toggle-enabled"+ data-ph-capture-attribute-scanner-type={scanner.scanner_type}+ data-ph-capture-attribute-will-be-enabled={!scanner.enabled}+ />+ </div>+ <div className="grid grid-cols-1 @2xl:grid-cols-2 gap-x-8 gap-y-4 items-start">+ <div className="min-w-0 flex flex-col gap-1">+ <div className="flex items-center gap-2">+ <span+ className={`size-2 rounded-full shrink-0 ${TONE_DOT[tone]} ${+ tone === 'success' || tone === 'warning' ? ACTIVE_PULSE : ''+ }`}+ aria-hidden+ />+ <span className="text-sm font-semibold">{label}</span>+ </div>+ <div className="text-xs text-muted pl-4">+ {detail}+ {status.kind === 'no_matches' && (+ <>+ {' '}+ <Link+ to={urls.replayVisionScannerTriggers(scannerId)}+ data-attr="vision-scanner-status-review-filters"+ >+ Review filters+ </Link>+ </>+ )}+ </div>+ </div>+ <div className="min-w-0 flex flex-col gap-1">+ <div className="flex items-center justify-between gap-2 text-sm">+ <span className="font-semibold">Spending limit for this scanner</span>+ {spend && <span className="text-xs text-muted tabular-nums">{spend.usedPct}%</span>}+ </div>+ {spend ? (+ <>+ <LemonProgress+ percent={spend.usedPct}+ strokeColor={scanner.limit_reached ? 'var(--danger)' : undefined}+ />+ <span className="text-xs text-muted tabular-nums">+ {formatCreditsRange(spend.used, spend.limit)} used this billing period+ </span>+ </>+ ) : (+ <span className="text-xs text-muted">+ No limit set. This scanner keeps scanning until your organization's credits run out.{' '}+ {!editDisabledReason && (+ <Link+ to={urls.replayVisionScannerConfigure(scannerId)}+ data-attr="vision-scanner-status-set-limit"+ >+ Set a limit+ </Link>+ )}+ </span>+ )}+ </div>+ </div>+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex e91bb2218c7e..210473407553 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -1149,6 +1149,37 @@ describe('replayScannerLogic', () => {expect(patchedBody.credit_limit).toBe(100)expect(patchedBody).not.toHaveProperty('credit_limit_enabled')})++ it('turns on self-driving with a patch of that one field and keeps the version the save bumped', async () => {+ let patchedBody: any+ useMocks({+ patch: {+ '/api/projects/:team/vision/scanners/:id/': async ({ request }: { request: Request }) => {+ patchedBody = await request.json()+ return [+ 200,+ {+ ...loadedScanner,+ emits_signals: true,+ scanner_version: 7,+ updated_at: '2026-09-24T10:00:00Z',+ },+ ]+ },+ },+ })+ await expectLogic(editLogic, () => editLogic.actions.loadScanner()).toFinishAllListeners()+ await expectLogic(editLogic, () => editLogic.actions.turnOnSelfDriving()).toDispatchActions([+ 'turnOnSelfDrivingSuccess',+ ])+ expect(patchedBody).toEqual({ emits_signals: true })+ expect(editLogic.values.scanner).toMatchObject({ emits_signals: true, scanner_version: 7 })+ expect(editLogic.values.originalScanner).toMatchObject({+ emits_signals: true,+ scanner_version: 7,+ updated_at: '2026-09-24T10:00:00Z',+ })+ })})describe('buildObservationListParams', () => {diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex 221a85a9fdd3..9a464f69c33b 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -106,6 +106,12 @@ import {scannerToPatchedApiBody,} from './types'+/** Narrows a cohort to one monitor verdict or one classifier category; empty means the type's default. */+export interface AffectedCohortQualifier {+ verdict?: ObservationVerdictValue+ tag?: string+}+export interface ReplayScannerLogicProps {id: string}@@ -402,7 +408,7 @@ export interface replayScannerLogicValues {originalScanner: ScannerFormValues | nullpollUntil: numberretryingObservationIds: string[]- savingCohortTag: string | null+ savingCohortKey: string | nullscanner: ScannerFormValuesscannerAllErrors: Record<string, any>scannerChanged: boolean@@ -424,6 +430,7 @@ export interface replayScannerLogicValues {tagSuggestionsLoading: booleantogglingEnabled: booleantriggeringOnDemandObservation: boolean+ turningOnSelfDriving: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -588,8 +595,12 @@ export interface replayScannerLogicActions {retryObservationSuccess: (observationId: string) => {observationId: string}- saveAffectedCohort: (tag?: string) => {- tag: string | undefined+ saveAffectedCohort: (+ windowDays: number,+ qualifier?: AffectedCohortQualifier+ ) => {+ qualifier: AffectedCohortQualifier+ windowDays: number}saveAffectedCohortFailure: (error: string,@@ -603,14 +614,16 @@ export interface replayScannerLogicActions {cohort_id: number} | null,payload?: {- tag: string | undefined+ qualifier: AffectedCohortQualifier+ windowDays: number}) => {affectedCohort: {cohort_id: number} | nullpayload?: {- tag: string | undefined+ qualifier: AffectedCohortQualifier+ windowDays: number}}scannerSaved: (scanner: ScannerFormValues) => {@@ -742,6 +755,19 @@ export interface replayScannerLogicActions {triggerOnDemandObservationSuccess: () => {value: true}+ turnOnSelfDriving: () => {+ value: true+ }+ turnOnSelfDrivingFailure: () => {+ value: true+ }+ turnOnSelfDrivingSuccess: (+ scannerVersion: number,+ updatedAt: string+ ) => {+ scannerVersion: number+ updatedAt: string+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -815,7 +841,10 @@ export const replayScannerLogic = kea<replayScannerLogicType>([setExperimentVariant: (variantKey: string | null) => ({ variantKey }),detachExperimentContext: true,rebuildExperimentContext: true,- saveAffectedCohort: (tag?: string) => ({ tag }),+ saveAffectedCohort: (windowDays: number, qualifier: AffectedCohortQualifier = {}) => ({+ windowDays,+ qualifier,+ }),setScannerType: (scannerType: ScannerType) => ({ scannerType }),startFromTemplate: (templateKey: string | null) => ({ templateKey }),discardScannerDraft: true,@@ -841,6 +870,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([toggleEnabled: true,toggleEnabledSuccess: (enabled: boolean) => ({ enabled }),toggleEnabledFailure: true,+ turnOnSelfDriving: true,+ turnOnSelfDrivingSuccess: (scannerVersion: number, updatedAt: string) => ({ scannerVersion, updatedAt }),+ turnOnSelfDrivingFailure: true,setObservationStatusFilter: (values: ObservationStatusValue[]) => ({ values }),setObservationTriggeredByFilter: (values: ObservationTriggeredByValue[]) => ({ values }),setObservationVerdictFilter: (values: ObservationVerdictValue[]) => ({ values }),@@ -976,7 +1008,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([lemonToast.success('Scanner created. First scan in progress.', {button: {label: 'Scan a recording now',- action: () => router.actions.push(`${urls.replayVision(response.id)}?tab=on-demand`),+ action: () => router.actions.push(`${urls.replayVision(response.id)}?tab=run`),dataAttr: 'vision-scanner-created-scan-now',},})@@ -1005,17 +1037,16 @@ export const replayScannerLogic = kea<replayScannerLogicType>([affectedCohort: [null as { cohort_id: number } | null,{- saveAffectedCohort: async ({ tag }) => {+ saveAffectedCohort: async ({ windowDays, qualifier }) => {const teamId = teamLogic.values.currentTeamIdif (!teamId || props.id === 'new') {return values.affectedCohort}try {- const response = await visionScannersAffectedCohortCreate(- String(teamId),- props.id,- tag ? { tag } : {}- )+ const response = await visionScannersAffectedCohortCreate(String(teamId), props.id, {+ window_days: windowDays,+ ...qualifier,+ })lemonToast.success(`Cohort "${response.name}" created with ${response.users_in_cohort.toLocaleString()} ${response.users_in_cohort === 1 ? 'person' : 'people'@@ -1125,11 +1156,10 @@ export const replayScannerLogic = kea<replayScannerLogicType>([(templateKey ? 'template' : 'scratch') as ScannerCreationMethodEnumApi,},],- // Which tag's cohort is being created, so tag rows can show a per-row spinner.- savingCohortTag: [+ savingCohortKey: [null as string | null,{- saveAffectedCohort: (_, { tag }) => tag ?? null,+ saveAffectedCohort: (_, { qualifier }) => qualifier.verdict ?? qualifier.tag ?? null,saveAffectedCohortSuccess: () => null,saveAffectedCohortFailure: () => null,},@@ -1154,6 +1184,11 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// Keyed on the real save, not submitScannerSuccess — kea-forms fires that on the no-API advance path too.scannerSaved: (_, { scanner }) => scanner,toggleEnabledSuccess: (state, { enabled }) => (state ? { ...state, enabled } : state),+ // Self-driving changes the prompt the model gets, so the backend bumps the version with it.+ turnOnSelfDrivingSuccess: (state, { scannerVersion, updatedAt }) =>+ state+ ? { ...state, emits_signals: true, scanner_version: scannerVersion, updated_at: updatedAt }+ : state,},],togglingEnabled: [@@ -1164,6 +1199,14 @@ export const replayScannerLogic = kea<replayScannerLogicType>([toggleEnabledFailure: () => false,},],+ turningOnSelfDriving: [+ false,+ {+ turnOnSelfDriving: () => true,+ turnOnSelfDrivingSuccess: () => false,+ turnOnSelfDrivingFailure: () => false,+ },+ ],triggeringOnDemandObservation: [false,{@@ -2181,6 +2224,27 @@ export const replayScannerLogic = kea<replayScannerLogicType>([}},+ turnOnSelfDriving: async () => {+ const teamId = teamLogic.values.currentTeamId+ if (props.id === 'new' || !values.scanner || !teamId) {+ actions.turnOnSelfDrivingFailure()+ return+ }+ try {+ const response = await visionScannersPartialUpdate(String(teamId), props.id, {+ emits_signals: true,+ })+ actions.setScannerValue('emits_signals', true)+ actions.setScannerValue('scanner_version', response.scanner_version)+ actions.setScannerValue('updated_at', response.updated_at)+ actions.turnOnSelfDrivingSuccess(response.scanner_version, response.updated_at)+ lemonToast.success('Self-driving turned on')+ } catch (error: any) {+ lemonToast.error(`Failed to turn on self-driving${error.detail ? `: ${error.detail}` : ''}`)+ actions.turnOnSelfDrivingFailure()+ }+ },+triggerOnDemandObservation: async ({ sessionId, silent }) => {if (props.id === 'new') {actions.triggerOnDemandObservationFailure()diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.test.tsindex bf0b0993bf4f..304e1b20dce8 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.test.ts@@ -4,7 +4,7 @@ import { urls } from 'scenes/urls'import { initKeaTests } from '~/test/init'-import { replayScannerSceneLogic } from './replayScannerSceneLogic'+import { ReplayScannerTab, replayScannerSceneLogic } from './replayScannerSceneLogic'describe('replayScannerSceneLogic', () => {beforeEach(() => {@@ -32,4 +32,17 @@ describe('replayScannerSceneLogic', () => {logic.unmount()})++ it.each([+ ['on-demand', ReplayScannerTab.Run],+ ['backfills', ReplayScannerTab.Run],+ ['configuration', ReplayScannerTab.Overview],+ ])('an old %s tab link opens the tab it was merged into', (oldTab, expected) => {+ const logic = replayScannerSceneLogic()+ logic.mount()+ router.actions.push(urls.replayVision('scanner-9'), { tab: oldTab })++ expect(logic.values.activeTab).toBe(expected)+ logic.unmount()+ })})diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.tsindex 15f8a2f50273..4f4292ff3e01 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts@@ -12,9 +12,7 @@ export enum ReplayScannerTab {Observations = 'observations',Search = 'search',Calibration = 'calibration',- OnDemand = 'on-demand',- Backfills = 'backfills',- Configuration = 'configuration',+ Run = 'run',Scouts = 'scouts',Alerts = 'alerts',}@@ -23,7 +21,17 @@ const SCANNER_TABS: ReplayScannerTab[] = Object.values(ReplayScannerTab)// The at-a-glance Overview (charts + stat panels) is the landing tab; Observations is the drill-down list.const DEFAULT_TAB: ReplayScannerTab = ReplayScannerTab.Overview+// Keys of tabs that were merged into others, so links and bookmarks made before still open the right place.+const TAB_ALIASES: Record<string, ReplayScannerTab> = {+ 'on-demand': ReplayScannerTab.Run,+ backfills: ReplayScannerTab.Run,+ configuration: ReplayScannerTab.Overview,+}+function parseTab(tab: unknown): ReplayScannerTab {+ if (typeof tab === 'string' && Object.hasOwn(TAB_ALIASES, tab)) {+ return TAB_ALIASES[tab]+ }return SCANNER_TABS.includes(tab as ReplayScannerTab) ? (tab as ReplayScannerTab) : DEFAULT_TAB}diff --git a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.tsindex 646b9a7cab84..4f051cfecd0c 100644--- a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts@@ -218,9 +218,9 @@ export const scannerEditorSceneLogic = kea<scannerEditorSceneLogicType>([}return crumbs}- // Editing an existing scanner: surface the detail page (on its Configuration tab, where the- // Edit button lives) as an intermediate crumb so the back arrow returns there, not to the list.- crumbs.push(scannerBreadcrumb(scannerId, null, { tab: 'configuration' }), {+ // Editing an existing scanner: surface the detail page (its Overview, where the Setup card's+ // Edit link lives) as an intermediate crumb so the back arrow returns there, not to the list.+ crumbs.push(scannerBreadcrumb(scannerId, null, { tab: 'overview' }), {key: `scanner-${scannerId}-edit`,name: 'Edit',path: urls.replayVisionScannerConfigure(scannerId),diff --git a/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.test.tsindex 115227f3970c..ef4e68fd43cc 100644--- a/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.test.ts@@ -19,15 +19,13 @@ const STATS = {scorer: null,}-const IMPACT = { affected_sessions: 0, affected_users: 0, sessions_without_user: 0, window_days: 14 }-describe('scannerOverviewLogic', () => {let statsRequests: string[]- let impactRequests: string[]+ let cohortBodies: Record<string, unknown>[]beforeEach(() => {statsRequests = []- impactRequests = []+ cohortBodies = []useMocks({get: {'/api/projects/:team/vision/scanners/:id/': {@@ -39,15 +37,17 @@ describe('scannerOverviewLogic', () => {enabled: true,},'/api/projects/:team/vision/scanners/:id/observations/': { results: [], count: 0 },- '/api/projects/:team/vision/scanners/:id/impact/': ({ request }) => {- impactRequests.push(request.url)- return [200, IMPACT]- },'/api/projects/:team/vision/scanners/:id/observations/stats/': ({ request }) => {statsRequests.push(request.url)return [200, STATS]},},+ post: {+ '/api/projects/:team/vision/scanners/:id/affected_cohort/': async ({ request }) => {+ cohortBodies.push((await request.json()) as Record<string, unknown>)+ return [201, { cohort_id: 1, name: 'c', users_in_cohort: 1, window_days: 7 }]+ },+ },})initKeaTests()})@@ -92,16 +92,40 @@ describe('scannerOverviewLogic', () => {expect(url.searchParams.get('tags')).toBe('checkout')})- it('reloads impact with a window derived from the date range, clamped to the endpoint max', async () => {+ it('saves cohorts over a window derived from the date range, clamped to the endpoint max', async () => {await expectLogic(logic).toFinishAllListeners()- impactRequests = []+ // A cohort over a different window would hold users the panel never counted.await expectLogic(logic, () => logic.actions.setOverviewDateRange('-7d', null)).toFinishAllListeners()- expect(new URL(impactRequests[impactRequests.length - 1]).searchParams.get('window_days')).toBe('7')+ await expectLogic(logic, () => logic.actions.saveCohort({ verdict: 'no' })).toFinishAllListeners()// A range past the endpoint's 90-day cap must clamp, not send an out-of-range value the API rejects.await expectLogic(logic, () => logic.actions.setOverviewDateRange('-180d', null)).toFinishAllListeners()- expect(new URL(impactRequests[impactRequests.length - 1]).searchParams.get('window_days')).toBe('90')+ await expectLogic(logic, () => logic.actions.saveCohort({ tag: 'checkout' })).toFinishAllListeners()++ expect(cohortBodies).toEqual([+ { window_days: 7, verdict: 'no' },+ { window_days: 90, tag: 'checkout' },+ ])+ })++ it.each([+ ['a range ending today', '-7d', null, null],+ [+ 'a range ending yesterday',+ '-14d',+ '-1d',+ 'Cohorts cover the most recent days. Pick a date range that ends today to save one.',+ ],+ [+ 'a fixed range that ended weeks ago',+ '2020-01-01',+ '2020-01-14',+ 'Cohorts cover the most recent days. Pick a date range that ends today to save one.',+ ],+ ])('with %s, saving a cohort is blocked only when the range ended in the past', (_name, from, to, expected) => {+ logic.actions.setOverviewDateRange(from, to)+ expect(logic.values.cohortDisabledReason).toBe(expected)})it('clearOverviewFilters resets the date back to the default, not null', async () => {@@ -136,40 +160,6 @@ describe('scannerOverviewLogic', () => {expect(router.values.location.pathname).toBe(before)})})-- describe('creditLimitStats', () => {- it('is null when the scanner has no limit, so callers render no panel instead of "0% of 0"', async () => {- await expectLogic(logic).toFinishAllListeners()- expect(logic.values.creditLimitStats).toBeNull()- })-- it.each([- { used: 200, limit: 1000, expectedPct: 20, expectedReached: false },- { used: 1000, limit: 1000, expectedPct: 100, expectedReached: true },- { used: 1200, limit: 1000, expectedPct: 100, expectedReached: true },- // The server reports reached as soon as what's left can't cover one more scan, so this- // must come from the API and not be re-derived from usedPct.- { used: 990, limit: 1000, expectedPct: 99, expectedReached: true },- ])(- 'derives usedPct $expectedPct and limitReached $expectedReached from used=$used, limit=$limit',- async ({ used, limit, expectedPct, expectedReached }) => {- await expectLogic(logic, () =>- logic.actions.loadScannerSuccess({- ...logic.values.scanner,- credit_limit: limit,- credits_used_against_limit: used,- limit_reached: expectedReached,- })- ).toFinishAllListeners()- expect(logic.values.creditLimitStats).toEqual({- limit,- used,- usedPct: expectedPct,- limitReached: expectedReached,- })- }- )- })})describe('observationsDrilldownSearchParams', () => {@@ -288,13 +278,10 @@ describe('scannerOverviewLogic', () => {await jest.advanceTimersByTimeAsync(1_000)expect(freshLogic.values.firstScanPending).toBe(true)- // Pending arms a background reload on the calmer first-scan interval. Each tick refreshes- // stats and the watermark only; reloading impact per tick would triple the request count.+ // Pending arms a background reload on the calmer first-scan interval.const before = statsRequests.length- const impactBefore = impactRequests.lengthawait jest.advanceTimersByTimeAsync(16_000)expect(statsRequests.length).toBe(before + 1)- expect(impactRequests.length).toBe(impactBefore)// Once observations settle, the pending state dissolves and polling stops.statsBody = SETTLED_STATSdiff --git a/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.tsindex 61f1866c7a16..67db86f2dcd6 100644--- a/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.ts@@ -12,26 +12,22 @@ import {reducers,selectors,} from 'kea'-import { loaders } from 'kea-loaders'import { router } from 'kea-router'import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { dateStringToDayJs } from 'lib/utils/dateFilters'import { isNullBreakdown, isOtherBreakdown } from 'scenes/insights/utils'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { IntervalType } from '~/types'-import {- visionScannersImpactRetrieve,- visionScannersObservationsStatsRetrieve,- visionScannersRetrieve,-} from '../generated/api'-import type { ObservationStatsApi, ScannerImpactApi } from '../generated/api.schemas'+import { visionScannersObservationsStatsRetrieve, visionScannersRetrieve } from '../generated/api'+import type { ObservationStatsApi } from '../generated/api.schemas'import { scheduleObservationPoll } from '../logics/observationPolling'import { replayScannerLogic } from './replayScannerLogic'-import type { ObservationVerdictValue } from './replayScannerLogic'+import type { AffectedCohortQualifier, ObservationVerdictValue } from './replayScannerLogic'import type { ClassifierTagStats, CoverageStats, MonitorStats, ScorerHistogram, ScorerSummary } from './scannerStats'import {availableTagsFromStats,@@ -64,13 +60,6 @@ const FIRST_SCAN_POLL_INTERVAL_MS = 15_000// checks it has to admit the failure itself instead of spinning on a promise it can't verify.const FIRST_SCAN_CHECK_FAILING_AFTER = 3-export interface CreditLimitStats {- limit: number- used: number- usedPct: number- limitReached: boolean-}-/** The bucket size of the Overview charts; the drill-down only knows how to map day buckets onto the Observations tab. */export const OVERVIEW_CHART_INTERVAL: IntervalType = 'day'@@ -108,8 +97,9 @@ export interface scannerOverviewLogicValues {scanner: ScannerFormValues // replayScannerLogicavailableTags: string[]classifierTagStats: ClassifierTagStats+ cohortDisabledReason: string | null+ cohortWindowDays: numbercoverageStats: CoverageStats- creditLimitStats: CreditLimitStats | nullfirstScanCheckFailing: booleanfirstScanPending: booleanfirstScanSettled: boolean@@ -117,8 +107,6 @@ export interface scannerOverviewLogicValues {monitorStats: MonitorStatsoverviewDateFrom: string | nulloverviewDateTo: string | null- overviewImpact: ScannerImpactApi | null- overviewImpactLoading: booleanoverviewStatsApi: ObservationStatsApi | nulloverviewStatsApiLoading: booleanoverviewStatsCheckedAt: number@@ -134,6 +122,13 @@ export interface scannerOverviewLogicActions {loadScannerSuccess: (scanner: ScannerFormValues) => {scanner: ScannerFormValues} // replayScannerLogic+ saveAffectedCohort: (+ windowDays: number,+ qualifier?: AffectedCohortQualifier | undefined+ ) => {+ qualifier: AffectedCohortQualifier+ windowDays: number+ } // replayScannerLogicscannerWatermarkRefreshed: (scanner: ReplayScanner) => {scanner: ReplayScanner} // replayScannerLogic@@ -147,21 +142,6 @@ export interface scannerOverviewLogicActions {breakdown: unknownday: number | string | undefined}- loadOverviewImpact: () => any- loadOverviewImpactFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadOverviewImpactSuccess: (- overviewImpact: ScannerImpactApi | null,- payload?: any- ) => {- overviewImpact: ScannerImpactApi | null- payload?: any- }loadOverviewStats: () => {value: true}@@ -174,6 +154,9 @@ export interface scannerOverviewLogicActions {markFirstScanSettled: () => {value: true}+ saveCohort: (qualifier: AffectedCohortQualifier) => {+ qualifier: AffectedCohortQualifier+ }setOverviewDateRange: (dateFrom: string | null,dateTo: string | null@@ -213,7 +196,8 @@ export interface scannerOverviewLogicMeta {overviewStatsCheckedAt: number) => booleanfirstScanCheckFailing: (firstScanPending: boolean, overviewStatsFailureCount: number) => boolean- creditLimitStats: (scanner: ScannerFormValues) => CreditLimitStats | null+ cohortWindowDays: (overviewDateFrom: string | null, overviewDateTo: string | null) => number+ cohortDisabledReason: (overviewDateTo: string | null) => string | null}}@@ -224,15 +208,15 @@ export type scannerOverviewLogicType = MakeLogicType<scannerOverviewLogicMeta>-// The impact endpoint caps its lookback at 90 days; the overview date range can go wider.-const MAX_IMPACT_WINDOW_DAYS = 90+// The cohort endpoint caps its lookback at 90 days; the overview date range can go wider.+const MAX_COHORT_WINDOW_DAYS = 90/*** Backs the scanner's Overview tab: the built-in charts and stat panels, with their OWN filter set* (date range + verdict/tag), independent of the Observations tab's list filters. It loads the same* observations-stats endpoint as the Observations tab, but with these filters — so filtering the- * overview never disturbs the observations list and vice versa. Impact lives here too, loaded with a- * window derived from the overview date range so every widget honors the same timing.+ * overview never disturbs the observations list and vice versa. Cohorts saved from the panels use a+ * window derived from the same date range, so they match the counts beside them.*/export const scannerOverviewLogic = kea<scannerOverviewLogicType>([path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'scannerOverviewLogic']),@@ -242,7 +226,10 @@ export const scannerOverviewLogic = kea<scannerOverviewLogicType>([connect((props: ScannerOverviewLogicProps) => ({values: [replayScannerLogic({ id: props.scannerId }), ['scanner']],// Bound at build time, so dispatching into the scanner logic can't depend on it being mounted.- actions: [replayScannerLogic({ id: props.scannerId }), ['loadScannerSuccess', 'scannerWatermarkRefreshed']],+ actions: [+ replayScannerLogic({ id: props.scannerId }),+ ['loadScannerSuccess', 'scannerWatermarkRefreshed', 'saveAffectedCohort'],+ ],})),actions({@@ -255,6 +242,7 @@ export const scannerOverviewLogic = kea<scannerOverviewLogicType>([setOverviewTagFilter: (values: string[]) => ({ values }),clearOverviewFilters: true,drillIntoObservations: (day: string | number | undefined, breakdown?: unknown) => ({ day, breakdown }),+ saveCohort: (qualifier: AffectedCohortQualifier) => ({ qualifier }),}),reducers({@@ -392,56 +380,25 @@ export const scannerOverviewLogic = kea<scannerOverviewLogicType>([(pending: boolean, failureCount: number): boolean =>pending && failureCount >= FIRST_SCAN_CHECK_FAILING_AFTER,],- // Null when the scanner has no limit set, so callers can render nothing rather than a "0% of 0" panel.- creditLimitStats: [- (s) => [s.scanner],- (scanner: ReplayScanner): CreditLimitStats | null => {- const limit = scanner.credit_limit- if (limit == null) {- return null- }- const used = scanner.credits_used_against_limit- return {- limit,- used,- usedPct: limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0,- // Comes from the API, not from usedPct: a scanner stops as soon as what's left can't- // cover another scan, so this can be true below 100%.- limitReached: !!scanner.limit_reached,- }- },+ cohortWindowDays: [+ (s) => [s.overviewDateFrom, s.overviewDateTo],+ (dateFrom: string | null, dateTo: string | null): number =>+ Math.min(MAX_COHORT_WINDOW_DAYS, Math.max(1, daysFromDateRange(dateFrom, dateTo))),],- }),-- loaders(({ props, values }) => ({- overviewImpact: [- null as ScannerImpactApi | null,- {- loadOverviewImpact: async () => {- const teamId = teamLogic.values.currentTeamId- // Impact only exists for monitors (a qualifier-free predicate); other types show no panel.- if (!teamId || props.scannerId === 'new' || values.scanner?.scanner_type !== 'monitor') {- return null- }- const windowDays = Math.min(- MAX_IMPACT_WINDOW_DAYS,- Math.max(1, daysFromDateRange(values.overviewDateFrom, values.overviewDateTo))- )- return await visionScannersImpactRetrieve(String(teamId), props.scannerId, {- window_days: windowDays,- })- },+ // A cohort always covers the last N days, so a range that ended earlier would save different users than the panels show.+ cohortDisabledReason: [+ (s) => [s.overviewDateTo],+ (dateTo: string | null): string | null => {+ const end = dateTo && dateTo !== 'all' ? dateStringToDayJs(dateTo) : null+ return end && end.endOf('day').isBefore(dayjs().startOf('day'))+ ? 'Cohorts cover the most recent days. Pick a date range that ends today to save one.'+ : null},],- })),+ }),listeners(({ actions, cache, props, values }) => {const reloadStats = (): void => actions.loadOverviewStats()- // Only the date range changes the impact window; verdict/tag filters don't apply to impact.- const reloadDateScoped = (): void => {- actions.loadOverviewStats()- actions.loadOverviewImpact()- }// Pending also hangs off the scanner's sweep watermark, which only the scanner endpoint// reports; without refreshing it a first sweep that matches nothing would never clear// pending. Fetched directly because loadScanner flips scannerLoading, which blanks the scene,@@ -494,7 +451,7 @@ export const scannerOverviewLogic = kea<scannerOverviewLogicType>([}return {setOverviewDateRange: () => {- reloadDateScoped()+ reloadStats()syncFirstScanPoll()},setOverviewVerdictFilter: () => {@@ -506,19 +463,16 @@ export const scannerOverviewLogic = kea<scannerOverviewLogicType>([syncFirstScanPoll()},clearOverviewFilters: () => {- reloadDateScoped()+ reloadStats()syncFirstScanPoll()},loadOverviewStatsSuccess: syncFirstScanPoll,loadOverviewStatsFailure: syncFirstScanPoll,scannerWatermarkRefreshed: syncFirstScanPoll,- // Impact needs the scanner type; refire once the scanner (and its type) resolves. The- // poll syncs too: pending depends on the sweep watermark, which may resolve after the- // first stats response.- loadScannerSuccess: () => {- actions.loadOverviewImpact()- syncFirstScanPoll()- },+ // Pending depends on the sweep watermark, which may resolve after the first stats response.+ loadScannerSuccess: syncFirstScanPoll,++ saveCohort: ({ qualifier }) => actions.saveAffectedCohort(values.cohortWindowDays, qualifier),drillIntoObservations: ({ day, breakdown }) => {const searchParams = observationsDrilldownSearchParams({@@ -578,7 +532,5 @@ export const scannerOverviewLogic = kea<scannerOverviewLogicType>([afterMount(({ actions }) => {actions.loadOverviewStats()- // If the scanner is already cached, loadScannerSuccess won't refire — load impact now too.- actions.loadOverviewImpact()}),])diff --git a/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.tsindex ab1af92a0c91..9808d1342bf4 100644--- a/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts@@ -118,7 +118,6 @@ export interface scannerScoutLogicValues {createTemplateKey: ScannerScoutTemplateKey | nullcreating: booleanenrolled: boolean | null- expanded: booleanexpandedSkillNames: string[]latestReportRow: ScoutReportApi | nulllatestRun: SignalScoutRunSummary | null@@ -311,9 +310,6 @@ export interface scannerScoutLogicActions {setScoutConfigsFailed: (failed: boolean) => {failed: boolean}- toggleExpanded: () => {- value: true- }toggleScoutExpanded: (skillName: string) => {skillName: string}@@ -402,7 +398,6 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([actions({setScoutConfigsFailed: (failed: boolean) => ({ failed }),- toggleExpanded: true,toggleScoutExpanded: (skillName: string) => ({ skillName }),openReport: (reportId: string) => ({ reportId }),closeReport: true,@@ -554,13 +549,6 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([state.includes(skillName) ? state.filter((name) => name !== skillName) : [...state, skillName],},],- // Whether the Overview card shows the whole digest or the clipped preview.- expanded: [- false,- {- toggleExpanded: (state) => !state,- },- ],creating: [false,{diff --git a/products/replay_vision/frontend/replay_scanners/scannerStatus.test.ts b/products/replay_vision/frontend/replay_scanners/scannerStatus.test.tsnew file mode 100644index 000000000000..b2ac93aab56f--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/scannerStatus.test.ts@@ -0,0 +1,84 @@+import { dayjs } from 'lib/dayjs'++import { ScannerStatusFields, scannerStatus, spendAgainstLimit } from './scannerStatus'++const NOW = dayjs('2026-05-12T12:00:00Z')++// A healthy, long-running scanner: swept on schedule, its watermark trailing by the settle window.+const HEALTHY: ScannerStatusFields = {+ enabled: true,+ sampling_rate: 1,+ limit_reached: false,+ sweep_throttle_factor: 1,+ created_at: '2026-05-01T00:00:00Z',+ last_swept_at: NOW.subtract(40, 'minute').toISOString(),+}++const DROUGHT = { everScanned: true, samplingRate: 1 }++// A new scanner's watermark starts one settle window before creation and only moves once a sweep finishes.+const createdMinutesAgo = (minutes: number): Partial<ScannerStatusFields> => ({+ created_at: NOW.subtract(minutes, 'minute').toISOString(),+ last_swept_at: NOW.subtract(minutes + 35, 'minute').toISOString(),+})++describe('scannerStatus', () => {+ test.each([+ ['running when nothing is wrong', {}, {}, 'running'],+ ['off wins over every other problem', { enabled: false, limit_reached: true }, { quotaExhausted: true }, 'off'],+ ['off at 0% sampling, ahead of a reached limit', { sampling_rate: 0, limit_reached: true }, {}, 'off'],+ [+ "the scanner's own limit ahead of the org quota",+ { limit_reached: true },+ { quotaExhausted: true },+ 'limit_reached',+ ],+ ['stopped when the org quota is used up', {}, { quotaExhausted: true }, 'quota_exhausted'],+ ['starting while the first sweep has not finished', createdMinutesAgo(10), {}, 'starting'],+ ['delayed once a first sweep is over an hour late', createdMinutesAgo(70), {}, 'delayed'],+ [+ 'delayed when sweeps stopped advancing',+ { last_swept_at: NOW.subtract(3, 'hour').toISOString() },+ {},+ 'delayed',+ ],+ [+ 'not delayed while a throttled sweep waits out its longer interval',+ { sweep_throttle_factor: 12, last_swept_at: NOW.subtract(2, 'hour').toISOString() },+ {},+ 'throttled',+ ],+ [+ 'delayed ahead of no matches, since no sweep ran to match anything',+ { last_swept_at: NOW.subtract(3, 'hour').toISOString() },+ { drought: DROUGHT },+ 'delayed',+ ],+ ['no matches ahead of throttled', { sweep_throttle_factor: 3 }, { drought: DROUGHT }, 'no_matches'],+ ['throttled when the read budget stretches the cadence', { sweep_throttle_factor: 3 }, {}, 'throttled'],+ ])('%s', (_name, scannerOverrides, options, expected) => {+ const status = scannerStatus(+ { ...HEALTHY, ...scannerOverrides },+ { quotaExhausted: false, drought: null, now: NOW, ...options }+ )+ expect(status.kind).toBe(expected)+ })++ it('reports the stretched interval so the strip can say how often it checks', () => {+ expect(+ scannerStatus({ ...HEALTHY, sweep_throttle_factor: 12 }, { quotaExhausted: false, drought: null, now: NOW })+ ).toMatchObject({+ kind: 'throttled',+ intervalMinutes: 60,+ })+ })++ test.each([+ [null, 0, null],+ [1000, 200, { limit: 1000, used: 200, usedPct: 20 }],+ [1000, 1200, { limit: 1000, used: 1200, usedPct: 100 }],+ [0, 0, { limit: 0, used: 0, usedPct: 0 }],+ ])('spend against a limit of %s with %s used', (credit_limit, credits_used_against_limit, expected) => {+ expect(spendAgainstLimit({ credit_limit, credits_used_against_limit })).toEqual(expected)+ })+})diff --git a/products/replay_vision/frontend/replay_scanners/scannerStatus.ts b/products/replay_vision/frontend/replay_scanners/scannerStatus.tsnew file mode 100644index 000000000000..1c70e94cdf72--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/scannerStatus.ts@@ -0,0 +1,86 @@+import { Dayjs, dayjs } from 'lib/dayjs'++import type { ScanDrought } from './scanDrought'+import type { ReplayScanner } from './types'++// Mirrors the backend sweep schedule: a tick every 5 minutes over recordings that ended 35+ minutes ago.+export const SWEEP_INTERVAL_MINUTES = 5+const SWEEP_SETTLE_MINUTES = 35+// Slack past the expected watermark lag before a late sweep counts as delayed, so one slow tick doesn't flag it.+const DELAYED_GRACE_MINUTES = 60+// Matches the first-scan panel's cap: past it, a first sweep that never finished reads as delayed instead.+const STARTING_MAX_AGE_MINUTES = 60++export type ScannerStatus =+ | { kind: 'off'; reason: 'disabled' | 'no_sampling' }+ | { kind: 'limit_reached' }+ | { kind: 'quota_exhausted' }+ | { kind: 'starting' }+ | { kind: 'delayed'; lastCheckedAt: Dayjs }+ | { kind: 'no_matches'; drought: ScanDrought }+ | { kind: 'throttled'; intervalMinutes: number; lastCheckedAt: Dayjs }+ | { kind: 'running'; intervalMinutes: number; lastCheckedAt: Dayjs }++export type ScannerStatusFields = Pick<+ ReplayScanner,+ 'enabled' | 'sampling_rate' | 'limit_reached' | 'sweep_throttle_factor' | 'created_at' | 'last_swept_at'+>++/** The one status the scanner page leads with. Earlier checks win, so a scanner that is off never also reads as stopped. */+export function scannerStatus(+ scanner: ScannerStatusFields,+ options: { quotaExhausted: boolean; drought: ScanDrought | null; now?: Dayjs }+): ScannerStatus {+ const now = options.now ?? dayjs()+ if (!scanner.enabled) {+ return { kind: 'off', reason: 'disabled' }+ }+ if (scanner.sampling_rate === 0) {+ return { kind: 'off', reason: 'no_sampling' }+ }+ if (scanner.limit_reached) {+ return { kind: 'limit_reached' }+ }+ if (options.quotaExhausted) {+ return { kind: 'quota_exhausted' }+ }+ const factor = Math.max(1, scanner.sweep_throttle_factor)+ const intervalMinutes = SWEEP_INTERVAL_MINUTES * factor+ const createdAt = dayjs(scanner.created_at)+ const lastSweptAt = dayjs(scanner.last_swept_at)+ // The watermark is seeded before created_at and only advances when a sweep tick finishes.+ if (lastSweptAt.isBefore(createdAt) && now.diff(createdAt, 'minute') < STARTING_MAX_AGE_MINUTES) {+ return { kind: 'starting' }+ }+ // The watermark trails wall clock by the settle window, so that lag is normal and not a delay.+ // Capped at now, so clock skew can't make the last check read as in the future.+ const settledAt = lastSweptAt.add(SWEEP_SETTLE_MINUTES, 'minute')+ const lastCheckedAt = settledAt.isAfter(now) ? now : settledAt+ if (now.diff(lastCheckedAt, 'minute') > intervalMinutes + DELAYED_GRACE_MINUTES) {+ return { kind: 'delayed', lastCheckedAt }+ }+ if (options.drought) {+ return { kind: 'no_matches', drought: options.drought }+ }+ if (factor > 1) {+ return { kind: 'throttled', intervalMinutes, lastCheckedAt }+ }+ return { kind: 'running', intervalMinutes, lastCheckedAt }+}++export interface SpendAgainstLimit {+ limit: number+ used: number+ usedPct: number+}++export function spendAgainstLimit(+ scanner: Pick<ReplayScanner, 'credit_limit' | 'credits_used_against_limit'>+): SpendAgainstLimit | null {+ const limit = scanner.credit_limit+ if (limit == null) {+ return null+ }+ const used = scanner.credits_used_against_limit+ return { limit, used, usedPct: limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0 }+}diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.tsindex 15439cd18ed8..a5ca990ee6d9 100644--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts@@ -154,6 +154,7 @@ export function newScanner(templateKey?: string | null, teamName?: string | null// An unsaved scanner has no spend yet, so it can't have hit a limit it doesn't have.credits_used_against_limit: 0,limit_reached: false,+ sweep_throttle_factor: 1,} as constconst template = findScannerTemplate(templateKey ?? undefined)diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.tsindex 0957f56020bc..d5771d818015 100644--- a/products/replay_vision/frontend/replay_scanners/types.ts+++ b/products/replay_vision/frontend/replay_scanners/types.ts@@ -212,6 +212,22 @@ export function failureKindDescription(kind: FailureKind): string {return FAILURE_KINDS[kind].description}+/** Why a failed or ineligible scan produced no result, short enough for a table cell: the message when there is one, else the kind's description. */+export function unsuccessfulScanReason(+ status: ReplayObservationApi['status'],+ errorReason: string | null | undefined+): string | null {+ if (!errorReason || (status !== 'failed' && status !== 'ineligible')) {+ return null+ }+ if (status === 'failed') {+ const parsed = parseFailureReason(errorReason)+ return parsed ? parsed.message || failureKindDescription(parsed.kind) : errorReason+ }+ const parsed = parseIneligibleReason(errorReason)+ return parsed ? parsed.message || ineligibleKindDescription(parsed.kind) : errorReason+}+/*** How to offer a retry for a given failure. An unparseable or unknown kind gets the encouraging default, since* the alternative is discouraging a retry we have no evidence against.diff --git a/products/replay_vision/frontend/utils/backfills.ts b/products/replay_vision/frontend/utils/backfills.tsindex 7daffb14f27f..ab305f5cac10 100644--- a/products/replay_vision/frontend/utils/backfills.ts+++ b/products/replay_vision/frontend/utils/backfills.ts@@ -1,4 +1,4 @@-// The filter row fits only the UUID prefix. The Backfills table shows the full ID for comparison.+// The filter row fits only the UUID prefix. The backfill history table shows the full ID for comparison.export function shortBackfillId(id: string): string {return id.slice(0, 8)}diff --git a/products/replay_vision/frontend/utils/sessionIdInput.test.ts b/products/replay_vision/frontend/utils/sessionIdInput.test.tsnew file mode 100644index 000000000000..cdd0c392c8ff--- /dev/null+++ b/products/replay_vision/frontend/utils/sessionIdInput.test.ts@@ -0,0 +1,23 @@+import { sessionIdFromInput } from './sessionIdInput'++describe('sessionIdFromInput', () => {+ test.each([+ ['a bare ID', '01966b3f-70a1-7c52-a4d5-3f9b2e8c1d07', '01966b3f-70a1-7c52-a4d5-3f9b2e8c1d07'],+ ['a bare ID with whitespace', ' abc123 ', 'abc123'],+ ['a recording link', 'https://us.example.com/project/2/replay/abc123', 'abc123'],+ ['a recording link with a timestamp', 'https://us.example.com/project/2/replay/abc123?t=42', 'abc123'],+ ['a relative recording path', '/project/2/replay/abc123', 'abc123'],+ [+ 'a replay list link with a selected recording',+ 'https://us.example.com/project/2/replay/home?sessionRecordingId=abc123',+ 'abc123',+ ],+ ['a replay list link with nothing selected', 'https://us.example.com/project/2/replay/home', null],+ ['a playlist link', 'https://us.example.com/project/2/replay/playlists/xyz', null],+ ['a link to some other page', 'https://us.example.com/project/2/insights/abc', null],+ ['a link with broken percent-encoding', '/project/2/replay/abc%E0%A4%A', null],+ ['nothing', ' ', null],+ ])('%s', (_name, input, expected) => {+ expect(sessionIdFromInput(input)).toBe(expected)+ })+})diff --git a/products/replay_vision/frontend/utils/sessionIdInput.ts b/products/replay_vision/frontend/utils/sessionIdInput.tsnew file mode 100644index 000000000000..e433a6964967--- /dev/null+++ b/products/replay_vision/frontend/utils/sessionIdInput.ts@@ -0,0 +1,36 @@+// Replay pages that sit directly under /replay/ but are not a recording.+const NON_RECORDING_REPLAY_PATHS = new Set(['home', 'playlists', 'settings', 'file-playback', 'kiosk'])++/**+ * The session ID in what someone pasted: a bare ID, a recording link (`/replay/<id>`), or a replay list link with+ * `sessionRecordingId`. Null when it is a link that points at no recording.+ */+export function sessionIdFromInput(input: string): string | null {+ const trimmed = input.trim()+ if (!trimmed) {+ return null+ }+ if (!trimmed.includes('/')) {+ return trimmed+ }+ let url: URL+ try {+ // The base only matters for a pasted path without a host.+ url = new URL(trimmed, 'https://app.example.com')+ } catch {+ return null+ }+ const fromParam = url.searchParams.get('sessionRecordingId')+ if (fromParam) {+ return fromParam+ }+ const match = url.pathname.match(/\/replay\/([^/]+)\/?$/)+ if (!match || NON_RECORDING_REPLAY_PATHS.has(match[1])) {+ return null+ }+ try {+ return decodeURIComponent(match[1])+ } catch {+ return null+ }+}diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex b67ecb4947f4..17eaa18fec9c 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -823,6 +823,17 @@ class SignalSourceSliceOutcomes:report_count: intpr_count: intmerged_pr_count: int+ # Newest first, so a caller can link to what the counts are counting.+ reports: "list[SignalSourceSliceReport]"+ pull_requests: "list[SignalSourceSlicePullRequest]"+++@frozen+class SignalSourceSlicePullRequest:+ """One implementation PR opened on a report the slice's signals were grouped into."""++ url: str+ merged: bool@frozen@@ -886,13 +897,21 @@ def get_outcomes_for_signal_source_slice()report_ids = [report.id for report in reports]prs = fetch_implementation_prs_for_reports(report_ids, team_id=team.id)- pr_urls = {pr.url for report_prs in prs.values() for pr in report_prs}- merged_pr_urls = {pr.url for report_prs in prs.values() for pr in report_prs if pr.merged}+ # Reports arrive newest first, so the first sighting of a URL keeps that order; several reports can share a PR.+ pull_requests: dict[str, SignalSourceSlicePullRequest] = {}+ for report_id in report_ids:+ for pr in prs.get(report_id, []):+ known = pull_requests.get(pr.url)+ pull_requests[pr.url] = SignalSourceSlicePullRequest(+ url=pr.url, merged=pr.merged or bool(known and known.merged)+ )return SignalSourceSliceOutcomes(signal_count=stats.signal_count,report_count=len(report_ids),- pr_count=len(pr_urls),- merged_pr_count=len(merged_pr_urls),+ pr_count=len(pull_requests),+ merged_pr_count=sum(1 for pr in pull_requests.values() if pr.merged),+ reports=reports,+ pull_requests=list(pull_requests.values()),)diff --git a/products/signals/backend/test/test_signal_queries.py b/products/signals/backend/test/test_signal_queries.pyindex 936289536e68..5ed63d407ae6 100644--- a/products/signals/backend/test/test_signal_queries.py+++ b/products/signals/backend/test/test_signal_queries.py@@ -11,7 +11,7 @@ from parameterized import parameterizedfrom posthog.clickhouse.client import sync_executefrom products.signals.backend.facade.api import (- SignalSourceSliceOutcomes,+ SignalSourceSlicePullRequest,get_outcomes_for_signal_source_slice,get_reports_for_signal_source_slice,)@@ -534,7 +534,17 @@ class TestGetOutcomesForSignalSourceSlice(_SignalEmbeddingsTestBase):team=self.team, source_product="errors", source_type="some_type", extra_equals={"scanner_id": "sA"})- assert outcomes == SignalSourceSliceOutcomes(signal_count=5, report_count=2, pr_count=2, merged_pr_count=1)+ assert (outcomes.signal_count, outcomes.report_count, outcomes.pr_count, outcomes.merged_pr_count) == (+ 5,+ 2,+ 2,+ 1,+ )+ # The links behind the counts: the same deduped PRs, newest report's first.+ assert outcomes.pull_requests == [+ SignalSourceSlicePullRequest(url=shared_pr.url, merged=True),+ SignalSourceSlicePullRequest(url=second_pr.url, merged=False),+ ]def test_hydrates_the_same_slice_newest_first(self) -> None:# The link surface shares the slice query with the counters, so it must drop the samediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6e82076babc9..2bce3f5e52ff 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -9723,6 +9723,20 @@ export namespace Schemas {identifier: string;}+ /**+ * * `yes` - Yes+ * * `no` - No+ * * `inconclusive` - Inconclusive+ */+ export type ObservationVerdictEnum = typeof ObservationVerdictEnum[keyof typeof ObservationVerdictEnum];+++ export const ObservationVerdictEnum = {+ Yes: 'yes',+ No: 'no',+ Inconclusive: 'inconclusive',+ } as const;+/*** Body of POST /vision/scanners/:id/affected_cohort/. Same qualifiers as the impact GET.*/@@ -9733,6 +9747,12 @@ export namespace Schemas {* @maximum 90*/window_days?: number;+ /** Monitor scanners only: count sessions with this verdict. Defaults to `yes`. Not applicable to other scanner types.+ *+ * * `yes` - Yes+ * * `no` - No+ * * `inconclusive` - Inconclusive */+ verdict?: ObservationVerdictEnum | null;/*** Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.* @maxLength 100@@ -63946,6 +63966,8 @@ export namespace Schemas {readonly credits_used_against_limit: number;/** Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is set and the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set. */readonly limit_reached: boolean;+ /** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */+ readonly sweep_throttle_factor: number;/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at: string;readonly created_at: string;@@ -75086,6 +75108,8 @@ export namespace Schemas {readonly credits_used_against_limit?: number;/** Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is set and the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set. */readonly limit_reached?: boolean;+ /** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */+ readonly sweep_throttle_factor?: number;/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at?: string;readonly created_at?: string;@@ -86758,7 +86782,7 @@ export namespace Schemas {* Who this scanner's findings affected in the window; counted from observations, not estimated.*/export interface ScannerImpact {- /** Distinct sessions with an affected observation in the window. For monitors only verdict-yes observations count; for other scanner types every succeeded observation counts. */+ /** Distinct sessions with an affected observation in the window. For monitors only observations with the requested verdict count (yes by default); for other scanner types every succeeded observation counts. */readonly affected_sessions: number;/** Distinct users behind the affected sessions, by distinct ID. May include anonymous device IDs when the recorded sessions were not identified. */readonly affected_users: number;@@ -87118,6 +87142,25 @@ export namespace Schemas {config: SignalScoutConfig;}+ export interface SelfDrivingReport {+ /** Signal report ID, for linking to it in the inbox. */+ id: string;+ /**+ * Report title. Null until the report is summarized.+ * @nullable+ */+ title: string | null;+ /** The report's inbox status. */+ status: string;+ }++ export interface SelfDrivingPullRequest {+ /** URL of the implementation pull request. */+ url: string;+ /** Whether the pull request has merged. */+ merged: boolean;+ }+/*** Response of GET /vision/scanners/:id/self_driving_stats/.*/@@ -87130,6 +87173,10 @@ export namespace Schemas {prs_opened: number;/** Of the opened PRs, how many have merged. */prs_merged: number;+ /** The newest reports counted in `reports_contributed`, at most 20. */+ reports: SelfDrivingReport[];+ /** The newest PRs counted in `prs_opened`, at most 20. */+ pull_requests: SelfDrivingPullRequest[];}/**@@ -114745,6 +114792,15 @@ export namespace Schemas {* @nullable*/tag?: string | null;+ /**+ * Monitor scanners only: count sessions with this verdict. Defaults to `yes`. Not applicable to other scanner types.+ *+ * * `yes` - Yes+ * * `no` - No+ * * `inconclusive` - Inconclusive+ * @nullable+ */+ verdict?: VisionScannersImpactRetrieveVerdict;/*** Trailing window of observations to count. Defaults to 30 days.* @minimum 1@@ -114753,6 +114809,15 @@ export namespace Schemas {window_days?: number;};+ export type VisionScannersImpactRetrieveVerdict = typeof VisionScannersImpactRetrieveVerdict[keyof typeof VisionScannersImpactRetrieveVerdict] | null;+++ export const VisionScannersImpactRetrieveVerdict = {+ Yes: 'yes',+ No: 'no',+ Inconclusive: 'inconclusive',+ } as const;+export type VisionScannersBackfillsListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.tsindex da7d91953c8e..44e5c7741609 100644--- a/services/mcp/src/generated/replay_vision/api.ts+++ b/services/mcp/src/generated/replay_vision/api.ts@@ -613,6 +613,17 @@ export const VisionScannersAffectedCohortCreateBody = () => zod.max(visionScannersAffectedCohortCreateBodyWindowDaysMax).default(visionScannersAffectedCohortCreateBodyWindowDaysDefault).describe('Trailing window of observations to count. Defaults to 30 days.'),+ verdict: zod+ .union([+ zod+ .enum(['yes', 'no', 'inconclusive'])+ .describe('\* `yes` - Yes\n\* `no` - No\n\* `inconclusive` - Inconclusive'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Monitor scanners only: count sessions with this verdict. Defaults to `yes`. Not applicable to other scanner types.\n\n\* `yes` - Yes\n\* `no` - No\n\* `inconclusive` - Inconclusive'+ ),tag: zod.string().max(visionScannersAffectedCohortCreateBodyTagMax)@@ -665,6 +676,12 @@ export const VisionScannersImpactRetrieveQueryParams = () => zod.object({.describe('Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.'),+ verdict: zod+ .union([zod.literal('yes'), zod.literal('no'), zod.literal('inconclusive'), zod.literal(null)])+ .nullish()+ .describe(+ 'Monitor scanners only: count sessions with this verdict. Defaults to `yes`. Not applicable to other scanner types.\n\n\* `yes` - Yes\n\* `no` - No\n\* `inconclusive` - Inconclusive'+ ),window_days: zod.number().min(1)diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.tsindex bd6ae0b0ee89..8a27ff89f6a1 100644--- a/services/mcp/src/tools/generated/replay_vision.ts+++ b/services/mcp/src/tools/generated/replay_vision.ts@@ -221,6 +221,9 @@ const visionScannersAffectedCohortCreate = (): ToolBase<if (params.window_days !== undefined) {body['window_days'] = params.window_days}+ if (params.verdict !== undefined) {+ body['verdict'] = params.verdict+ }if (params.tag !== undefined) {body['tag'] = params.tag}@@ -410,6 +413,7 @@ const visionScannersImpactRetrieve = (): ToolBase<max_score: params.max_score,min_score: params.min_score,tag: params.tag,+ verdict: params.verdict,window_days: params.window_days,},})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-affected-cohort-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-affected-cohort-create.jsonindex af41d178469b..25f93ed86d87 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-affected-cohort-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-affected-cohort-create.json@@ -39,6 +39,19 @@],"description": "Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types."},+ "verdict": {+ "anyOf": [+ {+ "description": "* `yes` - Yes\n* `no` - No\n* `inconclusive` - Inconclusive",+ "enum": ["yes", "no", "inconclusive"],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Monitor scanners only: count sessions with this verdict. Defaults to `yes`. Not applicable to other scanner types.\n\n* `yes` - Yes\n* `no` - No\n* `inconclusive` - Inconclusive"+ },"window_days": {"default": 30,"description": "Trailing window of observations to count. Defaults to 30 days.",diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-impact-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-impact-retrieve.jsonindex af41d178469b..0e2704e75cc5 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-impact-retrieve.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-impact-retrieve.json@@ -39,6 +39,34 @@],"description": "Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types."},+ "verdict": {+ "anyOf": [+ {+ "anyOf": [+ {+ "const": "yes",+ "type": "string"+ },+ {+ "const": "no",+ "type": "string"+ },+ {+ "const": "inconclusive",+ "type": "string"+ },+ {+ "const": null,+ "type": "null"+ }+ ]+ },+ {+ "type": "null"+ }+ ],+ "description": "Monitor scanners only: count sessions with this verdict. Defaults to `yes`. Not applicable to other scanner types.\n\n* `yes` - Yes\n* `no` - No\n* `inconclusive` - Inconclusive"+ },"window_days": {"default": 30,"description": "Trailing window of observations to count. Defaults to 30 days.",