Skip to content

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

feat(posthog-ai): Make new Posthog AI 2.0 UX BUTTERY 🧈🧈🧈; group routine tool calls and reasoning in task threads (#97104)

Jake Ruthf2be832c315b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 505ab4ca0173..a17f9fd7cdcf 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5609,21 +5609,41 @@ snapshots:
products-posthog-ai-queuedmessagelist--waiting-for-approval--light:
hash: v1.k794b7964.84558994ccccfbf6b0479c05e70fa04048ecdb813a76ac4a3e689b3f3d4a3cfd.WdgXqb0eDP9c6glP6UuTXb--spzTGFym3foe4wFyEIg
products-posthog-ai-runalertactivity--agent-crash--dark:
- hash: v1.k794b7964.eccf2dc544a4a6695a42fb347e5c87b78fe735e8ac46647d17e53bf94d25884e.-9d5PYEyERQrPQag4CvnJteuh6fkhr0vYWyTDOt0Z8E
+ hash: v1.k794b7964.c24fb9cd17d324218dc3b8708de5c05f112d1c6f65c9ff44f9e74c815608c448.t54VYmu9mZwk2sWYA8TsqLHuS_-087t2Wm7NNl8qGh4
products-posthog-ai-runalertactivity--agent-crash--light:
- hash: v1.k794b7964.a1a3356544f2fc4eeb9c4dbd07acddf65deda2f2b19e5ac305786684d26586b3.vR3tocrtA_r07ZhmTjsFexJfBWRBzP22x3-KGGTGDBc
+ hash: v1.k794b7964.766c3f16a2bbcda2654eee7dfc8027fee38a296a7cde1214a26b7ea1119a6a4d.fUbnuqNgAhx1QsJv2kWwiKWn01dSyMnwNLVao2PTgn0
products-posthog-ai-runalertactivity--agent-error--dark:
- hash: v1.k794b7964.0276d89cce09b46a54c0fef79d3c62587ccefe47201e3860af4d60d30a15b57f.kFHhWgpFAoCuaEQhc5xxshPCdih4bzc4wOxzg7DJC10
+ hash: v1.k794b7964.571b05f6b216d4a9d5c6fe9780f83e8805b51c1c3ad16e179d991a29f8105976.uk6ksOcZbGYlk7rzeqim-Rw6yigz2drj_T2qXNBOImU
products-posthog-ai-runalertactivity--agent-error--light:
- hash: v1.k794b7964.5aac60601e21838248726ef6479c5cd1c6c1fed7a0bbdea2ef86a84d43c515f1.GxYyehkFyxpHnoRl240yop9VC_W_v_El3IcGzCIiRzY
+ hash: v1.k794b7964.cfbb0166a1696db3f63e799b1c11849f5e8f0599395e030df294894535351127.lRRmsiNgZZk9HUbjnN1h9j06GqdQKdcJq20xQtjB1Z0
products-posthog-ai-runalertactivity--connection-lost--dark:
- hash: v1.k794b7964.410f559d98dc233ee8047dd8cfd5ce5f16bf47298ac0f3ea7c38e21913f3e79e._jbCcWpMORUlIHh_Te_m_hWib0TJ1zlg4bw-cm35FTI
+ hash: v1.k794b7964.31c7fd62daefb54216da5c53779c56e4c440441f72447fdd80a8b99190d35713.WfQlAvkYZKbboDjk-PaqhmaBt67pg8VBxAb7_8EwKOQ
products-posthog-ai-runalertactivity--connection-lost--light:
- hash: v1.k794b7964.6a54547f7784b2a6ddcdde131600ed37ee2abdb56180e9cff603e8a7a3e395bf.cUg8KJHc-L7D6KFrCng16YTN5A0-WRMfw75cElwkroI
+ hash: v1.k794b7964.0bac493951bd2047e08b842ba4476ca3853b5cf2bab2bc586375eca502b36fd8.OmwzOF2ZEibfR1C9Ta07PYWQYuLUu6Firyw6xmtwKYc
products-posthog-ai-startup-chat--sidebar--dark:
- hash: v1.k794b7964.97e75539fb76cb77f57dce890bba8174746a999ac0f00fa4b6c0b27b197892f6.HxsSbUTC0_6SGTHo867GUBAgfdVQGH1_mKgZxVl-k1c
+ hash: v1.k794b7964.567861258fbfdb2691329675379e27af95694c69f734e63d12e88f74d36c2eee.pStxB048sPXcS-nkSrl05g9zJO3iZQmPEYE-VzPrCro
products-posthog-ai-startup-chat--sidebar--light:
- hash: v1.k794b7964.1447c8f9e17c9d9fc09f81ec8469ec0629bafef796c45c3c66894961ad4d978f.H-qJsZXlEGLNeIzG2_tb_L5OarwFKvYVoktKd2p6w-w
+ hash: v1.k794b7964.e6ac4e16cfc30937fa95cf22ebb3adff8f4bc80c52737d919273a0ab4609c220.tbDbVYqrgoK6xmsgtuG1d3ymNaokp5MmQnpllFLfx78
+ products-posthog-ai-threadactivitygroup--long-history--dark:
+ hash: v1.k794b7964.2e3de4c9920447e12ddad04f5ebdbc7aa37d8724ea2c3089f752d5476abb4d3a.8adra9j6VC2g8199P2Y4HNamG7wds2LYoefV0R-MH_s
+ products-posthog-ai-threadactivitygroup--long-history--light:
+ hash: v1.k794b7964.e3105b81b2e343041589897879e2432d06c56e822593ef51dba139544ddb10fe.ZdI1ynaQPOp1ZPL2nqFblBw22a1Mci3OE6dRB-C9By0
+ products-posthog-ai-threadactivitygroup--narrow--dark:
+ hash: v1.k794b7964.eb655a55f31ed378bd406492655a2f06b6bf46d5840de6e6f928f49be7166d60.czOa1Vjr_jJ0GhohYMuQx050uaG4ctHJ85fNYI0ajEo
+ products-posthog-ai-threadactivitygroup--narrow--light:
+ hash: v1.k794b7964.2d6791a064d53f189ce73912dc95f0e71b3fb748d90f8a6a5b27e52543a00999.8SwVDhcfDi54VdC5eksSXLlkVPtWnQbjY4eFiuE8CHM
+ products-posthog-ai-threadactivitygroup--short-history--dark:
+ hash: v1.k794b7964.9b7c599d8bc0d014aff92a39d9ea25776fa5b0b1a98844bcd61ed482fb54a662.xwAV8zDAz2Mgxx5QvLNvnzo2tYGjpPOOzqnxswWL3jc
+ products-posthog-ai-threadactivitygroup--short-history--light:
+ hash: v1.k794b7964.1d1fe51d8f925a0609cb6563ef584fca24291cd75ed7a492ed8902b218ef247c.xlMOAY6k05UlEKiNS2B5lEH2RnWszpW1QZU8TBUFavc
+ products-posthog-ai-threadactivitygroup--thought-only--dark:
+ hash: v1.k794b7964.59f9b65f3327467b23b1b60b730af8e31db8a0420b14bbaf090cb90ad49d1ad1.mT7-Bu4Nhyci96u6AToP8iXGMUY_6L7HT29STuJ_tFM
+ products-posthog-ai-threadactivitygroup--thought-only--light:
+ hash: v1.k794b7964.f18630672f4cd6196f401bdfc8026668c370e73572820d3bbfa581538ec9a979.2cvSxyjCrolxtd2YehEopd4hKqguy-kajBmB88-qYJU
+ products-posthog-ai-threadactivitygroup--unknown-timing--dark:
+ hash: v1.k794b7964.dd4706709f78c02664f030c478cbb840a011b1ef2c5667a24b69f2da69d080e1.nyWDTetgXbFNe5gbJh_FRvK-1VQ0IzYQ22doIIokQeA
+ products-posthog-ai-threadactivitygroup--unknown-timing--light:
+ hash: v1.k794b7964.53f358e67f6b451f54117490d453d1a8ac9df23954e600c5136b8460ba176cdd.oPnmThRLe7TWRQMutMewFyRpHGhuYPXaEhUJN0FrWTs
products-posthog-ai-virtualizedthread--anchored-open--dark:
hash: v1.k794b7964.eecc3dde9e8475fb8f20f259880edae96e2750529897fc326c44d33ce20e0885.hQlXYcfwZ9CiFajcBHUg9oY6h2QcGrm91CkXVIht-OE
products-posthog-ai-virtualizedthread--anchored-open--light:
@@ -7585,17 +7605,17 @@ snapshots:
scenes-app-inbox-detail--report-minimal--light:
hash: v1.k794b7964.1ec199f350734471b4a0b1463ff94a4654a30424276fc64c115c3d65db3cdb41.Tc9W_NbKBqiZUS8nJ_J48f161oSMbOpTNtd99CK-a5I
scenes-app-inbox-detail--run-failed--dark:
- hash: v1.k794b7964.18c9ba56db7b5cb2bcb878df2052f4d91526e6fa34a29dfcf96032baf75e8df0.-rwa7P77YEts2Ha8p22f6CCVlogjJUMABDuVmwdaLK8
+ hash: v1.k794b7964.8ea3a3172853ee54499c2c6cfefce80607be334c6e811241d34287a6f765653c.-6vgVoBAALRraFupOI_QA0z0eBbSWQn1uYV0rckIjsg
scenes-app-inbox-detail--run-failed--light:
- hash: v1.k794b7964.c1bed300d7cddaaa8dcebcc33f50dd827dbb0d65b53b63731fe52be3cd15c1a2.KSlqMmSZLxK3S8qUdpOnIUjSu1jCQWf5IrglKsKVfxQ
+ hash: v1.k794b7964.fc3316cfa56e2cb68215f1e5bedf0afff66d97dd89b3b6399eefa4f30631fc88.RjIHic-nM5H4gzyq0aIR_xBNKnPj34xD5ezDHtKNiDk
scenes-app-inbox-detail--run-in-progress--dark:
- hash: v1.k794b7964.bb129fb2d85fd31d1bfca95d231cfa4699c5b27512baf5d3fc95d1882fab3652.10k12B0ZpQhff4dAc5pUxxKNN7CJrtaIATPc27eOFds
+ hash: v1.k794b7964.dc6d56db7348706b6b21c61c15ab0b46cebe1f34ed2e7d356a67f0b23d462e9b.fsMnFqNIFF6O4iJylI-LIlj1vW-0y_QNV6btMpC4WRw
scenes-app-inbox-detail--run-in-progress--light:
- hash: v1.k794b7964.a7e1db6a9a3dc332b0a51696b8fb54e96ea9d419eb888c2920ff342d8569e245.5NBzRp68Nvv8izLu83oNjoSqN7HNQ5y6Fl-eZF1iUQA
+ hash: v1.k794b7964.eed9654f6551d18c0707bb196c885034a571768e49a6a557e69a65b07744aaa2.EZQyoFOwlA_qgHVREpUKWDLQweNOk5tHOJt0rL3U_I0
scenes-app-inbox-detail--run-ready--dark:
- hash: v1.k794b7964.f4c724bf1571f63ed12f153cd7cae45028c5f842850738c980657a16eaffba47.bZBzfSAW7bDXjjecrjVvRTlPFKmyZ_cUElF_zrVnWZU
+ hash: v1.k794b7964.6d25562ee11eb3e2bc5ecf6aedff4fe058299de21db40a241d22ec348566b5e7.1QCX8kAJWvaKf9rBXs7O4S-9Nh9tbQR6zn2IL5ehZpo
scenes-app-inbox-detail--run-ready--light:
- hash: v1.k794b7964.db7f6bd45e96876356ac107cc821d48bb7f053f91c824ed07d25a0a8be7f6636.OOlpTL2fpns11lgi8vN1cRKSrPLJyrrmOhVa_u1hdPA
+ hash: v1.k794b7964.2a7035c21bc396a44a81e18222d5f9a50f8ca650d47bc387b27a4c8ab72db7aa.BZ_qNCVpWT1v8Ov60-xHUyKzBwvr1BPNjoLZgjobYw4
scenes-app-inbox-discussreportbutton--with-suggestions--dark:
hash: v1.k794b7964.eac6e6142d7e4691b0d21db813719df6719b507ecef84137f0df4b4bf3efe4f3.a69HoQRIbA83KFV7pEchsR08azkm0XLHON-UcYLRwf4
scenes-app-inbox-discussreportbutton--with-suggestions--light:
@@ -8553,9 +8573,9 @@ snapshots:
scenes-app-posthog-ai--chat-with-ui-context--light:
hash: v1.k794b7964.7da5b403f49dc509926f2529168284df4dc7d7c842aa4bf08ddbcea4fa15ea5e.26kMq0Dv1hT1YkUwJPYO0KbgKxp8p1m-ONUbE0oVX-M
scenes-app-posthog-ai--empty-thread-loading--dark:
- hash: v1.k794b7964.4f058f5fc0873361bbf11633bdd48a8d2cb97d1c3a0f47f6002f354e81900122.0ZzEY05ZJ05P_S6-JT742BBmXq11N6zmQnPCfX-No5I
+ hash: v1.k794b7964.c2e18541e4cc111ef58178270f2f52fcdf6c56009fa60365cc872ab8a06f5282.5wVA_MMg-ZZx6BzN8P4yj-vnXGaQzgxd_tVW1_2zGbs
scenes-app-posthog-ai--empty-thread-loading--light:
- hash: v1.k794b7964.8a2284ff77e57276dcb81e77f9c4143a5a8889900aefddec1eca6bdf842f7cf2.gmQgSDaAnhzMtizklmZuMIdox453n_MbKjIxQEsSryg
+ hash: v1.k794b7964.8cb9890a2c93a2907953a128640d835f3c82e160035f62bfedb725e0ee665274.8Hi6Fm-3KfWT9wwwKj-JulHHYhfT1O-UMSFvgP-QyYU
scenes-app-posthog-ai--generation-failure-thread--dark:
hash: v1.k794b7964.075ec56307f12f7d72b40d7d5cd3b7c9731ee2d2264fb93123a5dd85a51b8189.dqB1qogZZbp34xVDHeBHJSNh-E4dwqCYscvkt0nq-FQ
scenes-app-posthog-ai--generation-failure-thread--light:
@@ -8589,9 +8609,9 @@ snapshots:
scenes-app-posthog-ai--thread-with-failed-generation--light:
hash: v1.k794b7964.f9519e52d664ffa99400f40d051685f5c4e58d79f754e36a557db8411c150812.Uh8jeOtQLlnrRr3B3f3BtQsA5bE1TX2XNAbvsQrIwNY
scenes-app-posthog-ai--thread-with-in-progress-conversation--dark:
- hash: v1.k794b7964.75871426b5230228dbb66635ca5bd2a3687c8f95e32e37b4c4143e5d15bc522c.WrklAQualDzv_t38nN-5G71qmgZ1_1fCsb21Ql_upxM
+ hash: v1.k794b7964.a8c0b1d661ef770213580a66c9ff82f759be33d9a02e8371307edda8a2e450a2.EUm2SS-BSbi4K0PM_JsWtfON-mgm-FvxujeEuXNpwNQ
scenes-app-posthog-ai--thread-with-in-progress-conversation--light:
- hash: v1.k794b7964.4f9d88e076e9aa81e8aaac264f0a6fe900efcb0f726a73c5fcdc52a7e6459c88.JiPtjsbZcioinx0lKmJUIV_xtBpjI1oRJuqF8Pi6kFE
+ hash: v1.k794b7964.d86972005ef5516a0fd5198074b037ad5b955b023dbe9ab3dc98245721f25816.XkKeafdqLURGpErLEcZrFrrJxRyl1bKObiFGhYSXUWg
scenes-app-posthog-ai--thread-with-multiple-context-objects--dark:
hash: v1.k794b7964.b0c6b37ec6d05b2b43ad2c6a59dd805a54642922facb223c49eba0d7c51d7345.FE6W9UiYJ4VT7wv7CFru1jLMLqfCJVmAnezZGPiarIg
scenes-app-posthog-ai--thread-with-multiple-context-objects--light:
@@ -8629,37 +8649,37 @@ snapshots:
scenes-app-posthog-ai--welcome-with-latest-conversations--light:
hash: v1.k794b7964.b54b4d009baaae102c8d371902bfc84dc14648f197e9781b204f54c222ba64c3._DC8J9KA3PE5kzvVhIHuOVmmg7BtWTETx-9ICvHyrqU
scenes-app-posthog-ai-forms--thread-with-mixed-field-type-form--dark:
- hash: v1.k794b7964.ca6175217faed0e867cfd45be05a7fb37e9f355177abd664e492c5f3dbc6cddb.bhAYDptn3_ULxSBKXl2K0JUWH6Irbq6RS5bvwPt0j2c
+ hash: v1.k794b7964.54ad5b18104e4e01d20da34010c667dcf6b8d59fd87173f7e61f95c20b1002c1.iWbOqOU6gY7a9E8-MTwfRZ760Q7h_XzAzklb5lMPOl8
scenes-app-posthog-ai-forms--thread-with-mixed-field-type-form--light:
- hash: v1.k794b7964.fdeef789c938fbbd0a8d205302ca2870d7eb1e604a2f1f9bb81c8dbcf9857525.hTFh9hxDu1zGc-wr4tP1ZxneSsm0SL4RVqY9bzgZNr4
+ hash: v1.k794b7964.d9f3d49bfce307430ffb7fb05bfa861878e094eef5c2d84d77f69b75a4399053.QNo2yPY91q2TffO7F30d3B6IVLMDe2JXPWTgCWnyjRs
scenes-app-posthog-ai-forms--thread-with-multi-field-question--dark:
- hash: v1.k794b7964.2783d961779a0ad61d3c947d45323523885dd459a9413a836ab63427f85cc5cf.vUBBpQdpBFtBeiUnYtFhDCGu0y3IwIXD4m_XJqusEpU
+ hash: v1.k794b7964.ac11d0dd43e72ff466a356a9640bd7569c532dc1fe086aeef18132bbb5cae6ac.YIBQMSjdhF21LUGV3UlU1ty3FHw_asqf-BgiGvHmx8E
scenes-app-posthog-ai-forms--thread-with-multi-field-question--light:
- hash: v1.k794b7964.3228c57a2d426d7c85450d521e8e0f23d7e310b276eed7ed13671da1a17095bb.GLkzVNoHGqzUxMw49HqvXNBXKUsIjyCn-aWTztxBGYk
+ hash: v1.k794b7964.24814c5ea4efc80778bd8edb5d61399338d9c70c50f7547336e9aa74bf87ad8d.nwFiSigNwHgXqt2C9P8RPf9eDRMkSOwAc7vfC41GAOg
scenes-app-posthog-ai-forms--thread-with-multi-question-form--dark:
- hash: v1.k794b7964.83e440630230a0ceb689de86d1e7a43dc93a610285df2fd3662cf6bcdd7246bb.DAP5bR5rRJ__kB2412hY9bhDNzTc3kTL-w77Khyo_wA
+ hash: v1.k794b7964.e8fa9e5aceb1344f978d9fbe209234696c2cdc92d114168c8d70627744a855fa.0dx_62KFf-Kk7Zp6V6jYOpg2tUcYLgW1zFvDtkEBAds
scenes-app-posthog-ai-forms--thread-with-multi-question-form--light:
- hash: v1.k794b7964.766c93cee0619da839bcc04ad727749f673f6511f1435b70969e77afad0b2424.fzTGPlVjZaVePBTIGfpbljDTRMhn8lG2llCKr2DN9ps
+ hash: v1.k794b7964.2abebca8398e2ec23af9994a45756613c782fbb88ee3339da17950e713e53f5f.Ri7ss3lQU-d2FgzVBlqkqeYyjw_XH3j9fvru5FQxNI0
scenes-app-posthog-ai-forms--thread-with-multi-question-form-long-content--dark:
- hash: v1.k794b7964.ad70ad42f688ecdcba846c7744856bb48c424c39923753af4fdde99b2495b55c.IC2oHp-wj-obAE6SBt2-XnNCQRZbl-X1kbJrLTGxqSo
+ hash: v1.k794b7964.a13a9caf409ab069110395c7b42be5fe5b645ee943e417fcfc79a8422145097a.wlDJMASmpreQ8MzoQCLUT4qhJXkZ8L4swUOdJ6jelWs
scenes-app-posthog-ai-forms--thread-with-multi-question-form-long-content--light:
- hash: v1.k794b7964.ae84fa938b48ffcfaccfe8bc2d818a55942022dec0e3504c31c4d69d4f7b1095.1NE_-iw8m9ar2ZNwB8uvHlwvQ7sx4HLmK5DndPq0TFc
+ hash: v1.k794b7964.93726239c3e3576be4ec9eddfa1bb8c7d0a37c1aee986fa65bc1ccb969c36382.NmP3bKZIjIF8r87L06YTEbSqIN6WGnXrCkFqUNN9cXs
scenes-app-posthog-ai-forms--thread-with-multi-question-form-no-custom-answer--dark:
- hash: v1.k794b7964.58446c668493fd0d3e98687d46d508a488cfd81c8ae5295e3875cbe0498cfe1d.PM9gtRSO3yQw2jO4SLwV4rEGyYL3uk1fB8dI52f-zKo
+ hash: v1.k794b7964.eddbff8ce7e256fe4e46832326fa06c2c70ada68e22811a9b305c30954dd9e33.2f7Ov_ilzSj3tf3MQCNACgB6bKkrpboeJ0kbhbjZPaU
scenes-app-posthog-ai-forms--thread-with-multi-question-form-no-custom-answer--light:
- hash: v1.k794b7964.4b0f25306147075e593c42dbdbdb5c3f28d6e3576dd93a83e383115fa432e0bd.uUFvZYdaE9fPFYJjVlTbhOKqINslDoyBjmjsGqNvESI
+ hash: v1.k794b7964.f8557f29128754128c086b5263c1c6b4485daabbacd9dee43fe1acd0f15a34aa.mTkIO4T5h3EvP-kDhA6mQ7cWL_E9JckkXsHxSqfEEWk
scenes-app-posthog-ai-forms--thread-with-single-question-form--dark:
- hash: v1.k794b7964.30798265f266cd80f34182ebdf0663299797a167f03ee4d6d7d460795e0556f7.vYd-oY6_SVIGdDA1K6PVxY_qlLmCRRXYQqbyoiJfuxU
+ hash: v1.k794b7964.e830a8740c4b0f36caaf39984d7d352fe3187f3f5810283543332f6f833b028d.N1kGYK6zVyTRFKqmNcbU71ZoRk3uNC97qSDGqGk0Jdk
scenes-app-posthog-ai-forms--thread-with-single-question-form--light:
- hash: v1.k794b7964.3245627c76335c65d9e6ca435abb40846390393ed87448de4ea6bc3d20f73770.PZ3pORXbURfNXR75ZcA8Gadgau_ehOmQ9S1bB7kh6M4
+ hash: v1.k794b7964.651890737222ba6f727262dab6f99acdde180762e7f6b77cc31ea561eceb4632.bOFAlQQzkNG3w9fi3NAa3bN5A8C6uPIYgKwqji3nHJk
scenes-app-posthog-ai-forms--thread-with-slider-form--dark:
- hash: v1.k794b7964.40fb0993869cefc014a672e671d7e54cd6945adf8e45401b41792427b8e3d3fb.RVVUD4NsBR0jQu3-97-YZ_OlNHdin1EekglIPj6PIdM
+ hash: v1.k794b7964.5481a40b96036d21a09f5a29dfe20b003c8ef7cc84abddc438886643ada6746c.kEv1RYfuUWE_RyPK9OrqZ3NyV17zbWJHCNUymy77n3A
scenes-app-posthog-ai-forms--thread-with-slider-form--light:
- hash: v1.k794b7964.2ecc1184501441b95bcc9c2c487fb88cfffa4ad70bfb296834b96b02a37c9ba2.WSHkP1FZaItLQqEMKcWgjs7w00-dUb1r3JHYaijjHqI
+ hash: v1.k794b7964.dd203a8a15076c07f8e807ab85ce46e7036e3251b44a95f246c8ea4936c56982.s-dVkPNhcN58zMgn9MGOOlMXqa-Y9a_voS5i5xH2L4g
scenes-app-posthog-ai-forms--thread-with-text-and-number-form--dark:
- hash: v1.k794b7964.3923de3f48ea5edc066d61b076fc42f2ad3504d54c9a86b110680ade93fae5f9.6PwAFhwn4_aCg_ME9ioU9rZqb_9QZRpMpf9L3QBUb14
+ hash: v1.k794b7964.69a1e5eea52abebae062fbccdfcd613e24760bd0843e54c1576cecbee868cc5d.DWFG-7lnbtlTvNy2hvY4v-IliU1BjPk9VaDqkQt4Bh0
scenes-app-posthog-ai-forms--thread-with-text-and-number-form--light:
- hash: v1.k794b7964.f71c93d98ef931b7eb242b48d1eae894ea17896268645853546ac6052df09bba.GZneO2ApKZQ2Jwn_Q3fjdSkBOR1OSv6ad2538VYQUE8
+ hash: v1.k794b7964.aee1550de1b97850cb1d8c27d39e40db81c28d4fe6116a13f48d45672c143710.M1lWbiiqC33CbFfL0ZdteiJH328flmdL2oPxzwPsJgw
scenes-app-posthog-ai-hands-free-surface--speaking--dark:
hash: v1.k794b7964.57e6cf1b2966bbbcac0c6dc1fc79dbcec30647b444819a36036bf414e5b2e620.VxF2LBHOgDjQ7K3quyqD7Lt7Jr7BaC9pAP7aaPI_cKQ
scenes-app-posthog-ai-hands-free-surface--speaking--light:
@@ -8673,13 +8693,13 @@ snapshots:
scenes-app-posthog-ai-tools--changelog-only--light:
hash: v1.k794b7964.db02496ba43c950916b078e95081d7c7ce1465ec9880c52c1334775a66b012d0.Hke-BwLThL2Im6TXKzxK633zeRKWwwtvi9ao1GTXQPU
scenes-app-posthog-ai-tools--dangerous-operation-pending-approval--dark:
- hash: v1.k794b7964.70ae9ee5e2bb82dc37e17102a8d532b7364bb693d4103148b100b0ea789fc9a3.pLWXl8wv17Ii_gk8IIjY9z7yCDe1JZ0sdiBVQ5Ve0gw
+ hash: v1.k794b7964.f22ce4e5d5c9f1a23d800afe1586984e5878639b5a3b0d88bdb0d7291b589971.AZJgwIxLFW2rvV37QZkNPgE6Aw47kXI80HiIZ8yt5nI
scenes-app-posthog-ai-tools--dangerous-operation-pending-approval--light:
- hash: v1.k794b7964.3754f06a9d49f482e434bde25ea397cafec39720eb265bca42e01d5f1910f4bf.EU5aTFsbg5meCAvBL-Yqv2XC_y-Sqf2FAlfohzZDpRM
+ hash: v1.k794b7964.05ad5fbe902c60249adb5303164e33fae7a10ee6dde04096c042ad187bfa113a.xo9-nsBdzZYhOABl8MJBrTxZIQuJayACJj6yZ7UYGNw
scenes-app-posthog-ai-tools--dangerous-operation-pending-approval-long-content--dark:
- hash: v1.k794b7964.6efefb2eea40bb7da59387dcad88fddd7da0f72aafa3846adca5c35180cbfce4.e5vjZcOUH9YJydN1GUN_nJSqg0WJ5I9kLtF_q7hmwP8
+ hash: v1.k794b7964.0422d91f81327d88a231d23c5ccb5fd44263f8e57ce310bcef9323e20bba09d0.Vx-lCyyHe3RgnfIdke2DtmXQnq94flXe64wsicpjE4U
scenes-app-posthog-ai-tools--dangerous-operation-pending-approval-long-content--light:
- hash: v1.k794b7964.6557ac5b0fac9d1f226f12f944e08240e2913aef7d527c4b53a2017d6a7231aa.v61UHKqXj02ZfvDPrQtC2qsl4vPe0oPd98gpiaaQ_2Y
+ hash: v1.k794b7964.1ea5f8d8c313c7f673940c6edfc836738cc9c527b05dfbdf6b5838c5596e66c3.nypVmBTG9h__aSzNLsIU2YoiTuj3XCbxYku4o11eQsA
scenes-app-posthog-ai-tools--multi-visualization-in-thread--dark:
hash: v1.k794b7964.6becd54faf97831df4f4a778c5e8de44acd297727ab9c1def058323cd071be33.PqDN2G62zNR4yAmnMU-xdjNsPU82m7BmBuYCveOsw6E
scenes-app-posthog-ai-tools--multi-visualization-in-thread--light:
@@ -8705,33 +8725,33 @@ snapshots:
scenes-app-posthog-ai-tools--planning-component--light:
hash: v1.k794b7964.77ad908ab65fc3c7732923ff558a6f4cbf811888ea9cddf37c9f2d8611adf59c.boK_sHAD9WEjc6ewXHHR8GSerjmTHvNwC7j8YjLjuLM
scenes-app-posthog-ai-tools--reasoning-component--dark:
- hash: v1.k794b7964.59409cf43ccc3077267c455eb5e37e6400b6cbcdf5514cfacab56561ed877759.w9E4gAmY8i95xkQDdtKDXFParUAMp8W6DJcw4nQOSbg
+ hash: v1.k794b7964.24a261a2c9a87fc7efbc68c966e9e3f25961fb8079a83f2ecddc3b8379f35f01.JzXX6g17oJs5cjc-gy3wmMFn9yOdyRq0BFMLwzFf6AY
scenes-app-posthog-ai-tools--reasoning-component--light:
- hash: v1.k794b7964.dca7da4af36ceebc27cd91f2284cd25cb946bb57519baf051a9f64d2935c4928.E4EffgLrKuLQ122-ICag-EP7jqGV15mkkyoJlpECrW0
+ hash: v1.k794b7964.91c4f63066c200f52c3d444451abb2331bc03d7042f7d084dfe907a0ce24d362.MDaFEjv51UZpGhHvFbUdLh5IefOjJY5fkZkJJJO78DI
scenes-app-posthog-ai-tools--search-error-tracking-issues-empty--dark:
- hash: v1.k794b7964.def15ce7c77b0ab97194e2057379b26d354f6e3bd454dad3e078f1edd45010af.ZfvLWjGTL1-h4MjPI83U9lU3s2k3IVSDjHFCy0P5xCw
+ hash: v1.k794b7964.1131ca6949b0b353c7912562d3338cf0c8bf1681a0f84125b6410b03282a5d65.PrwehQ9wGPTA0tQJiqcvd1er1RH7XsN70K4djdNxgUQ
scenes-app-posthog-ai-tools--search-error-tracking-issues-empty--light:
- hash: v1.k794b7964.455539f043cd9d4688ecb57bf518f514979f0060c34dd1c1443015fb6e84ec77.AWGTsFtR-qmANnp73JFdu4WlzbSrU25sL2WQo0won7I
+ hash: v1.k794b7964.af613133c1a91c86decf05fb53561cdcd56899b5165f6b254013f70f0d1ac315.OdJYbPcjcDIeoDcHhftwd36T328DRNR3bWMvMcejyfw
scenes-app-posthog-ai-tools--search-error-tracking-issues-with-results--dark:
- hash: v1.k794b7964.5c1e4df4e9d429a1e79b38878a9d101467786d921f8042efec0f05c69c6b746a.7cT2z8MJXu_l7qbsKBTowT38AmIh4vyxtpzvZ8XprAE
+ hash: v1.k794b7964.e5cd45cf39eddd361ee27cbbdb0150a32e69337c370f8dcc743b34f84f7e55b2.JqjNvkZkZKJfuy3LK0mafxmAOQYKuz-ZGYle5eVHiwc
scenes-app-posthog-ai-tools--search-error-tracking-issues-with-results--light:
- hash: v1.k794b7964.7f42dfd544b0344e2d9a15b61121c8171cd94e6898d7d76e74bb704265ed6bc6.Qq0epn8rqZJKLjEnXJL7iSc9lqyYnOpIY1PLg1VhZjk
+ hash: v1.k794b7964.1e7edb3844b18ac20e4df2f11161b1e3cec2f1cbe2b192864a895dac316c9ba0.VpJus8i9CB8IJerveWFsmzAHTgGwD6JTK3pWFFS_owk
scenes-app-posthog-ai-tools--search-session-recordings-empty--dark:
- hash: v1.k794b7964.6e39256ff09fec755194c9c99cb7577b406c08abc7e1514638bd2f25c2d3a69c.7bOELSl7z_2pZFHgk7JeTh0BdL2R7ukaRUNgDT2wLuQ
+ hash: v1.k794b7964.d297d8154d85922c06f9bac2f13127271d0193df9fce70c32390db9d03e6e5e9.D-E5T3AUONypA1wqvnD6B_PGop2URx8Jta2ml-ZUnQo
scenes-app-posthog-ai-tools--search-session-recordings-empty--light:
- hash: v1.k794b7964.3032f10f1d24ba2bd94c3b7864aa0e58399b6cfbb2de46992102ce248b948155.vVErlVL-wjJFaSCAtodp1i6Bo8zIbf_F8emM9jrE0JA
+ hash: v1.k794b7964.2952cd367ecb76cd38d7c80f7c69063ae6c5d9c24e6f274aeced4928a6d31213.XnbKXPt9ZjTSCvAKifRzW3f9XUD2LsumgJ62yGzIuyY
scenes-app-posthog-ai-tools--search-session-recordings-with-results--dark:
- hash: v1.k794b7964.8e922cbe8fc0ef6b2f4e9c9ed4ebf13cc8a31988a212346d43752712187c4cef.Nu1Q3mtibOgOBTa3AiBvrIyvrH1lTkBDmlirmMnpSvU
+ hash: v1.k794b7964.7790d13929f3369dc778a78b5638caa31f5bca9d2f37da88307ffe0497d00c7c.M0Pp8Q-ktr2LQskMT6oLS7C3ykhuz12ntvbvsTB70IM
scenes-app-posthog-ai-tools--search-session-recordings-with-results--light:
- hash: v1.k794b7964.5979f8a32840e89fd5575725a16c5128db066033c7a4a93b2f09f43d28ab4e2e.RU5z6eFhEJPVxuCgBCFvbG3DacJh7luaOZNvtUsO72A
+ hash: v1.k794b7964.456d0f829bda1167067b0a3eae143d5bfbdba7e5f50399bddb9fa32cf7c2580d.SFUQJzvJLgHmEP-PPyJERNnBXnUXU_GS6q-Z1U-va-c
scenes-app-posthog-ai-tools--task-execution-component--dark:
- hash: v1.k794b7964.a5907a6dec461381edd6edf117daa693e49faa2992b2fe876c6dfe6614e3cd21.DidAIzzCzluEY9xA-GyzmEJNgQhSjDzDtKgV-dU1Zv0
+ hash: v1.k794b7964.e3dc41a41870cd922d9718898a049b1aa5f885808189d1c6d792d8a062b0c437.H1LkmTALKQy4q6NSC_z5xKy8xWcjkYdLYKbrF8ek4kI
scenes-app-posthog-ai-tools--task-execution-component--light:
- hash: v1.k794b7964.6fa40ed1af111cf070b99419361fa9fc89f3b1c23744cfb86f3c4516db5b0cc8.Gd6L898Ak7ge2TxZfp2pBzhVLh_BjwjwgEg8UYbsgug
+ hash: v1.k794b7964.15f7de2d5b8a2522e95dfc9b81723eb672d95a1ac90f7693a015cf417eab632f.o04xZc4nuuAE4151LWgMT0JfBwWqowDZdUHmHAJhHAE
scenes-app-posthog-ai-tools--task-execution-with-failure--dark:
- hash: v1.k794b7964.e0cfd139759cd4edfd5b2c3fe0031d80ec64e53926601f5115eef8f80d201d00.9MA9rFXTHO8WC2PPvU9OXItexwZucfubQYdMrcSlo0w
+ hash: v1.k794b7964.d2b80939730bde72f5200735588819e4da983497a862733565d1a00b91e844ee.yU8y1RdwfXtNoHThRJqU0fpryNDpmphW06Jj_NWENTQ
scenes-app-posthog-ai-tools--task-execution-with-failure--light:
- hash: v1.k794b7964.a4e89c0399f9e9f4e0d26124b1d2d781cd1a194e7301e802fb770b66842eea79.6xQ5Gxmttf5lGj-DeDgibLZo1mnikN8uwc6uEQZ4NXE
+ hash: v1.k794b7964.e56bc7d3257f75c155232b600debac6d5a1ed42b70475d04b18623807c6cb87f.52_GqnYfKz8PCs66PWQSCwFAiSFvh-99lxxlotFnQe4
scenes-app-posthog-ai-tools--thread-with-sql-query-overflow--dark:
hash: v1.k794b7964.391102534d669872e56c9486d30d2f564a9e585650c4d2f766fd79cf710dfc0e.FzCVV4b9mvwjCrQqe3Rs52Tj5aYHbVNe2IqRInXRDzQ
scenes-app-posthog-ai-tools--thread-with-sql-query-overflow--light:
diff --git a/products/posthog_ai/frontend/components/ActivityDisclosure.tsx b/products/posthog_ai/frontend/components/ActivityDisclosure.tsx
new file mode 100644
index 000000000000..6dbcea50aabd
--- /dev/null
+++ b/products/posthog_ai/frontend/components/ActivityDisclosure.tsx
@@ -0,0 +1,24 @@
+import type { ReactNode } from 'react'
+
+import { CollapsiblePrimitive, CollapsiblePrimitiveContent } from 'lib/ui/Collapsible/lib/CollapsiblePrimitive'
+
+export function ActivityDisclosure({
+ open,
+ id,
+ children,
+}: {
+ open: boolean
+ id?: string
+ children: ReactNode
+}): JSX.Element {
+ return (
+ <CollapsiblePrimitive open={open}>
+ <CollapsiblePrimitiveContent
+ id={id}
+ className="transition-[height,opacity] duration-150 ease-out opacity-100 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0 motion-reduce:transition-none"
+ >
+ {children}
+ </CollapsiblePrimitiveContent>
+ </CollapsiblePrimitive>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/ActivityElapsedTime.tsx b/products/posthog_ai/frontend/components/ActivityElapsedTime.tsx
new file mode 100644
index 000000000000..22d5fca3651c
--- /dev/null
+++ b/products/posthog_ai/frontend/components/ActivityElapsedTime.tsx
@@ -0,0 +1,38 @@
+import { useEffect, useState } from 'react'
+
+import { usePageVisibility } from 'lib/hooks/usePageVisibility'
+
+export function ActivityElapsedTime({
+ startedAt,
+ endedAt,
+ active,
+}: {
+ startedAt?: number
+ endedAt?: number
+ active: boolean
+}): JSX.Element | null {
+ const [now, setNow] = useState(Date.now)
+ const { isVisible } = usePageVisibility()
+ useEffect(() => {
+ if (!active || startedAt === undefined || !isVisible) {
+ return
+ }
+ setNow(Date.now())
+ const interval = setInterval(() => setNow(Date.now()), 1000)
+ return () => clearInterval(interval)
+ }, [active, startedAt, isVisible])
+ const end = active ? now : endedAt
+ if (startedAt === undefined || end === undefined || end < startedAt) {
+ return null
+ }
+ const seconds = Math.floor((end - startedAt) / 1000)
+ return (
+ <span
+ className="tabular-nums text-muted"
+ title="Elapsed time for this activity group, including tools and waiting, not the whole response."
+ >
+ · {seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, '0')}s`}{' '}
+ elapsed
+ </span>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/ActivityPrimitives.test.tsx b/products/posthog_ai/frontend/components/ActivityPrimitives.test.tsx
index 58491c6c05ab..7a6a48ca0209 100644
--- a/products/posthog_ai/frontend/components/ActivityPrimitives.test.tsx
+++ b/products/posthog_ai/frontend/components/ActivityPrimitives.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { render, screen } from '@testing-library/react'
+import { fireEvent, render, screen } from '@testing-library/react'
import { Activity } from './ActivityPrimitives'
@@ -9,6 +9,16 @@ function expectBefore(first: HTMLElement, second: HTMLElement): void {
}
describe('Activity', () => {
+ it('keeps manually opened tool details open when the call completes', () => {
+ const { rerender } = render(
+ <Activity id="tool" title="Read file" status="in_progress" autoExpand={false} details="File contents" />
+ )
+ expect(screen.queryByText('File contents')).not.toBeInTheDocument()
+ fireEvent.click(screen.getByText('Read file'))
+ expect(screen.getByText('File contents')).toBeInTheDocument()
+ rerender(<Activity id="tool" title="Read file" status="completed" autoExpand={false} details="File contents" />)
+ expect(screen.getByText('File contents')).toBeInTheDocument()
+ })
it('renders details before the widget body', () => {
render(
<Activity
diff --git a/products/posthog_ai/frontend/components/ActivityPrimitives.tsx b/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
index 81db70374fad..3fc79c270d13 100644
--- a/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
+++ b/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
@@ -5,6 +5,7 @@ import { IconChevronDown, IconChevronRight } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
import { MarkdownMessage } from '../messages/MarkdownMessage'
+import { ActivityDisclosure } from './ActivityDisclosure'
export type ActivityStatus = 'pending' | 'in_progress' | 'completed' | 'failed'
@@ -96,7 +97,7 @@ export function ActivityHeader({
{isInProgress && animate ? (
<ShimmeringContent>{title}</ShimmeringContent>
) : (
- <span className={clsx('inline-flex', isInProgress && 'text-muted')}>{title}</span>
+ <span className={clsx('inline-flex min-w-0', isInProgress && 'text-muted')}>{title}</span>
)}
</div>
)
@@ -115,12 +116,12 @@ export function ActivityHeader({
// Explicit transition properties, not transition-all: `all` also catches inherited
// scrollbar-color flips from the scrolling ancestor, starting hundreds of no-op
// transitions (and full-document style recalcs) whenever the thread is hovered.
- 'group/activity-header transition-colors duration-500 flex select-none min-w-0',
+ 'group/activity-header transition-colors duration-500 flex items-center gap-2 px-2 min-h-8 select-none min-w-0',
isPending && 'text-muted',
isFailed && 'text-danger',
!isInProgress && !isPending && !isFailed && 'text-default',
hasDetails ? 'cursor-pointer' : 'cursor-default',
- hasDetails && 'rounded px-1 -mx-1 hover:bg-fill-button-tertiary-hover',
+ hasDetails && 'rounded hover:bg-fill-button-tertiary-hover',
hasDetails && isDetailsExpanded && 'bg-fill-button-tertiary-active'
)}
onClick={hasDetails ? onToggleDetails : undefined}
@@ -153,7 +154,12 @@ export function ActivityHeader({
</span>
{hasDetails && (
<span className="absolute inline-flex translate-x-1 scale-90 text-tertiary opacity-0 transition-[color,transform,opacity] duration-200 ease-out group-hover/activity-header:translate-x-0 group-hover/activity-header:scale-100 group-hover/activity-header:text-primary group-hover/activity-header:opacity-100 group-focus-within/activity-header:translate-x-0 group-focus-within/activity-header:scale-100 group-focus-within/activity-header:text-primary group-focus-within/activity-header:opacity-100">
- <IconChevronDown className="size-5" />
+ <IconChevronDown
+ className={clsx(
+ 'size-5 transition-transform duration-150 ease-out motion-reduce:transition-none',
+ !isDetailsExpanded && '-rotate-90'
+ )}
+ />
</span>
)}
</div>
@@ -276,6 +282,8 @@ export function Activity({
substeps = [],
details = null,
children = null,
+ autoExpand = true,
+ onToggleDetails,
}: {
id: string
title: React.ReactNode
@@ -289,9 +297,11 @@ export function Activity({
substeps?: string[]
details?: React.ReactNode
children?: React.ReactNode
+ autoExpand?: boolean
+ onToggleDetails?: (expanded: boolean) => void
}): JSX.Element {
const hasDetails = substeps.length > 0 || !!details
- const shouldExpandDetails = hasDetails && status !== 'completed' && status !== 'failed'
+ const shouldExpandDetails = autoExpand && hasDetails && status !== 'completed' && status !== 'failed'
const [isDetailsExpanded, setIsDetailsExpanded] = useState(shouldExpandDetails)
useLayoutEffect(() => {
@@ -299,7 +309,7 @@ export function Activity({
}, [shouldExpandDetails])
return (
- <div className="flex flex-col rounded w-full min-w-0 gap-1 text-xs">
+ <div className="flex flex-col rounded w-full min-w-0 text-[13px] leading-5 font-normal">
<ActivityHeader
title={title}
status={status}
@@ -307,20 +317,25 @@ export function Activity({
animate={animate}
hasDetails={hasDetails}
isDetailsExpanded={isDetailsExpanded}
- onToggleDetails={() => setIsDetailsExpanded(!isDetailsExpanded)}
+ onToggleDetails={() => {
+ onToggleDetails?.(!isDetailsExpanded)
+ setIsDetailsExpanded(!isDetailsExpanded)
+ }}
showCompletionIcon={showCompletionIcon}
showProgressIcon={showProgressIcon}
failedIcon={failedIcon}
>
{subtitle}
</ActivityHeader>
- {isDetailsExpanded && hasDetails && (
- <ActivityDetails hasIcon={!!icon}>
- {substeps.length > 0 && <ActivitySubsteps id={id} substeps={substeps} status={status} />}
- {details}
- </ActivityDetails>
- )}
- {children}
+ <ActivityDisclosure open={isDetailsExpanded && hasDetails}>
+ <div className="pt-1">
+ <ActivityDetails hasIcon={!!icon}>
+ {substeps.length > 0 && <ActivitySubsteps id={id} substeps={substeps} status={status} />}
+ {details}
+ </ActivityDetails>
+ </div>
+ </ActivityDisclosure>
+ {children && <div className="pt-1">{children}</div>}
</div>
)
}
diff --git a/products/posthog_ai/frontend/components/PermissionInput.tsx b/products/posthog_ai/frontend/components/PermissionInput.tsx
index 3969f63f82ec..942959c1ce60 100644
--- a/products/posthog_ai/frontend/components/PermissionInput.tsx
+++ b/products/posthog_ai/frontend/components/PermissionInput.tsx
@@ -246,7 +246,6 @@ function PermissionOptionRows({ options, responding, onRespond }: PermissionOpti
const active = selectedIndex === index || hoveredIndex === index
const editing = isFeedbackOption(option) && selectedIndex === index
const sublabel = optionSublabel(option)
- const showSublabel = sublabel && (editing || active)
return (
<div
key={option.optionId}
@@ -307,7 +306,7 @@ function PermissionOptionRows({ options, responding, onRespond }: PermissionOpti
)}
</div>
</div>
- {showSublabel && <p className="mt-0.5 mb-0 pl-10 text-xs text-muted">{sublabel}</p>}
+ {sublabel && <p className="mt-0.5 mb-0 pl-10 text-xs text-muted">{sublabel}</p>}
</div>
)
})}
diff --git a/products/posthog_ai/frontend/components/QuestionRenderer.test.tsx b/products/posthog_ai/frontend/components/QuestionRenderer.test.tsx
index 3c6a18d07e73..8da44614729c 100644
--- a/products/posthog_ai/frontend/components/QuestionRenderer.test.tsx
+++ b/products/posthog_ai/frontend/components/QuestionRenderer.test.tsx
@@ -38,29 +38,33 @@ describe('QuestionRenderer', () => {
cleanup()
})
- it('previews the answer on the second line and shows the full Q&A on expand', () => {
+ it('shows the full Q&A on expand', () => {
renderCard(makeMessage({ rawOutput: { answers: { 'Which goal matters most?': 'Revenue' } } }))
- // Preview on the header's second line (always visible).
- expect(screen.getByText('Revenue')).toBeInTheDocument()
+ expect(screen.queryByText('Revenue')).not.toBeInTheDocument()
// The full question + answer live in the collapsible body.
expect(screen.queryByText('Which goal matters most?')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button'))
expect(screen.getByText('Which goal matters most?')).toBeInTheDocument()
- expect(screen.getAllByText('Revenue').some((el) => el.classList.contains('font-medium'))).toBe(true)
+ expect(screen.getByText('Revenue')).toBeInTheDocument()
// The header label ("Goal") is dropped from the recap.
expect(screen.queryByText('Goal')).not.toBeInTheDocument()
})
- it('does not render a body while the question is still being asked', () => {
- renderCard(makeMessage({ status: 'in_progress', rawOutput: undefined }))
+ it.each(['in_progress', 'failed', 'completed'] as const)(
+ 'lets the user read an unanswered question when the call is %s',
+ (status) => {
+ renderCard(makeMessage({ status, rawOutput: undefined }))
- expect(screen.queryByText('Which goal matters most?')).not.toBeInTheDocument()
- expect(screen.queryByRole('button')).not.toBeInTheDocument()
- })
+ expect(screen.queryByText('Which goal matters most?')).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button'))
+ expect(screen.getByText('Which goal matters most?')).toBeVisible()
+ expect(screen.queryByText('Revenue')).not.toBeInTheDocument()
+ }
+ )
- it('recaps each answer for a multi-question request', () => {
+ it('retains unanswered questions alongside answers for a partially answered request', () => {
renderCard(
makeMessage({
rawInput: {
@@ -69,25 +73,33 @@ describe('QuestionRenderer', () => {
{ question: 'When?', header: 'When', multiSelect: false, options: [{ label: 'Weekly' }] },
],
},
- rawOutput: { answers: { 'Goal?': 'Revenue', 'When?': 'Weekly' } },
+ rawOutput: { answers: { 'Goal?': 'Revenue' } },
})
)
fireEvent.click(screen.getByRole('button'))
expect(screen.getByText('Revenue')).toBeInTheDocument()
- expect(screen.getByText('Weekly')).toBeInTheDocument()
+ expect(screen.getByText('When?')).toBeInTheDocument()
+ expect(screen.queryByText('Weekly')).not.toBeInTheDocument()
})
it('falls back to a joined answer string when there is no per-question map', () => {
renderCard(makeMessage({ rawOutput: { text: 'User picked Revenue' } }))
+ fireEvent.click(screen.getByRole('button'))
expect(screen.getByText('User picked Revenue')).toBeInTheDocument()
})
it('shows the error message when the call failed', () => {
- renderCard(makeMessage({ status: 'failed', rawOutput: undefined, error: { message: 'Question timed out' } }))
+ const title = 'Choose a goal for this analysis before continuing with the remaining steps.'
+ renderCard(
+ makeMessage({ title, status: 'failed', rawOutput: undefined, error: { message: 'Question timed out' } })
+ )
expect(screen.getByText('Question timed out')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button'))
+ expect(screen.getByText(title)).toBeInTheDocument()
+ expect(screen.getByText('Which goal matters most?')).toBeVisible()
})
it('falls back to the generic tool card when the input has no questions', () => {
diff --git a/products/posthog_ai/frontend/components/QuestionRenderer.tsx b/products/posthog_ai/frontend/components/QuestionRenderer.tsx
index 2bd8bf6fafc5..9baf28d3b494 100644
--- a/products/posthog_ai/frontend/components/QuestionRenderer.tsx
+++ b/products/posthog_ai/frontend/components/QuestionRenderer.tsx
@@ -7,14 +7,12 @@ import {
} from '../policy/questionUtils'
import { GenericMcpToolRenderer } from './tool/GenericMcpToolRenderer'
import { ToolActivity } from './tool/ToolActivity'
-import { truncateText } from './tool/toolContentUtils'
import type { ToolRendererProps } from './tool/toolRegistry'
/**
* Thread recap for the `AskUserQuestion` Claude built-in. The interactive answering happens in the
- * input overlay (`QuestionInput`); this is the transcript record: the chosen answers preview on
- * the header's second line, and the full question + answer in the expandable body. Malformed input
- * falls back to the generic tool card.
+ * input overlay (`QuestionInput`). The transcript details retain every question, including unanswered
+ * ones, and any chosen answers. Malformed input falls back to the generic tool card.
*/
export function QuestionRenderer(props: ToolRendererProps): JSX.Element {
const { message, icon, displayName, turnComplete, turnCancelled } = props
@@ -30,33 +28,27 @@ export function QuestionRenderer(props: ToolRendererProps): JSX.Element {
const fallbackAnswer =
Object.keys(answersByKey).length === 0 ? extractSandboxQuestionAnswer(message.rawOutput) : null
- const answered = questions
- .map((question, index) => {
- const answer = answersByKey[question.question] ?? (index === 0 ? fallbackAnswer : null)
- return answer ? { question: question.question, answer } : null
- })
- .filter((entry): entry is { question: string; answer: string } => entry !== null)
-
- const answerPreview = answered.map((entry) => entry.answer).join(', ')
-
- const body =
- answered.length > 0 ? (
- <div className="flex flex-col gap-3">
- {answered.map((entry, index) => (
- <div key={index} className="flex flex-col gap-1 text-xs">
- <div className="text-muted">{entry.question}</div>
- <span className="font-medium text-secondary">{entry.answer}</span>
- </div>
- ))}
- </div>
- ) : undefined
+ const entries = questions.map((question, index) => ({
+ question: question.question,
+ answer: answersByKey[question.question] ?? (index === 0 ? fallbackAnswer : null),
+ }))
+
+ const body = (
+ <div className="flex flex-col gap-3 break-words">
+ {entries.map((entry, index) => (
+ <div key={index} className="flex flex-col gap-1 text-xs">
+ <div className="text-muted">{entry.question}</div>
+ {entry.answer && <span className="font-medium text-secondary">{entry.answer}</span>}
+ </div>
+ ))}
+ </div>
+ )
return (
<ToolActivity
message={message}
icon={icon ?? <IconAI />}
title={message.title || displayName || 'Question'}
- subtitle={answerPreview ? truncateText(answerPreview, 120) : undefined}
body={body}
turnComplete={turnComplete}
turnCancelled={turnCancelled}
diff --git a/products/posthog_ai/frontend/components/RunContext.tsx b/products/posthog_ai/frontend/components/RunContext.tsx
index 188753a1595e..47a2d4bff773 100644
--- a/products/posthog_ai/frontend/components/RunContext.tsx
+++ b/products/posthog_ai/frontend/components/RunContext.tsx
@@ -23,10 +23,13 @@ export const RunContext = memo(function RunContext({
}): JSX.Element {
return (
<div
- className={cn('flex items-center gap-1.5 px-3 py-1 text-xs text-muted', className)}
+ className={cn(
+ 'flex items-center gap-2 px-2 py-1 min-h-8 text-[13px] leading-5 font-normal text-muted',
+ className
+ )}
data-attr="max-sandbox-run-context"
>
- <IconGitBranch className="size-3.5 shrink-0" />
+ <IconGitBranch className="size-5 shrink-0" />
<span className="min-w-0 truncate">
Working on{' '}
{repo ? (
diff --git a/products/posthog_ai/frontend/components/ThreadActivityGroup.stories.tsx b/products/posthog_ai/frontend/components/ThreadActivityGroup.stories.tsx
new file mode 100644
index 000000000000..0ddf6aab36c5
--- /dev/null
+++ b/products/posthog_ai/frontend/components/ThreadActivityGroup.stories.tsx
@@ -0,0 +1,81 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import type { ToolInvocation } from '../types/streamTypes'
+import type { ThreadActivityGroup as ActivityGroup } from '../utils/groupThreadActivity'
+import { ThreadActivityGroup } from './ThreadActivityGroup'
+import { ThreadRow } from './ThreadRow'
+
+const tools = new Map<string, ToolInvocation>(
+ Array.from({ length: 300 }, (_, index) => {
+ const id = `example-call-${index}`
+ return [
+ id,
+ {
+ toolCallId: id,
+ rawServerName: 'example',
+ rawToolName: 'read_report',
+ title: `Read example report ${index + 1}`,
+ input: { report: index + 1 },
+ status: index === 148 ? 'failed' : 'completed',
+ error: index === 148 ? { message: 'Example report is unavailable' } : undefined,
+ contentBlocks: [
+ {
+ type: 'text',
+ text: Array.from({ length: 30 }, (_, line) => `Example result ${line + 1}`).join('\n'),
+ },
+ ],
+ },
+ ]
+ })
+)
+const group: ActivityGroup = {
+ id: 'example-activity',
+ type: 'activity_group',
+ startedAt: 1000,
+ endedAt: 65000,
+ items: [...tools.keys()].map((id) => ({ id, type: 'tool_invocation', toolCallId: id })),
+}
+
+const meta: Meta<typeof ThreadActivityGroup> = {
+ title: 'Products/PostHog AI/ThreadActivityGroup',
+ component: ThreadActivityGroup,
+ args: {
+ group,
+ toolInvocations: tools,
+ active: false,
+ cancelled: false,
+ renderItem: (item) => (
+ <ThreadRow
+ item={item}
+ isLast={false}
+ isThinking={false}
+ toolInvocations={tools}
+ turnComplete
+ turnCancelled={false}
+ />
+ ),
+ },
+ decorators: [
+ (Story, { parameters }) => (
+ <div className={parameters.narrow ? 'w-96 p-4' : 'w-180 p-4'}>
+ <Story />
+ </div>
+ ),
+ ],
+}
+export default meta
+type Story = StoryObj<typeof ThreadActivityGroup>
+
+export const LongHistory: Story = {}
+export const ShortHistory: Story = { args: { group: { ...group, items: group.items.slice(0, 4) } } }
+export const UnknownTiming: Story = { args: { group: { ...group, startedAt: undefined } } }
+export const Narrow: Story = { parameters: { narrow: true } }
+export const ThoughtOnly: Story = {
+ args: {
+ group: {
+ id: 'example-thought',
+ type: 'activity_group',
+ items: [{ id: 'thought', type: 'assistant_thought', text: 'Compare the available approaches.' }],
+ },
+ },
+}
diff --git a/products/posthog_ai/frontend/components/ThreadActivityGroup.test.tsx b/products/posthog_ai/frontend/components/ThreadActivityGroup.test.tsx
new file mode 100644
index 000000000000..d4a8eaf7ea0f
--- /dev/null
+++ b/products/posthog_ai/frontend/components/ThreadActivityGroup.test.tsx
@@ -0,0 +1,270 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+
+import { ReasoningAnswer } from '../messages/ReasoningAnswer'
+import type { ToolInvocation } from '../types/streamTypes'
+import type { ThreadActivityGroup as ActivityGroup } from '../utils/groupThreadActivity'
+import { Activity } from './ActivityPrimitives'
+import { ThreadActivityGroup } from './ThreadActivityGroup'
+import { VirtualizedThread } from './VirtualizedThread'
+
+jest.mock('../messages/MarkdownMessage', () => ({
+ MarkdownMessage: ({ content }: { content: string }) => <div>{content}</div>,
+}))
+
+describe('ThreadActivityGroup', () => {
+ afterEach(() => {
+ cleanup()
+ jest.restoreAllMocks()
+ })
+
+ it.each([2, 11])('keeps expansions while following %i calls and freezes the list after scrolling away', (count) => {
+ const following = jest.spyOn(VirtualizedThread, 'useIsFollowing').mockReturnValue(true)
+ const tools = new Map<string, ToolInvocation>()
+ const makeGroup = (length: number): ActivityGroup => ({
+ id: 'streaming',
+ type: 'activity_group',
+ items: Array.from({ length }, (_, index) => {
+ const id = `call-${index}`
+ tools.set(id, {
+ toolCallId: id,
+ rawServerName: 'example',
+ rawToolName: 'read',
+ input: {},
+ status: 'completed',
+ contentBlocks: [],
+ })
+ return { id, type: 'tool_invocation', toolCallId: id }
+ }),
+ })
+ const renderGroup = (group: ActivityGroup): JSX.Element => (
+ <ThreadActivityGroup
+ group={group}
+ toolInvocations={tools}
+ active
+ cancelled={false}
+ renderItem={(item) => (
+ <Activity
+ id={item.id}
+ title={item.id}
+ status="completed"
+ autoExpand={false}
+ details={`Details for ${item.id}`}
+ />
+ )}
+ />
+ )
+ const { rerender } = render(renderGroup(makeGroup(count)))
+ fireEvent.click(screen.getByTestId('thread-activity-toggle'))
+ fireEvent.click(screen.getAllByTestId('thread-tool-chain').at(-1)!.querySelector('[role="button"]')!)
+ fireEvent.click(screen.getByText(`call-${count - 1}`))
+ expect(screen.getByText(`Details for call-${count - 1}`)).toBeVisible()
+
+ rerender(renderGroup(makeGroup(count + 1)))
+ expect(screen.getByText(`call-${count}`)).toBeVisible()
+ expect(screen.getByText(`Details for call-${count - 1}`)).toBeVisible()
+ expect(screen.queryByTestId('thread-activity-refresh')).not.toBeInTheDocument()
+
+ following.mockReturnValue(false)
+ rerender(renderGroup(makeGroup(count + 2)))
+ expect(screen.queryByText(`call-${count + 1}`)).not.toBeInTheDocument()
+ expect(screen.getByTestId('thread-activity-refresh')).toHaveTextContent('Show 1 new activity')
+ expect(screen.getByText(`Details for call-${count - 1}`)).toBeVisible()
+
+ following.mockReturnValue(true)
+ rerender(renderGroup(makeGroup(count + 2)))
+ expect(screen.getByText(`call-${count + 1}`)).toBeVisible()
+ expect(screen.queryByTestId('thread-activity-refresh')).not.toBeInTheDocument()
+ expect(screen.getByText(`Details for call-${count - 1}`)).toBeVisible()
+ })
+
+ it('collapses consecutive tools into a chain while keeping failures and individual calls accessible', () => {
+ const tools = new Map<string, ToolInvocation>(
+ ['first', 'second', 'third'].map((id, index) => [
+ id,
+ {
+ toolCallId: id,
+ rawServerName: 'posthog',
+ rawToolName: 'exec',
+ input: { command: 'call execute-sql {}' },
+ status: index === 1 ? 'failed' : 'completed',
+ contentBlocks: [],
+ },
+ ])
+ )
+ render(
+ <ThreadActivityGroup
+ group={{
+ id: 'group',
+ type: 'activity_group',
+ items: [...tools.keys()].map((id) => ({ id, type: 'tool_invocation', toolCallId: id })),
+ }}
+ toolInvocations={tools}
+ active={false}
+ cancelled={false}
+ renderItem={(item) => <div>{item.id}</div>}
+ />
+ )
+ fireEvent.click(screen.getByTestId('thread-activity-toggle'))
+ const chain = screen.getByTestId('thread-tool-chain')
+ expect(chain).toHaveTextContent('execute-sql· 3 calls· 1 failed')
+ expect(screen.queryByText('first')).not.toBeInTheDocument()
+ fireEvent.click(chain.querySelector('[role="button"]')!)
+ for (const id of tools.keys()) {
+ expect(screen.getByText(id)).toBeVisible()
+ }
+ })
+
+ it('reveals thought-only activity with one click and keeps streamed text readable when a tool arrives', () => {
+ const tools = new Map<string, ToolInvocation>()
+ const group: ActivityGroup = {
+ id: 'thoughts',
+ type: 'activity_group',
+ items: [{ id: 'thought-1', type: 'assistant_thought', text: 'Compare the available approaches.' }],
+ }
+ const renderGroup = (value: ActivityGroup): JSX.Element => (
+ <ThreadActivityGroup
+ group={value}
+ toolInvocations={tools}
+ active
+ cancelled={false}
+ renderItem={(item) =>
+ item.type === 'assistant_thought' ? (
+ <ReasoningAnswer id={item.id} content={item.text ?? ''} completed />
+ ) : (
+ <div>{item.id}</div>
+ )
+ }
+ />
+ )
+ const { rerender } = render(renderGroup(group))
+ expect(screen.getByTestId('thread-activity-toggle')).toHaveTextContent('Thinking')
+ fireEvent.click(screen.getByTestId('thread-activity-toggle'))
+ expect(screen.getByText('Compare the available approaches.')).toBeVisible()
+ expect(screen.getAllByRole('button')).toHaveLength(1)
+
+ const updatedThought = { ...group.items[0], text: 'Compare the approaches and check the source.' }
+ tools.set('call-1', {
+ toolCallId: 'call-1',
+ rawServerName: 'example',
+ rawToolName: 'read',
+ input: {},
+ status: 'in_progress',
+ contentBlocks: [],
+ })
+ rerender(
+ renderGroup({
+ ...group,
+ items: [updatedThought, { id: 'call-1', type: 'tool_invocation', toolCallId: 'call-1' }],
+ })
+ )
+ expect(screen.getByText(updatedThought.text)).toBeVisible()
+ expect(screen.queryByText('call-1')).not.toBeInTheDocument()
+ expect(screen.getByTestId('thread-activity-refresh')).toHaveTextContent('Show 1 new activity')
+ })
+
+ it('keeps the inspected rows stable while new calls arrive and adds hidden failures without replacing them', async () => {
+ const tools = new Map<string, ToolInvocation>(
+ Array.from({ length: 12 }, (_, index) => {
+ const id = `call-${index}`
+ return [
+ id,
+ {
+ toolCallId: id,
+ rawServerName: 'example',
+ rawToolName: index % 2 === 0 ? 'read' : 'search',
+ input: {},
+ status: 'in_progress',
+ contentBlocks: [],
+ },
+ ]
+ })
+ )
+ const group: ActivityGroup = {
+ id: 'group',
+ type: 'activity_group',
+ items: [...tools.keys()].slice(0, 11).map((id) => ({ id, type: 'tool_invocation', toolCallId: id })),
+ }
+ const renderGroup = (value: ActivityGroup): JSX.Element => (
+ <ThreadActivityGroup
+ group={value}
+ toolInvocations={tools}
+ active={false}
+ cancelled={false}
+ renderItem={(item) => (
+ <div data-attr="test-activity-row">
+ {item.id}: {tools.get(item.id)?.status}
+ </div>
+ )}
+ />
+ )
+ const { rerender } = render(renderGroup(group))
+ fireEvent.click(screen.getByTestId('thread-activity-toggle'))
+ expect(screen.getAllByTestId('test-activity-row')).toHaveLength(5)
+ tools.set('call-10', { ...tools.get('call-10')!, status: 'failed' })
+ tools.set('call-5', { ...tools.get('call-5')!, status: 'failed' })
+ const next: ActivityGroup = {
+ ...group,
+ items: [...group.items, { id: 'call-11', type: 'tool_invocation', toolCallId: 'call-11' }],
+ }
+ rerender(renderGroup(next))
+ expect(screen.getByTestId('thread-activity-toggle')).toHaveTextContent('2 tool calls failed')
+ expect(screen.getByText('call-10: failed')).toBeInTheDocument()
+ expect(screen.queryByText('call-11: in_progress')).not.toBeInTheDocument()
+ fireEvent.click(screen.getByTestId('thread-activity-refresh'))
+ expect(screen.getByText('call-11: in_progress')).toBeInTheDocument()
+ fireEvent.click(screen.getByTestId('thread-activity-failures'))
+ expect(screen.getAllByTestId('test-activity-row')).toHaveLength(6)
+ expect(screen.getByText('call-5: failed')).toBeInTheDocument()
+ expect(screen.getByText('call-10: failed')).toBeInTheDocument()
+ expect(screen.getByText('call-11: in_progress')).toBeInTheDocument()
+ fireEvent.click(screen.getByTestId('thread-activity-failures'))
+ await waitFor(() => expect(screen.queryByText('call-5: failed')).not.toBeInTheDocument())
+ expect(screen.getAllByTestId('test-activity-row')).toHaveLength(5)
+ })
+
+ it('pages additional failures without changing the ordinary activity page or duplicating visible calls', () => {
+ const tools = new Map<string, ToolInvocation>(
+ Array.from({ length: 300 }, (_, index) => {
+ const id = `failure-${index}`
+ return [
+ id,
+ {
+ toolCallId: id,
+ rawServerName: 'example',
+ rawToolName: index % 2 === 0 ? 'read' : 'search',
+ input: {},
+ status: 'failed',
+ contentBlocks: [],
+ },
+ ]
+ })
+ )
+ const group: ActivityGroup = {
+ id: 'failures',
+ type: 'activity_group',
+ items: [...tools.keys()].map((id) => ({ id, type: 'tool_invocation', toolCallId: id })),
+ }
+ render(
+ <ThreadActivityGroup
+ group={group}
+ toolInvocations={tools}
+ active={false}
+ cancelled={false}
+ renderItem={(item) => <div data-attr="test-activity-row">{item.id}</div>}
+ />
+ )
+ fireEvent.click(screen.getByTestId('thread-activity-toggle'))
+ fireEvent.click(screen.getByTestId('thread-activity-more'))
+ fireEvent.click(screen.getByTestId('thread-activity-next'))
+ const originalRows = screen.getAllByTestId('test-activity-row').map((row) => row.textContent)
+ fireEvent.click(screen.getByTestId('thread-activity-failures'))
+ expect(screen.getAllByTestId('test-activity-row')).toHaveLength(25)
+ fireEvent.click(screen.getByTestId('thread-activity-failures-next'))
+ const rows = screen.getAllByTestId('test-activity-row').map((row) => row.textContent)
+ expect(new Set(rows).size).toBe(25)
+ originalRows.forEach((text) => expect(rows).toContain(text))
+ expect(screen.getByText('Page 2 of 30')).toBeInTheDocument()
+ })
+})
diff --git a/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx b/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx
new file mode 100644
index 000000000000..ab890e18f389
--- /dev/null
+++ b/products/posthog_ai/frontend/components/ThreadActivityGroup.tsx
@@ -0,0 +1,329 @@
+import { Fragment, type ReactNode, useEffect, useState } from 'react'
+
+import { IconChevronRight, IconSpinner } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { MarkdownMessage } from '../messages/MarkdownMessage'
+import type { ThreadItem, ToolInvocation } from '../types/streamTypes'
+import {
+ activityWindow,
+ groupConsecutiveTools,
+ type ThreadActivityGroup as ActivityGroup,
+} from '../utils/groupThreadActivity'
+import { resolveToolCall } from '../utils/toolResolver'
+import { ActivityDisclosure } from './ActivityDisclosure'
+import { ActivityElapsedTime } from './ActivityElapsedTime'
+import { Activity } from './ActivityPrimitives'
+import { lookupToolRenderer } from './tool/toolRegistry'
+import { VirtualizedThread } from './VirtualizedThread'
+
+export function ThreadActivityGroup({
+ group,
+ toolInvocations,
+ active,
+ cancelled,
+ waitingForInput = false,
+ renderItem,
+}: {
+ group: ActivityGroup
+ toolInvocations: Map<string, ToolInvocation>
+ active: boolean
+ cancelled: boolean
+ waitingForInput?: boolean
+ renderItem: (item: ThreadItem) => ReactNode
+}): JSX.Element {
+ const pauseFollowing = VirtualizedThread.usePauseFollowing()
+ const isFollowing = VirtualizedThread.useIsFollowing()
+ const [expanded, setExpanded] = useState(false)
+ const [visibleIds, setVisibleIds] = useState<string[]>([])
+ const [middlePage, setMiddlePage] = useState(0)
+ const [showMiddle, setShowMiddle] = useState(false)
+ const [showFailures, setShowFailures] = useState(false)
+ const [failurePage, setFailurePage] = useState(0)
+ useEffect(() => {
+ if (expanded && isFollowing) {
+ setVisibleIds((previous) =>
+ previous.length === group.items.length && previous.every((id, index) => id === group.items[index].id)
+ ? previous
+ : group.items.map((item) => item.id)
+ )
+ }
+ }, [expanded, isFollowing, group.items])
+ const calls = group.items.flatMap((item) => {
+ const call = item.toolCallId ? toolInvocations.get(item.toolCallId) : undefined
+ return call ? [call] : []
+ })
+ const failures = calls.filter((call) => call.status === 'failed')
+ const thoughtsOnly = group.items.every((item) => item.type === 'assistant_thought')
+ const activeLabel = thoughtsOnly ? 'Thinking' : 'Working'
+ const finishedLabel = thoughtsOnly ? 'Thought' : 'Worked'
+ const label = waitingForInput ? 'Waiting for you' : active ? activeLabel : cancelled ? 'Stopped' : finishedLabel
+ const current = active
+ ? calls.findLast((call) => call.status === 'in_progress' || call.status === 'pending')
+ : undefined
+ const resolved = current ? resolveToolCall(current) : undefined
+ const currentLabel =
+ current && resolved
+ ? current.title || lookupToolRenderer(resolved.resolvedKey, !!resolved.innerToolName).displayName
+ : 'Thinking…'
+ const visible = new Set(visibleIds)
+ const snapshot = isFollowing ? group.items : group.items.filter((item) => visible.has(item.id))
+ const visibleThoughtsOnly = snapshot.every((item) => item.type === 'assistant_thought')
+ const chainKeys = new Map(
+ groupConsecutiveTools(group.items, toolInvocations).flatMap((chain) =>
+ chain.map((item) => [item.id, chain[0].id] as const)
+ )
+ )
+ const window = activityWindow(snapshot, middlePage)
+ const displayedIds = new Set(
+ [...window.first, ...(showMiddle ? window.middle : []), ...window.last].map((item) => item.id)
+ )
+ const additionalFailures = snapshot.filter(
+ (item) =>
+ !displayedIds.has(item.id) && item.toolCallId && toolInvocations.get(item.toolCallId)?.status === 'failed'
+ )
+ const failurePageCount = Math.ceil(additionalFailures.length / 10)
+ const currentFailurePage = Math.max(0, Math.min(failurePage, failurePageCount - 1))
+ const newCount = isFollowing ? 0 : group.items.filter((item) => !visible.has(item.id)).length
+ const toggle = (): void => {
+ if (!expanded) {
+ setVisibleIds(group.items.map((item) => item.id))
+ }
+ setExpanded(!expanded)
+ }
+ const individualRows = (items: ThreadItem[]): ReactNode =>
+ items.map((item) => (
+ <Fragment key={item.id}>
+ {visibleThoughtsOnly ? (
+ <div className="text-muted">
+ <MarkdownMessage id={item.id} content={item.text ?? ''} />
+ </div>
+ ) : (
+ renderItem(item)
+ )}
+ </Fragment>
+ ))
+ const rows = (items: ThreadItem[]): ReactNode =>
+ groupConsecutiveTools(items, toolInvocations).map((chain) => {
+ if (chain.length === 1) {
+ return <Fragment key={chain[0].id}>{individualRows(chain)}</Fragment>
+ }
+ const chainCalls = chain.map((item) => toolInvocations.get(item.toolCallId!)!)
+ const resolved = resolveToolCall(chainCalls[0])
+ const entry = lookupToolRenderer(resolved.resolvedKey, !!resolved.innerToolName)
+ const failed = chainCalls.filter((call) => call.status === 'failed').length
+ const running =
+ active && chainCalls.some((call) => call.status === 'pending' || call.status === 'in_progress')
+ return (
+ <div key={chainKeys.get(chain[0].id)} data-attr="thread-tool-chain">
+ <Activity
+ id={`chain-${chain[0].id}`}
+ title={
+ <span className="flex items-center gap-2 min-w-0">
+ <span className="truncate">{entry.displayName}</span>
+ <span className="text-muted shrink-0">· {chain.length} calls</span>
+ {failed > 0 && <span className="text-danger shrink-0">· {failed} failed</span>}
+ </span>
+ }
+ icon={entry.icon}
+ status={running ? 'in_progress' : 'completed'}
+ animate={false}
+ autoExpand={false}
+ details={<div className="flex flex-col gap-1 min-w-0">{individualRows(chain)}</div>}
+ />
+ </div>
+ )
+ })
+
+ return (
+ <div
+ className="flex flex-col gap-1 min-w-0 text-[13px] leading-5 font-normal"
+ data-attr="thread-activity-group"
+ >
+ <LemonButton
+ type="tertiary"
+ size="small"
+ fullWidth
+ onClick={toggle}
+ aria-expanded={expanded}
+ aria-controls={`activity-details-${group.id}`}
+ data-attr="thread-activity-toggle"
+ icon={
+ <span className="flex size-5 items-center justify-center">
+ <IconChevronRight
+ className={`text-[13px] transition-transform duration-150 ease-out motion-reduce:transition-none ${expanded ? 'rotate-90' : ''}`}
+ />
+ </span>
+ }
+ >
+ <span className="flex items-center gap-2 flex-wrap min-w-0 text-[13px] leading-5 font-normal">
+ <span>{label}</span>
+ {active && !waitingForInput && <IconSpinner className="animate-spin motion-reduce:animate-none" />}
+ {!waitingForInput && (
+ <ActivityElapsedTime startedAt={group.startedAt} endedAt={group.endedAt} active={active} />
+ )}
+ {calls.length > 0 && (
+ <span
+ className="text-muted tabular-nums"
+ title="Tool calls in this activity group, not the whole response. Calls shown separately are not included."
+ >
+ ·{' '}
+ <span
+ key={calls.length}
+ className="inline-block animate-fade-in [animation-duration:150ms] motion-reduce:animate-none"
+ >
+ {calls.length}
+ </span>{' '}
+ tool {calls.length === 1 ? 'call' : 'calls'}
+ </span>
+ )}
+ {failures.length > 0 && (
+ <span className="text-danger">
+ · {failures.length} tool {failures.length === 1 ? 'call' : 'calls'} failed
+ </span>
+ )}
+ </span>
+ </LemonButton>
+ {active && (!thoughtsOnly || waitingForInput) && (
+ <div className="pl-9 text-muted truncate h-5" title={currentLabel}>
+ {waitingForInput ? 'Review the request below' : currentLabel}
+ </div>
+ )}
+ <ActivityDisclosure open={expanded} id={`activity-details-${group.id}`}>
+ <div className="ml-3 pl-3 border-l border-border-secondary flex flex-col gap-1 min-w-0">
+ {(additionalFailures.length > 0 || showFailures) && (
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ status="danger"
+ data-attr="thread-activity-failures"
+ aria-expanded={showFailures}
+ aria-controls={`activity-failures-${group.id}`}
+ onClick={() => {
+ pauseFollowing()
+ setShowFailures(!showFailures)
+ }}
+ >
+ {showFailures
+ ? 'Hide additional failed calls'
+ : `Show ${additionalFailures.length} hidden failed ${additionalFailures.length === 1 ? 'call' : 'calls'}`}
+ </LemonButton>
+ )}
+ <ActivityDisclosure open={showFailures} id={`activity-failures-${group.id}`}>
+ <div
+ className="flex flex-col gap-1 pb-2 border-b border-border-secondary"
+ data-attr="thread-activity-additional-failures"
+ >
+ {additionalFailures.length === 0 && (
+ <span className="text-muted">All failed calls are visible in the activity below.</span>
+ )}
+ {failurePageCount > 1 && (
+ <div className="flex items-center gap-2 flex-wrap text-muted">
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ data-attr="thread-activity-failures-previous"
+ disabledReason={currentFailurePage === 0 ? 'First page' : undefined}
+ onClick={() => {
+ pauseFollowing()
+ setFailurePage(currentFailurePage - 1)
+ }}
+ >
+ Previous
+ </LemonButton>
+ <span>
+ Failed calls {currentFailurePage * 10 + 1}–
+ {Math.min((currentFailurePage + 1) * 10, additionalFailures.length)} of{' '}
+ {additionalFailures.length}
+ </span>
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ data-attr="thread-activity-failures-next"
+ disabledReason={
+ currentFailurePage + 1 === failurePageCount ? 'Last page' : undefined
+ }
+ onClick={() => {
+ pauseFollowing()
+ setFailurePage(currentFailurePage + 1)
+ }}
+ >
+ Next
+ </LemonButton>
+ </div>
+ )}
+ {individualRows(
+ additionalFailures.slice(currentFailurePage * 10, (currentFailurePage + 1) * 10)
+ )}
+ </div>
+ </ActivityDisclosure>
+ {rows(window.first)}
+ {window.hiddenCount > 0 && (
+ <>
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ data-attr="thread-activity-more"
+ aria-expanded={showMiddle}
+ aria-controls={`activity-middle-${group.id}`}
+ onClick={() => {
+ pauseFollowing()
+ setShowMiddle(!showMiddle)
+ }}
+ >
+ {showMiddle ? 'Hide middle activity' : `Show ${window.hiddenCount} more`}
+ </LemonButton>
+ <ActivityDisclosure open={showMiddle} id={`activity-middle-${group.id}`}>
+ <div className="flex flex-col gap-1 min-w-0">
+ <div className="flex items-center gap-2 flex-wrap text-muted">
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ disabledReason={window.page === 0 ? 'First page' : undefined}
+ onClick={() => {
+ pauseFollowing()
+ setMiddlePage(window.page - 1)
+ }}
+ data-attr="thread-activity-previous"
+ >
+ Previous
+ </LemonButton>
+ <span>
+ Page {window.page + 1} of {window.pageCount}
+ </span>
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ disabledReason={
+ window.page + 1 === window.pageCount ? 'Last page' : undefined
+ }
+ onClick={() => {
+ pauseFollowing()
+ setMiddlePage(window.page + 1)
+ }}
+ data-attr="thread-activity-next"
+ >
+ Next
+ </LemonButton>
+ </div>
+ {rows(window.middle)}
+ </div>
+ </ActivityDisclosure>
+ </>
+ )}
+ {rows(window.last)}
+ {newCount > 0 && (
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ data-attr="thread-activity-refresh"
+ onClick={() => setVisibleIds(group.items.map((item) => item.id))}
+ >
+ Show {newCount} new {newCount === 1 ? 'activity' : 'activities'}
+ </LemonButton>
+ )}
+ </div>
+ </ActivityDisclosure>
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/ThreadRow.tsx b/products/posthog_ai/frontend/components/ThreadRow.tsx
index 8f99e0a9b29f..4ed97bea4f35 100644
--- a/products/posthog_ai/frontend/components/ThreadRow.tsx
+++ b/products/posthog_ai/frontend/components/ThreadRow.tsx
@@ -13,7 +13,7 @@ import { MessageTemplate } from '../messages/MessageTemplate'
import { ReasoningAnswer } from '../messages/ReasoningAnswer'
import type { ProgressStep, ThreadItem } from '../types/streamTypes'
import { resolveToolCall } from '../utils/toolResolver'
-import { RunActivity } from './RunActivity'
+import { Activity } from './ActivityPrimitives'
import { RunAlertActivity } from './RunAlertActivity'
import { CompactBoundaryItem, ConversationClearedItem, StatusItem, TaskNotificationItem } from './ThreadItems'
import { ToolCallCard } from './tool/ToolCallCard'
@@ -81,13 +81,14 @@ function ProgressItem({ item }: { item: ThreadItem }): JSX.Element | null {
const state = resolveProgressState(steps)
return (
- <RunActivity
+ <Activity
id={item.id}
- content={headline}
+ title={headline}
substeps={substeps}
- state={state}
+ status={state}
icon={<IconWrench />}
showCompletionIcon={true}
+ autoExpand={false}
/>
)
}
@@ -123,7 +124,7 @@ export const ThreadRow = memo(function ThreadRow({
}
if (item.type === 'assistant_message') {
return (
- <MessageTemplate type="ai">
+ <MessageTemplate type="ai" wrapperClassName="max-w-4/5">
<MarkdownMessage content={item.text ?? ''} id={item.id} />
</MessageTemplate>
)
diff --git a/products/posthog_ai/frontend/components/ThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsx
index 2463365a1895..f9096aa4534c 100644
--- a/products/posthog_ai/frontend/components/ThreadView.tsx
+++ b/products/posthog_ai/frontend/components/ThreadView.tsx
@@ -6,17 +6,21 @@ import { inStorybookTestRunner } from 'lib/utils/dom'
import { runStreamLogic } from '../logics/runStreamLogic'
import { ReasoningAnswer } from '../messages/ReasoningAnswer'
import type { ThreadItem } from '../types/streamTypes'
+import { groupThreadActivity, type ThreadDisplayItem } from '../utils/groupThreadActivity'
import { getRandomThinkingMessage } from '../utils/thinkingMessages'
+import { resolveToolCall } from '../utils/toolResolver'
import { type TurnTrailer, computeTurnTrailers } from '../utils/turnTrailers'
import { ContextUsageBar } from './ContextUsageBar'
import { PullRequestCard } from './PullRequestCard'
import { RunAlertActivity } from './RunAlertActivity'
import { RunContext } from './RunContext'
+import { ThreadActivityGroup } from './ThreadActivityGroup'
import { ThreadRow } from './ThreadRow'
+import { lookupToolRenderer } from './tool/toolRegistry'
import { VirtualizedThread } from './VirtualizedThread'
/** Stable row key — defined at module scope so `getItemKey` never changes identity across renders. */
-function getThreadItemKey(item: ThreadItem): string {
+function getThreadItemKey(item: ThreadDisplayItem): string {
return item.id
}
@@ -41,7 +45,10 @@ const THREAD_ITEM_HEIGHT_ESTIMATES: Partial<Record<ThreadItem['type'], number>>
debug: 30,
}
-function estimateThreadItemHeight(item: ThreadItem): number {
+function estimateThreadItemHeight(item: ThreadDisplayItem): number {
+ if (item.type === 'activity_group') {
+ return 48
+ }
return THREAD_ITEM_HEIGHT_ESTIMATES[item.type] ?? 56
}
@@ -91,14 +98,26 @@ export function ThreadView({
toolInvocations,
isThinking,
streamPhase,
+ showThinkingIndicator,
runArtifacts,
turnComplete,
currentRunStatus,
contextUsage,
runConnectionState,
logBootstrapLoading,
+ pendingPermissionRequest,
} = useValues(runStreamLogic)
const turnCancelled = currentRunStatus === 'cancelled'
+ const displayItems = useMemo(() => {
+ const standaloneToolIds = new Set<string>()
+ for (const [id, invocation] of toolInvocations) {
+ const resolved = resolveToolCall(invocation)
+ if (lookupToolRenderer(resolved.resolvedKey, !!resolved.innerToolName).keepVisible) {
+ standaloneToolIds.add(id)
+ }
+ }
+ return groupThreadActivity(threadItems, standaloneToolIds)
+ }, [threadItems, toolInvocations])
// The last human message anchors the thread. Reopening a saved conversation lands on it — the last
// meaningful turn, response below — when at least a viewport of content follows it (otherwise the
// bottom); a fresh send (a new key) pins the thread to the bottom to follow the streaming response.
@@ -111,9 +130,6 @@ export function ThreadView({
() => (renderTurnTrailer ? computeTurnTrailers(threadItems) : null),
[threadItems, renderTurnTrailer]
)
- const hasActiveProgressItem = threadItems.some(
- (item) => item.type === 'progress' && item.progressSteps?.some((step) => step.status === 'in_progress')
- )
// Header/footer are kept as memoized leaf components with stable element identity so they don't rebuild
// `VirtualizedThread`'s `renderRow` (and re-sweep visible rows) on every streamed frame. Each is wrapped
@@ -132,12 +148,11 @@ export function ThreadView({
// The connection banner (reconnecting / connection-failed) owns the footer line when present, so it
// takes precedence over the thinking indicator (a mid-run reconnect otherwise reads as normal thinking).
const showConnectionStatus = !!runConnectionState
- // `provisioning` (conversations/open POST + cold boot before run_started) also shows the indicator,
- // gated by !hasActiveProgressItem so real `_posthog/progress` boot steps take precedence.
const showThinking =
- (streamPhase === 'thinking' || streamPhase === 'provisioning') &&
- !hasActiveProgressItem &&
- !showConnectionStatus
+ showThinkingIndicator &&
+ !showConnectionStatus &&
+ !pendingPermissionRequest &&
+ displayItems.at(-1)?.type !== 'activity_group'
const thinkingPhase = streamPhase === 'provisioning' ? 'provisioning' : 'thinking'
// Post-turn only: a reconnect refetch can fold in a pr_url mid-run, so gate on !isThinking.
const pullRequestUrl = !isThinking ? runArtifacts.prUrl : undefined
@@ -172,7 +187,31 @@ export function ThreadView({
)
const renderItem = useCallback(
- (item: ThreadItem, index: number): JSX.Element => {
+ (item: ThreadDisplayItem, index: number): JSX.Element => {
+ if (item.type === 'activity_group') {
+ const isLast = index === displayItems.length - 1
+ return (
+ <VirtualizedThread.Row className={rowClassName}>
+ <ThreadActivityGroup
+ group={item}
+ toolInvocations={toolInvocations}
+ active={isLast && isThinking}
+ waitingForInput={isLast && !!pendingPermissionRequest}
+ cancelled={isLast && (turnCancelled || currentRunStatus === 'failed')}
+ renderItem={(activity) => (
+ <ThreadRow
+ item={activity}
+ isLast={false}
+ isThinking={false}
+ toolInvocations={toolInvocations}
+ turnComplete={turnComplete}
+ turnCancelled={turnCancelled}
+ />
+ )}
+ />
+ </VirtualizedThread.Row>
+ )
+ }
if (item.type === 'turn_separator' && renderTurnTrailer) {
const trailer = turnTrailers?.get(item.id)
return (
@@ -185,7 +224,7 @@ export function ThreadView({
<VirtualizedThread.Row className={rowClassName}>
<ThreadRow
item={item}
- isLast={index === threadItems.length - 1}
+ isLast={index === displayItems.length - 1}
isThinking={isThinking}
toolInvocations={toolInvocations}
turnComplete={turnComplete}
@@ -195,7 +234,7 @@ export function ThreadView({
)
},
[
- threadItems.length,
+ displayItems.length,
isThinking,
toolInvocations,
turnComplete,
@@ -203,12 +242,14 @@ export function ThreadView({
rowClassName,
renderTurnTrailer,
turnTrailers,
+ pendingPermissionRequest,
+ currentRunStatus,
]
)
return (
<VirtualizedThread.Root
- items={threadItems}
+ items={displayItems}
getItemKey={getThreadItemKey}
estimateItemHeight={estimateThreadItemHeight}
anchorItemKey={anchorItemKey}
diff --git a/products/posthog_ai/frontend/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
index 9661beaa1f1c..2094a152c6a8 100644
--- a/products/posthog_ai/frontend/components/VirtualizedThread.tsx
+++ b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
@@ -94,6 +94,9 @@ const HEADER_KEY = '__vt_header__'
const FOOTER_KEY = '__vt_footer__'
interface RootContextValue {
+ isFollowing: boolean
+ /** Inspecting expanded content should release automatic following, just like scrolling up. */
+ pauseFollowing: () => void
/** The virtualizer's border-box `ResizeObserver` ref — attach to each measured row's outer element. */
measureElement: (node: Element | null) => void
/** Inter-row spacing (px), applied as bottom padding on the measured row so heights include it. */
@@ -218,14 +221,10 @@ function Root<T>({
const scrollRef = useRef<HTMLDivElement>(null)
const didInitialScrollRef = useRef(false)
- // Bottom-pinning state (see `turnActive`). Explicit rather than position-derived: during fast
- // streaming the scroll position transiently lags the growing content past any at-bottom threshold,
- // so "is the user at the bottom right now" cannot distinguish "scrolled away" from "content briefly
- // outran the follow scroll". Starts pinned: a thread that opens onto an active turn follows from the
- // first frame, and it stays inert while no turn is active. A ref rather than state because every
- // reader of it needs the value in the same tick as the gesture — the scroll listener, the per-commit
- // follow effect, and the virtualizer options, which `useVirtualizer` re-reads on every render.
+ // Content growth can move the bottom before the next follow write. Track reader intent separately:
+ // the ref updates scroll handlers immediately; state publishes the same mode to activity lists.
const pinnedRef = useRef(true)
+ const [pinned, setPinnedState] = useState(true)
// Highest offset the reader has reached since the last pin — the yardstick the unpin test measures
// against. A high-water mark rather than the previous event's offset because a slow drag (scrollbar,
// touch, a trackpad crawl) moves a couple of px per scroll event and would walk hundreds of px away
@@ -429,6 +428,7 @@ function Root<T>({
return
}
pinnedRef.current = next
+ setPinnedState(next)
virtualizer.options.scrollEndThreshold = next ? BOTTOM_THRESHOLD : NO_END_COMPENSATION
virtualizer.options.anchorTo = next ? 'end' : 'start'
if (next) {
@@ -676,6 +676,13 @@ function Root<T>({
peakTopRef.current = el.scrollTop
let touchStartY: number | null = null
let touchStartX: number | null = null
+ const resumeAtBottom = (): void => {
+ bottomRepinBlockedUntilRef.current = 0
+ // At the end, a downward gesture cannot emit a scroll event. It must still resume following.
+ if (el.scrollHeight - el.clientHeight - el.scrollTop <= AT_BOTTOM_EPSILON) {
+ setPinned(true)
+ }
+ }
const onWheel = (event: WheelEvent): void => {
if (event.deltaY !== 0) {
lastUserScrollAtRef.current = performance.now()
@@ -685,7 +692,7 @@ function Root<T>({
} else if (event.deltaY > 0) {
// An explicit downward gesture is unambiguous — the reader heading for the bottom must
// not be told "not yet" by the post-landing block.
- bottomRepinBlockedUntilRef.current = 0
+ resumeAtBottom()
}
}
const onTouchStart = (event: TouchEvent): void => {
@@ -708,7 +715,7 @@ function Root<T>({
} else if (deltaY < 0) {
// Finger moving up scrolls the content down — the same explicit "heading for the
// bottom" signal as a downward wheel, so it clears the post-landing block too.
- bottomRepinBlockedUntilRef.current = 0
+ resumeAtBottom()
}
}
}
@@ -842,8 +849,15 @@ function Root<T>({
}, [virtualized, stickToBottom, noteProgrammaticScroll])
const rootValue = useMemo<RootContextValue>(
- () => ({ measureElement: virtualizer.measureElement, gap, maxWidthClassName, virtualized }),
- [virtualizer, gap, maxWidthClassName, virtualized]
+ () => ({
+ measureElement: virtualizer.measureElement,
+ gap,
+ maxWidthClassName,
+ virtualized,
+ isFollowing: stickToBottom && (!virtualized || pinned),
+ pauseFollowing: () => setPinned(false),
+ }),
+ [virtualizer, gap, maxWidthClassName, virtualized, stickToBottom, pinned, setPinned]
)
// Flow mode: render rows directly so an ancestor scroll container (and its auto-scroller) keeps working.
@@ -884,7 +898,7 @@ function Root<T>({
<div
ref={scrollRef}
className={cn(
- 'flex-1 min-h-0 overflow-y-auto overflow-x-hidden overscroll-contain [overflow-anchor:none]',
+ 'flex-1 min-h-0 overflow-y-auto overflow-x-hidden overscroll-contain [overflow-anchor:none] [scrollbar-gutter:stable]',
listClassName
)}
>
@@ -951,4 +965,14 @@ function Row({ children, className }: { children: ReactNode; className?: string
)
}
-export const VirtualizedThread = { Root, Row }
+const noop = (): void => {}
+
+function usePauseFollowing(): () => void {
+ return useContext(RootContext)?.pauseFollowing ?? noop
+}
+
+function useIsFollowing(): boolean {
+ return useContext(RootContext)?.isFollowing ?? false
+}
+
+export const VirtualizedThread = { Root, Row, usePauseFollowing, useIsFollowing }
diff --git a/products/posthog_ai/frontend/components/tool/DataToolRow.tsx b/products/posthog_ai/frontend/components/tool/DataToolRow.tsx
index 0b05a4f21dee..f901cf8bc2de 100644
--- a/products/posthog_ai/frontend/components/tool/DataToolRow.tsx
+++ b/products/posthog_ai/frontend/components/tool/DataToolRow.tsx
@@ -7,20 +7,19 @@ import type { ToolRendererProps } from './toolRegistry'
/**
* Shared shell for the data-tool adapters (insight, dashboard, recordings, query, error tracking,
* notebook). Renders the same header/accordion as the generic MCP card — `Call <tool>` title,
- * compact input preview, expandable input/output body — with the adapter's visualization as
+ * expandable input/output body — with the adapter's visualization as
* always-visible content below it (via the Activity bridge), while each adapter keeps its own
* lazy chunk.
*/
export function DataToolRow({ children, ...props }: PropsWithChildren<ToolRendererProps>): JSX.Element {
const { message, icon, displayName, turnComplete, turnCancelled } = props
- const { title, subtitle, body } = getMcpToolPresentation(message, displayName)
+ const { title, body } = getMcpToolPresentation(message, displayName)
return (
<ToolActivity
message={message}
icon={icon}
title={title}
- subtitle={subtitle}
body={body}
turnComplete={turnComplete}
turnCancelled={turnCancelled}
diff --git a/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx
index 90d22cc18871..95f6a074bc9d 100644
--- a/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx
+++ b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx
@@ -3,14 +3,12 @@ import { memo } from 'react'
import { IconWrench } from '@posthog/icons'
import { ToolActivity } from './ToolActivity'
-import { compactInput, formatInput, getContentText, stripCodeFences } from './toolContentUtils'
+import { formatInput, getContentText, stripCodeFences } from './toolContentUtils'
import { ToolBody, ToolBodySection, ToolOutput } from './ToolOutput'
import type { ToolRendererProps } from './toolRegistry'
export interface McpToolPresentation {
title: string
- /** Compact mono input preview for the header's second line. */
- subtitle: JSX.Element | undefined
/** Collapsible input/output accordion body. */
body: JSX.Element | undefined
}
@@ -18,7 +16,7 @@ export interface McpToolPresentation {
/**
* The shared MCP tool-card presentation: PostHog `exec` inner tools read `Call <tool>`; other MCP
* tools read `Call <server> – <tool> (MCP)`; non-MCP built-ins show their friendly title. The
- * subtitle is a compact input preview and the body shows the full input plus any text output.
+ * body shows the input and text output on demand.
* Used by the generic card and by `DataToolRow`, so data-tool widgets keep the same header/accordion.
*/
export function getMcpToolPresentation(
@@ -33,8 +31,9 @@ export function getMcpToolPresentation(
message.innerToolName || message.rawToolName || message.claudeToolName || displayName || message.resolvedKey
const inputForPreview = message.innerInput ?? message.rawInput
const hasInput = !!inputForPreview && Object.keys(inputForPreview).length > 0
- const preview = hasInput ? compactInput(inputForPreview) : ''
- const output = stripCodeFences(getContentText(message.content))
+ const output =
+ stripCodeFences(getContentText(message.content)) ||
+ (message.rawOutput !== undefined ? formatInput(message.rawOutput) : '')
// Plain neutral title text, matching the built-in tool cards (e.g. "Read N lines"). A single text
// node is also one flex item, so the header's `inline-flex` wrapper keeps the spaces intact.
@@ -48,9 +47,15 @@ export function getMcpToolPresentation(
const body =
formattedInput || output ? (
<ToolBody>
- {formattedInput && <ToolOutput>{formattedInput}</ToolOutput>}
+ {formattedInput && (
+ <ToolBodySection>
+ <div className="text-muted mb-1">Input</div>
+ <ToolOutput>{formattedInput}</ToolOutput>
+ </ToolBodySection>
+ )}
{output && (
<ToolBodySection divided={!!formattedInput}>
+ <div className="text-muted mb-1">Output</div>
<ToolOutput>{output}</ToolOutput>
</ToolBodySection>
)}
@@ -59,7 +64,6 @@ export function getMcpToolPresentation(
return {
title,
- subtitle: preview ? <span className="font-mono">{preview}</span> : undefined,
body,
}
}
@@ -71,14 +75,13 @@ export function getMcpToolPresentation(
*/
export const GenericMcpToolRenderer = memo(function GenericMcpToolRenderer(props: ToolRendererProps): JSX.Element {
const { message, icon, displayName, turnComplete, turnCancelled } = props
- const { title, subtitle, body } = getMcpToolPresentation(message, displayName)
+ const { title, body } = getMcpToolPresentation(message, displayName)
return (
<ToolActivity
message={message}
icon={icon ?? <IconWrench />}
title={title}
- subtitle={subtitle}
body={body}
turnComplete={turnComplete}
turnCancelled={turnCancelled}
diff --git a/products/posthog_ai/frontend/components/tool/ToolActivity.test.tsx b/products/posthog_ai/frontend/components/tool/ToolActivity.test.tsx
index 8322fdc15618..d7ec2f5a12e6 100644
--- a/products/posthog_ai/frontend/components/tool/ToolActivity.test.tsx
+++ b/products/posthog_ai/frontend/components/tool/ToolActivity.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
@@ -20,9 +20,13 @@ function makeMessage(overrides: Partial<ToolCallMessage> = {}): ToolCallMessage
}
describe('ToolActivity', () => {
- it('renders the title and subtitle (second line)', () => {
+ afterEach(() => cleanup())
+
+ it('renders the title in the header and the subtitle inside the expanded details', () => {
render(<ToolActivity message={makeMessage()} title="Terminal" subtitle="ls -la" />)
expect(screen.getByText('Terminal')).toBeInTheDocument()
+ expect(screen.queryByText('ls -la')).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button'))
expect(screen.getByText('ls -la')).toBeInTheDocument()
})
@@ -33,7 +37,7 @@ describe('ToolActivity', () => {
expect(screen.getByText('command output')).toBeInTheDocument()
})
- it('auto-expands the body while the tool is running', () => {
+ it('keeps the body collapsed while the tool is running', () => {
render(
<ToolActivity
message={makeMessage({ status: 'in_progress' })}
@@ -41,7 +45,8 @@ describe('ToolActivity', () => {
body={<div>streaming…</div>}
/>
)
- expect(screen.getByText('streaming…')).toBeInTheDocument()
+ expect(screen.getByText('Running')).toBeInTheDocument()
+ expect(screen.queryByText('streaming…')).not.toBeInTheDocument()
})
it('renders children always-visible without expanding', () => {
@@ -66,6 +71,6 @@ describe('ToolActivity', () => {
it('marks a turn-cancelled tool', () => {
render(<ToolActivity message={makeMessage({ status: 'in_progress' })} title="Terminal" turnCancelled />)
- expect(screen.getByText('(cancelled)')).toBeInTheDocument()
+ expect(screen.getByText('Canceled')).toBeInTheDocument()
})
})
diff --git a/products/posthog_ai/frontend/components/tool/ToolActivity.tsx b/products/posthog_ai/frontend/components/tool/ToolActivity.tsx
index b638fc92fd2a..3182a7088a25 100644
--- a/products/posthog_ai/frontend/components/tool/ToolActivity.tsx
+++ b/products/posthog_ai/frontend/components/tool/ToolActivity.tsx
@@ -6,6 +6,7 @@ import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTyp
import { Activity } from '../ActivityPrimitives'
import type { ActivityStatus } from '../ActivityPrimitives'
+import { VirtualizedThread } from '../VirtualizedThread'
import { resolveToolCallStatus } from './toolContentUtils'
export interface ToolActivityProps {
@@ -14,7 +15,7 @@ export interface ToolActivityProps {
icon?: ReactNode
/** Header line 1. */
title: ReactNode
- /** Header line 2 — the tool's salient input (command, path, url, …) where applicable. */
+ /** Salient input (command, path, URL), shown inside the expanded details. */
subtitle?: ReactNode
/** Collapsible body: streamed/expandable output (Bash output, file preview, diff, …). */
body?: ReactNode
@@ -28,7 +29,7 @@ export interface ToolActivityProps {
/**
* Bridges a sandbox tool call onto the shared `Activity` accordion: maps the tool's status to
* Activity's status/icons, surfaces a failure line, and routes per-tool content to either the
- * collapsible body (`body` → Activity `details`, auto-expands while running) or the always-visible
+ * manually expanded body (`body` → Activity `details`) or the always-visible
* region (`children`). Every sandbox tool card renders through this.
*/
export function ToolActivity({
@@ -41,33 +42,11 @@ export function ToolActivity({
turnComplete,
turnCancelled,
}: ToolActivityProps): JSX.Element {
+ const pauseFollowing = VirtualizedThread.usePauseFollowing()
const { isLoading, isFailed, wasCancelled } = resolveToolCallStatus(message.status, !!turnCancelled, !!turnComplete)
const status: ActivityStatus = isFailed ? 'failed' : isLoading ? 'in_progress' : 'completed'
- // Activity has no "cancelled" status — render it as a neutral terminal row (no check) with a marker
- // on the subtitle, or the title when there's no subtitle.
- const cancelledMarker = wasCancelled ? <span className="text-muted"> (cancelled)</span> : null
- const renderedTitle =
- !subtitle && cancelledMarker ? (
- <>
- {title}
- {cancelledMarker}
- </>
- ) : (
- title
- )
- const renderedSubtitle =
- subtitle && cancelledMarker ? (
- <>
- {subtitle}
- {cancelledMarker}
- </>
- ) : (
- subtitle
- )
-
- // The failure message lives in the always-visible region so it shows even though a failed tool's
- // details auto-collapse.
+ // Failures remain readable without opening the raw input/output.
const errorLine =
isFailed && message.error?.message ? <div className="text-danger">{message.error.message}</div> : null
const alwaysVisible = errorLine ? (
@@ -82,14 +61,44 @@ export function ToolActivity({
return (
<Activity
id={message.id}
- title={renderedTitle}
- subtitle={renderedSubtitle}
+ title={
+ <span className="flex items-center gap-2 min-w-0">
+ <span className="truncate">{title}</span>
+ <span className="text-muted shrink-0 font-normal">
+ {isFailed
+ ? 'Failed'
+ : wasCancelled
+ ? 'Canceled'
+ : isLoading
+ ? message.status === 'pending'
+ ? 'Pending'
+ : 'Running'
+ : message.status === 'completed'
+ ? 'Completed'
+ : 'Incomplete'}
+ </span>
+ </span>
+ }
status={status}
icon={icon ?? <IconWrench />}
showProgressIcon
showCompletionIcon={!wasCancelled}
failedIcon={<IconWarning className="text-danger size-3" />}
- details={body}
+ animate={false}
+ autoExpand={false}
+ onToggleDetails={(expanded) => {
+ if (expanded) {
+ pauseFollowing()
+ }
+ }}
+ details={
+ subtitle || body ? (
+ <div className="flex flex-col gap-2 min-w-0">
+ {subtitle && <div className="text-muted break-words">{subtitle}</div>}
+ {body}
+ </div>
+ ) : undefined
+ }
>
{alwaysVisible}
</Activity>
diff --git a/products/posthog_ai/frontend/components/tool/ToolOutput.tsx b/products/posthog_ai/frontend/components/tool/ToolOutput.tsx
index bb14c094fd42..96c81d69e711 100644
--- a/products/posthog_ai/frontend/components/tool/ToolOutput.tsx
+++ b/products/posthog_ai/frontend/components/tool/ToolOutput.tsx
@@ -1,12 +1,55 @@
import clsx from 'clsx'
-import type { ReactNode } from 'react'
+import { type ReactNode, useEffect, useRef } from 'react'
-/** Monospace, scrollable output block for a tool card's collapsible body (terminal/search/fetch). */
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+
+/** Bounded text preview; full output opens as plain text without another scroll container in the chat. */
export function ToolOutput({ children }: { children: ReactNode }): JSX.Element {
+ const urls = useRef<string[]>([])
+ useEffect(
+ () => () => {
+ urls.current.forEach((url) => URL.revokeObjectURL(url))
+ },
+ []
+ )
+ const text = typeof children === 'string' ? children : undefined
+ const preview = text?.slice(0, 4000).split('\n').slice(0, 12).join('\n')
+ const truncated = text !== undefined && preview !== text
return (
- <pre className="m-0 font-mono text-xs leading-relaxed text-secondary whitespace-pre-wrap break-all max-h-64 overflow-auto">
- {children}
- </pre>
+ <div className="flex flex-col gap-1 min-w-0">
+ <pre className="m-0 font-mono text-xs leading-relaxed text-secondary whitespace-pre-wrap break-all">
+ {preview ?? children}
+ {truncated ? '\n…' : ''}
+ </pre>
+ {text !== undefined && (
+ <div className="flex gap-2 flex-wrap">
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ data-attr="tool-output-copy"
+ onClick={() => void copyToClipboard(text, 'tool text')}
+ >
+ Copy {truncated ? 'full text' : 'text'}
+ </LemonButton>
+ {truncated && (
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ data-attr="tool-output-open"
+ onClick={() => {
+ const url = URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' }))
+ urls.current.push(url)
+ window.open(url, '_blank', 'noopener,noreferrer')
+ }}
+ >
+ Open full text in new tab
+ </LemonButton>
+ )}
+ </div>
+ )}
+ </div>
)
}
diff --git a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx
index d0e7848ff50b..3b8e98da3fbe 100644
--- a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx
+++ b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx
@@ -47,8 +47,9 @@ describe('builtin tool renderers', () => {
})}
/>
)
- expect(screen.getByText('pnpm build')).toBeInTheDocument()
+ expect(screen.queryByText('pnpm build')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button'))
+ expect(screen.getByText('pnpm build')).toBeInTheDocument()
expect(screen.getByText('build succeeded')).toBeInTheDocument()
})
@@ -65,6 +66,7 @@ describe('builtin tool renderers', () => {
/>
)
expect(screen.getByText('Read 2 lines')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button'))
expect(screen.getByText('app.ts')).toBeInTheDocument()
})
@@ -98,6 +100,7 @@ describe('builtin tool renderers', () => {
/>
)
expect(screen.getByText('Grep TODO')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button'))
expect(screen.getByText('3 results')).toBeInTheDocument()
})
@@ -173,6 +176,7 @@ describe('builtin tool renderers', () => {
/>
)
expect(screen.getByText('Search tools')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button'))
expect(screen.getByText('funnel')).toBeInTheDocument()
})
diff --git a/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.test.tsx b/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.test.tsx
index 1d2bab2132e6..9b630f27c375 100644
--- a/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.test.tsx
+++ b/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.test.tsx
@@ -50,10 +50,10 @@ describe('posthog-code tool renderers', () => {
/>
)
expect(screen.getByText('Signed commits · 2 commits')).toBeInTheDocument()
- expect(screen.getByText('fix(api): handle null series')).toBeInTheDocument()
- // The commit links live in the collapsed accordion, not always-visible — reveal them first.
+ // The commit message and links live in the collapsed accordion, not always-visible — reveal them first.
expect(screen.queryByText(/a1b2c3d/)).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button'))
+ expect(screen.getByText('fix(api): handle null series')).toBeInTheDocument()
expect(screen.getByText(/a1b2c3d/).closest('a')).toHaveAttribute(
'href',
'https://github.com/posthog/posthog/commit/a1b2c3dabcdef'
@@ -72,6 +72,7 @@ describe('posthog-code tool renderers', () => {
render(
<PostHogCodeToolRenderer isLastInGroup message={makeMessage({ resolvedKey: qualified(tool), rawInput })} />
)
+ fireEvent.click(screen.getByRole('button'))
expect(screen.getByText(expected)).toBeInTheDocument()
})
@@ -128,11 +129,11 @@ describe('posthog-code tool renderers', () => {
/>
)
expect(screen.getByText('Clone repository')).toBeInTheDocument()
- expect(screen.getByText(/posthog\/posthog/).closest('a')).toHaveAttribute(
+ fireEvent.click(screen.getByRole('button'))
+ expect(screen.getByText('posthog/posthog').closest('a')).toHaveAttribute(
'href',
'https://github.com/posthog/posthog'
)
- fireEvent.click(screen.getByRole('button'))
expect(screen.getByText(/\/home\/user\/repos\/posthog\/posthog/)).toBeInTheDocument()
})
diff --git a/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx
index 715b5f3e45f7..394203dc2d61 100644
--- a/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx
+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { render, screen } from '@testing-library/react'
+import { fireEvent, render, screen } from '@testing-library/react'
import type { ReactNode } from 'react'
import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
@@ -159,10 +159,11 @@ describe('toolRegistry', () => {
})}
/>
)
- // Skeleton first (registry displayName), then the resolved card with the command. The
- // generous timeout covers jest compiling the lazy chunk's heavy deps on first load.
+ // Skeleton first (registry displayName), then the resolved card whose header expands to the
+ // command. The generous timeout covers jest compiling the lazy chunk's heavy deps on first load.
expect(screen.getByText('Terminal')).toBeInTheDocument()
- expect(await screen.findByText('echo hello-bash', {}, { timeout: 10000 })).toBeInTheDocument()
+ fireEvent.click(await screen.findByRole('button', {}, { timeout: 10000 }))
+ expect(screen.getByText('echo hello-bash')).toBeInTheDocument()
})
it('renders an unmapped MCP tool through the generic card', async () => {
diff --git a/products/posthog_ai/frontend/components/tool/toolRegistry.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
index 1b3fad91303e..7bf81d4962e8 100644
--- a/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
@@ -43,6 +43,8 @@ export interface ToolRendererProps {
type ToolRendererComponent = ComponentType<ToolRendererProps> | LazyExoticComponent<ComponentType<ToolRendererProps>>
export interface ToolRegistryEntry {
+ /** Keep results such as charts, plans and questions outside collapsed activity groups. */
+ keepVisible?: boolean
/**
* Registry key. For single-exec PostHog tools, this is the **inner** tool name parsed from
* `rawInput.command` (e.g. "execute-sql", "insight-create"); for `exec`'s discovery verbs,
@@ -165,7 +167,13 @@ const BUILTIN_TOOLS: { keys: string[]; displayName: string; icon: JSX.Element }[
]
for (const { keys, displayName, icon } of BUILTIN_TOOLS) {
for (const key of keys) {
- toolRegistry.register({ key, displayName, icon, Renderer: BuiltinToolRenderer })
+ toolRegistry.register({
+ key,
+ displayName,
+ icon,
+ Renderer: BuiltinToolRenderer,
+ keepVisible: key === 'ExitPlanMode',
+ })
}
}
@@ -213,6 +221,7 @@ for (const { name, displayName, icon } of POSTHOG_CODE_TOOLS) {
// lays the question + options out like the LangGraph question recap, rather than the generic JSON card.
toolRegistry.register({
key: 'AskUserQuestion',
+ keepVisible: true,
displayName: 'Question',
icon: <IconAI />,
Renderer: QuestionRenderer,
diff --git a/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.tsx b/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.tsx
index 7c26b481e7e9..30aff6f6869f 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.tsx
+++ b/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.tsx
@@ -58,7 +58,16 @@ function register(
Renderer: ComponentType<ToolRendererProps>
): void {
registerToolRenderers(
- keys.map((key): ToolRegistryEntry => ({ key, displayName, icon, Renderer, requiresPostHogOrigin: true }))
+ keys.map(
+ (key): ToolRegistryEntry => ({
+ key,
+ displayName,
+ icon,
+ Renderer,
+ requiresPostHogOrigin: true,
+ keepVisible: true,
+ })
+ )
)
}
@@ -141,6 +150,7 @@ registerToolRenderers(
icon,
Renderer: QueryRenderer,
requiresPostHogOrigin: true,
+ keepVisible: true,
})
)
)
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index 48d993f0403d..47420611b237 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -18,6 +18,7 @@ import { computeTurnTrailers } from '../utils/turnTrailers'
import { attachedContextLogic } from './attachedContextLogic'
import {
extractRunArtifacts,
+ foldLogToThread,
mapHttpStatusToStreamError,
MAX_CUMULATIVE_RECONNECT_ATTEMPTS,
MAX_HISTORY_FETCH_ATTEMPTS,
@@ -218,6 +219,29 @@ describe('runStreamLogic', () => {
})
describe('ingestAcpFrame replay', () => {
+ it('omits imported timing and resumes timing on the next native run', () => {
+ const frames = [
+ notification('_posthog/run_started', { imported: true }),
+ sessionUpdate({ sessionUpdate: 'tool_call', toolCallId: 'imported', status: 'completed' }),
+ notification('_posthog/run_started', {}),
+ sessionUpdate({ sessionUpdate: 'tool_call', toolCallId: 'native', status: 'in_progress' }),
+ sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'native', status: 'completed' }),
+ sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'missing-start', status: 'completed' }),
+ ]
+ const result = foldLogToThread(
+ frames.map((entry, index) => ({
+ source: 'replay',
+ entry: { ...entry, timestamp: new Date((index + 1) * 1000).toISOString() },
+ })),
+ { isResumeRun: true }
+ )
+ expect(result.threadItems.find((item) => item.id === 'imported')?.startedAt).toBeUndefined()
+ expect(result.threadItems.find((item) => item.id === 'native')).toMatchObject({
+ startedAt: 4000,
+ endedAt: 5000,
+ })
+ expect(result.threadItems.find((item) => item.id === 'missing-start')?.startedAt).toBeUndefined()
+ })
it('folds a stream of StoredLogEntry frames into thread items', async () => {
const frames: StoredLogEntry[] = [
notification('_posthog/run_started', {}),
@@ -241,6 +265,9 @@ describe('runStreamLogic', () => {
}),
notification('_posthog/turn_complete', {}),
]
+ frames.forEach((frame, index) => {
+ frame.timestamp = new Date((index + 1) * 1000).toISOString()
+ })
await expectLogic(logic, () => {
frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))
@@ -255,6 +282,8 @@ describe('runStreamLogic', () => {
const toolItem = logic.values.threadItems.find((item) => item.type === 'tool_invocation')
expect(toolItem?.toolCallId).toEqual('t1')
+ expect(toolItem).toMatchObject({ startedAt: 5000, endedAt: 6000 })
+ expect(assistantItem).toMatchObject({ startedAt: 2000, endedAt: 4000 })
const invocation = logic.values.toolInvocations.get('t1')
expect(invocation?.rawServerName).toEqual('posthog')
@@ -396,6 +425,37 @@ describe('runStreamLogic', () => {
})
describe('showThinkingIndicator', () => {
+ it.each(['in_progress', 'completed', 'failed'] as const)(
+ 'does not repeat the startup loader after a %s progress step',
+ async (status) => {
+ logic.actions.setRunOpening(true)
+ expect(logic.values.showThinkingIndicator).toBe(true)
+
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(
+ notification('_posthog/progress', {
+ group: 'setup:run-1',
+ step: 'sandbox',
+ status,
+ label: 'Sandbox setup',
+ })
+ )
+ }).toFinishAllListeners()
+
+ expect(logic.values.showThinkingIndicator).toBe(false)
+
+ logic.actions.reset()
+ logic.actions.setRunOpening(true)
+ expect(logic.values.showThinkingIndicator).toBe(true)
+ }
+ )
+
+ it('does not show startup progress after a delivery error', () => {
+ logic.actions.sseOpened()
+ logic.actions.pushErrorItem('Unable to deliver the message')
+ expect(logic.values.showThinkingIndicator).toBe(false)
+ })
+
const runStartedFrame = notification('_posthog/run_started', {})
const messageChunk = sessionUpdate({
sessionUpdate: 'agent_message_chunk',
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index 4c14fa69f469..5f19d025d4c7 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -1059,6 +1059,8 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
let taskSeq = 0
let consoleSeq = 0
let contextSeq = 0
+ let timestamp: number | undefined
+ let importedRun = false
const pushHuman = (text: string): void => {
items = insertHumanMessageAtTurnStart(items, {
@@ -1066,6 +1068,7 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
type: 'human_message',
text,
complete: true,
+ ...(timestamp !== undefined && { startedAt: timestamp }),
})
}
@@ -1090,10 +1093,20 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
// does, since the backend drops chunks), so the bare fallback id would collide as a React key
// across messages. The continuation lookup matches the `${id}@` prefix, so it still works.
if (idx === -1 || items[idx].complete || idx !== items.length - 1) {
- items.push({ id: `${id}@${bubbleSeq++}`, type, text: delta, complete: false })
+ items.push({
+ id: `${id}@${bubbleSeq++}`,
+ type,
+ text: delta,
+ complete: false,
+ ...(timestamp !== undefined && { startedAt: timestamp, endedAt: timestamp }),
+ })
return
}
- items[idx] = { ...items[idx], text: (items[idx].text ?? '') + delta }
+ items[idx] = {
+ ...items[idx],
+ text: (items[idx].text ?? '') + delta,
+ ...(timestamp !== undefined && { endedAt: timestamp }),
+ }
}
const finalizeMessage = (id: string, text: string): void => {
@@ -1119,15 +1132,26 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
// No buffer to close (the common replay case: S3 drops chunks, so a finalized message
// arrives alone). Push a fresh bubble with a unique id — a bare fallback id would collide
// as a React key with every other no-`messageId` message in the thread.
- items.push({ id: `${id}@${bubbleSeq++}`, type: 'assistant_message', text, complete: true })
+ items.push({
+ id: `${id}@${bubbleSeq++}`,
+ type: 'assistant_message',
+ text,
+ complete: true,
+ ...(timestamp !== undefined && { startedAt: timestamp, endedAt: timestamp }),
+ })
return
}
- items[idx] = { ...items[idx], text, complete: true }
+ items[idx] = { ...items[idx], text, complete: true, ...(timestamp !== undefined && { endedAt: timestamp }) }
}
- const upsertInvocationItem = (toolCallId: string): void => {
+ const upsertInvocationItem = (toolCallId: string, hasStart = true): void => {
if (!items.some((item) => item.type === 'tool_invocation' && item.toolCallId === toolCallId)) {
- items.push({ id: toolCallId, type: 'tool_invocation', toolCallId })
+ items.push({
+ id: toolCallId,
+ type: 'tool_invocation',
+ toolCallId,
+ ...(hasStart && timestamp !== undefined && { startedAt: timestamp }),
+ })
}
}
@@ -1182,7 +1206,13 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
}
invocations.set(next.toolCallId, next)
if (!existing && !subagentParentToolCallId(update._meta)) {
- upsertInvocationItem(next.toolCallId)
+ upsertInvocationItem(next.toolCallId, false)
+ }
+ if (timestamp !== undefined && (next.status === 'completed' || next.status === 'failed')) {
+ const index = items.findIndex((item) => item.toolCallId === next.toolCallId)
+ if (index !== -1) {
+ items[index] = { ...items[index], endedAt: timestamp }
+ }
}
}
@@ -1190,6 +1220,12 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
const notification = entry.notification
const method = notification.method
const params = (notification.params ?? {}) as Record<string, unknown>
+ if (method === '_posthog/run_started') {
+ importedRun = params.imported === true
+ }
+ const updateMeta = isRecord(params.update) && isRecord(params.update._meta) ? params.update._meta : null
+ const recordedAt = entry.timestamp ? Date.parse(entry.timestamp) : NaN
+ timestamp = !importedRun && !updateMeta?.imported && Number.isFinite(recordedAt) ? recordedAt : undefined
if (method === '_client/human_message') {
pushHuman(String(params.content ?? ''))
@@ -1215,7 +1251,12 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
}
if (method === '_posthog/turn_complete') {
const traceId = typeof params.traceId === 'string' ? params.traceId : undefined
- items.push({ id: `turn-${separatorSeq++}`, type: 'turn_separator', ...(traceId && { traceId }) })
+ items.push({
+ id: `turn-${separatorSeq++}`,
+ type: 'turn_separator',
+ ...(traceId && { traceId }),
+ ...(timestamp !== undefined && { startedAt: timestamp }),
+ })
continue
}
if (method === '_posthog/progress') {
@@ -1297,6 +1338,7 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:
type: 'task_notification',
status: stringifyOptional(params.status),
summary: stringifyOptional(params.summary),
+ ...(timestamp !== undefined && { startedAt: timestamp, endedAt: timestamp }),
})
continue
}
@@ -2341,13 +2383,16 @@ export const runStreamLogic = kea<runStreamLogicType>([
threadItems: ThreadItem[],
toolInvocations: Map<string, ToolInvocation>
): boolean => {
- if (streamPhase !== 'thinking') {
+ if (streamPhase === 'idle') {
return false
}
// Scan the current turn only (items after the last separator).
const turnStart = threadItems.findLastIndex((item) => item.type === 'turn_separator') + 1
for (let i = turnStart; i < threadItems.length; i++) {
const item = threadItems[i]
+ if (streamPhase === 'provisioning' && (item.type === 'progress' || item.type === 'error')) {
+ return false
+ }
// A running structured-progress activity owns the "busy" line.
if (item.type === 'progress' && item.progressSteps?.some((step) => step.status === 'in_progress')) {
return false
diff --git a/products/posthog_ai/frontend/types/streamTypes.ts b/products/posthog_ai/frontend/types/streamTypes.ts
index 7f862f5bf62e..dab7b9872f29 100644
--- a/products/posthog_ai/frontend/types/streamTypes.ts
+++ b/products/posthog_ai/frontend/types/streamTypes.ts
@@ -135,6 +135,9 @@ export interface ThreadItem {
/** Stable id — message buffer id, tool call id, or a generated separator/error id. */
id: string
type: ThreadItemType
+ /** Recorded activity times in milliseconds; absent for imported or untimed history. */
+ startedAt?: number
+ endedAt?: number
/** For `human_message`, `assistant_message`, and `assistant_thought` items. */
text?: string
/** Whether the assistant message buffer is finalized. */
diff --git a/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts b/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts
new file mode 100644
index 000000000000..0620af34085c
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/groupThreadActivity.test.ts
@@ -0,0 +1,101 @@
+import type { ThreadItem, ToolInvocation } from '../types/streamTypes'
+import { activityWindow, groupConsecutiveTools, groupThreadActivity } from './groupThreadActivity'
+
+describe('thread activity grouping', () => {
+ const tool = (id: string, startedAt = 1000): ThreadItem => ({
+ id,
+ type: 'tool_invocation',
+ toolCallId: id,
+ startedAt,
+ endedAt: startedAt + 100,
+ })
+
+ it('keeps messages, artifacts, failures and turn boundaries in order, without duplicating calls', () => {
+ const items: ThreadItem[] = [
+ { id: 'human', type: 'human_message', text: 'Find a report' },
+ tool('search'),
+ { id: 'thought', type: 'assistant_thought', text: 'Checking results', startedAt: 1100 },
+ { id: 'notification', type: 'task_notification', status: 'completed', startedAt: 1200 },
+ tool('chart', 1300),
+ tool('read', 1400),
+ { id: 'failure', type: 'task_notification', status: 'failed' },
+ { id: 'answer', type: 'assistant_message', text: 'Here is the report', startedAt: 1600 },
+ { id: 'end', type: 'turn_separator', startedAt: 1700 },
+ tool('next', 3000),
+ ]
+ const result = groupThreadActivity(items, new Set(['chart']))
+ expect(result.map((item) => item.id)).toEqual([
+ 'human',
+ 'activity-search',
+ 'chart',
+ 'activity-read',
+ 'failure',
+ 'answer',
+ 'end',
+ 'activity-next',
+ ])
+ expect(result.flatMap((item) => (item.type === 'activity_group' ? item.items : [item]))).toEqual(items)
+ expect(result[1]).toMatchObject({ startedAt: 1000, endedAt: 1300 })
+ expect(groupThreadActivity([...items, tool('last', 3200)], new Set(['chart'])).at(-1)?.id).toBe('activity-next')
+ })
+
+ it('does not invent a duration when part of the group has no recorded start', () => {
+ const result = groupThreadActivity(
+ [tool('timed'), { id: 'imported', type: 'tool_invocation', toolCallId: 'imported' }],
+ new Set()
+ )
+ expect(result[0].startedAt).toBeUndefined()
+ })
+
+ it('chains only adjacent calls to the same resolved tool and server, retaining every item', () => {
+ const calls = new Map<string, ToolInvocation>()
+ const call = (id: string, name: string, server = 'posthog'): ThreadItem => {
+ calls.set(id, {
+ toolCallId: id,
+ rawServerName: server,
+ rawToolName: 'exec',
+ input: { command: `call ${name} {}` },
+ status: 'completed',
+ contentBlocks: [],
+ })
+ return tool(id)
+ }
+ const items = [
+ call('a', 'execute-sql'),
+ call('b', 'execute-sql'),
+ call('c', 'query-trends'),
+ call('d', 'execute-sql'),
+ { id: 'thought', type: 'assistant_thought', text: 'Check another source.' } as ThreadItem,
+ call('e', 'execute-sql'),
+ call('f', 'execute-sql', 'other'),
+ tool('missing'),
+ call('g', 'execute-sql'),
+ ]
+ const groups = groupConsecutiveTools(items, calls)
+ expect(groups.map((group) => group.map((item) => item.id))).toEqual([
+ ['a', 'b'],
+ ['c'],
+ ['d'],
+ ['thought'],
+ ['e'],
+ ['f'],
+ ['missing'],
+ ['g'],
+ ])
+ expect(groups.flat()).toEqual(items)
+ })
+
+ it.each([0, 1, 10, 11, 300])('makes every item reachable in bounded pages for %i activities', (count) => {
+ const items = Array.from({ length: count }, (_, i) => i)
+ const collapsed = activityWindow(items, null)
+ expect(collapsed.first.length + collapsed.last.length).toBeLessThanOrEqual(10)
+ const seen = [...collapsed.first]
+ for (let page = 0; page < collapsed.pageCount; page++) {
+ const window = activityWindow(items, page)
+ expect(window.first.length + window.middle.length + window.last.length).toBeLessThanOrEqual(15)
+ seen.push(...window.middle)
+ }
+ seen.push(...collapsed.last)
+ expect(seen).toEqual(items)
+ })
+})
diff --git a/products/posthog_ai/frontend/utils/groupThreadActivity.ts b/products/posthog_ai/frontend/utils/groupThreadActivity.ts
new file mode 100644
index 000000000000..50cca9671813
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/groupThreadActivity.ts
@@ -0,0 +1,96 @@
+import type { ThreadItem, ToolInvocation } from '../types/streamTypes'
+import { resolveToolCall } from './toolResolver'
+
+export interface ThreadActivityGroup {
+ id: string
+ type: 'activity_group'
+ items: ThreadItem[]
+ startedAt?: number
+ endedAt?: number
+}
+
+export type ThreadDisplayItem = ThreadItem | ThreadActivityGroup
+
+/** Runs stay within the supplied page; hidden items must never make separate calls look adjacent. */
+export function groupConsecutiveTools(
+ items: ThreadItem[],
+ toolInvocations: ReadonlyMap<string, ToolInvocation>
+): ThreadItem[][] {
+ const groups: ThreadItem[][] = []
+ let previousKey: string | undefined
+ for (const item of items) {
+ const call =
+ item.type === 'tool_invocation' && item.toolCallId ? toolInvocations.get(item.toolCallId) : undefined
+ const resolved = call ? resolveToolCall(call) : undefined
+ const key =
+ call && resolved?.resolvedKey && resolved.resolvedKey !== '__posthog_exec_unknown__'
+ ? JSON.stringify([call.rawServerName, resolved.resolvedKey])
+ : undefined
+ if (key && key === previousKey) {
+ groups[groups.length - 1].push(item)
+ } else {
+ groups.push([item])
+ }
+ previousKey = key
+ }
+ return groups
+}
+
+export function groupThreadActivity(items: ThreadItem[], standaloneToolIds: ReadonlySet<string>): ThreadDisplayItem[] {
+ const result: ThreadDisplayItem[] = []
+ let group: ThreadActivityGroup | undefined
+ for (const item of items) {
+ const isActivity =
+ item.type === 'assistant_thought' ||
+ (item.type === 'task_notification' && item.status === 'completed') ||
+ (item.type === 'tool_invocation' && !!item.toolCallId && !standaloneToolIds.has(item.toolCallId))
+ if (!isActivity) {
+ if (group && item.startedAt !== undefined) {
+ group.endedAt = Math.max(group.endedAt ?? 0, item.startedAt)
+ }
+ group = undefined
+ result.push(item)
+ continue
+ }
+ if (!group) {
+ group = { id: `activity-${item.id}`, type: 'activity_group', items: [], startedAt: item.startedAt }
+ result.push(group)
+ }
+ group.items.push(item)
+ // An imported/missing start makes the whole interval unknown, rather than a misleading zero.
+ if (item.startedAt === undefined) {
+ group.startedAt = undefined
+ }
+ if (item.endedAt !== undefined) {
+ group.endedAt = Math.max(group.endedAt ?? 0, item.endedAt)
+ }
+ }
+ return result
+}
+
+export function activityWindow<T>(
+ items: T[],
+ middlePage: number | null
+): {
+ first: T[]
+ middle: T[]
+ last: T[]
+ hiddenCount: number
+ pageCount: number
+ page: number
+} {
+ const hiddenCount = items.length > 10 ? items.length - 5 : 0
+ const pageCount = Math.ceil(hiddenCount / 10)
+ const page = Math.max(0, Math.min(middlePage ?? 0, pageCount - 1))
+ return {
+ first: hiddenCount ? items.slice(0, 2) : items,
+ middle:
+ hiddenCount && middlePage !== null
+ ? items.slice(2 + page * 10, Math.min(2 + (page + 1) * 10, items.length - 3))
+ : [],
+ last: hiddenCount ? items.slice(-3) : [],
+ hiddenCount,
+ pageCount,
+ page,
+ }
+}
diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.py
index f58b840b4f03..c9d28e5d5a5b 100644
--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py
@@ -491,7 +491,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
await self._emit_progress("agent", "in_progress", "Starting agent", "setup")
agent_server_output = await self._start_agent_server(sandbox_output)
- await self._emit_progress("agent", "completed", "Started agent", "setup")
+ await self._emit_progress("agent", "completed", "Agent ready", "setup")
await self._track_workflow_event(
"sandbox_started",
@@ -1135,7 +1135,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
detail="Resumed from a previous snapshot",
)
else:
- await self._emit_progress("sandbox", "completed", "Set up sandbox", "setup")
+ await self._emit_progress("sandbox", "completed", "Sandbox ready", "setup")
if used_snapshot and prepared.snapshot_external_id:
await workflow.execute_activity(
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index ed71e94240d9..f197774fa7e3 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -1725,7 +1725,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
agent_server_output = await self._start_agent_server(sandbox_output, boot_excluded_ms=wizard_ms)
self._agent_shadow_launched = bool(sandbox_output.agent_shadow_launched or agent_server_output.shadow_launched)
self._agent_ready_at = workflow.now() if self._agent_boot_interaction_telemetry_enabled else None
- await self._emit_progress("agent", "completed", "Started agent", "setup")
+ await self._emit_progress("agent", "completed", "Agent ready", "setup")
await self._track_workflow_event(
"sandbox_started",
@@ -1943,7 +1943,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
detail="Resumed from a previous snapshot",
)
else:
- await self._emit_progress("sandbox", "completed", "Set up sandbox", "setup")
+ await self._emit_progress("sandbox", "completed", "Sandbox ready", "setup")
# Resuming from a filesystem snapshot carries the previous run's
# credentials baked into .git/config and any agentsh env file — refresh
@@ -2025,7 +2025,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
):
raise _TaskCompletedDuringSandboxCreation
used_snapshot = False
- await self._emit_progress("sandbox", "completed", "Set up sandbox", "setup")
+ await self._emit_progress("sandbox", "completed", "Sandbox ready", "setup")
can_clone_without_integration = is_public_sandbox_repo(prepared.repository)
has_clone_credentials = self.context.has_github_credentials or can_clone_without_integration