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): quill skin for the legacy chat behind phai-quill (#122022)

Adam Leith5cdf7b0e0896
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6e320679d6d6..d23d2246d0ef 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7917,21 +7917,21 @@ snapshots:
products-posthog-ai-threadview--saved-insight-query--light:
hash: v1.k794b7964.405cb15303a44d4f837d5569ab4110e07b62ffa71fc418e0aaeb29ddafe8cf8e.mnRWTc0Tao1ttGBbi8vm9n77TQn-RXrRtmeeaDk-yM8
products-posthog-ai-threadview-quill--compared-with-lemon--dark:
- hash: v1.k794b7964.0eef4b8bb8e847af86a96de1b100ccef151cc567197bee0200ca75a0e715c286.a5rC4BaHZaP6PhJ0-i0xMfj1DhJiQLcQtM_xXJkvMj4
+ hash: v1.k794b7964.6ee083d43feb17cbf75de903a58fc0f22e2a6096325ed71807bc7b5d4d9b3fb8.kb4rt8HOCJqb2JDFBOD4iCPLXARpcLLuaAruzfbiwKE
products-posthog-ai-threadview-quill--compared-with-lemon--light:
- hash: v1.k794b7964.c7a5ffd2925080a181b740d34b2c27b38ad09f50892b11d14ceceba7e336a968.6xFkSM46Y-L3sx2EzN4vegRwjUqUwaxMc4usQN_1Bcw
+ hash: v1.k794b7964.8ddd3e0f26bc30a2c8765cc95a50d44cbad6004ed71865e02803d0ce3bac8d70.880PRQXkoRu4Cqq7IolKEjWJKucfChdwHN2virYl4rQ
products-posthog-ai-threadview-quill--completed-turn--dark:
- hash: v1.k794b7964.18e0af3b40dd5dff18d7d9f35711a38735850eb1f40edb62250c12dc57138857.0QpvMwB4_kWqBkYx-UFabEDT7gjUyyUCRt53i7ekBu4
+ hash: v1.k794b7964.c0c04f36fad1bde518d957b22e870ce81bd09f24ab907101ee1e6c8f405caa81.YxTkfFJuf49W2ekYQ7vlU7xIik6AK0t3kZOLq_qdzXo
products-posthog-ai-threadview-quill--completed-turn--light:
- hash: v1.k794b7964.aaffd4821833cbd7be9d8c7cd77e9f0809e71ffcc3e5084dd838907c9a4555c7.TK23ojxPSurDuQlaipSd9dkwMzO20ChsfIc1mUjYTts
+ hash: v1.k794b7964.30a0f679fc786bd440e0fff410df5a8b5f07401f2d44944d9b7e01be640b2e3e.sala-ge66qAYCscRp1fRudt5KKXoUJojb6h-OT2UBC8
products-posthog-ai-threadview-quill--long-run--dark:
hash: v1.k794b7964.649d59f9d5e3d4dda17e70d3328394cee09f2cfdef39250ec1bfbfefc876b476.0YWMro0yyOCP9-2KChyQ3IqVUigeNmVYfRzoS1ijTZc
products-posthog-ai-threadview-quill--long-run--light:
hash: v1.k794b7964.d86e7871a7a187ef1637cb1434b4baefdf7695f68abe3f0adaebdc39ff8e220a.NK0Pld_NMcqp8eaGZhDeuLYcNb69l5kYYstVtK3r2HE
products-posthog-ai-threadview-quill--streaming-turn--dark:
- hash: v1.k794b7964.01bd9095cf2448a061749878dfe6b7987084fbcbbc8fbb666ed4289e7087e332.AMVJTk5ixhgsTacK3PZ4heII47WXHCgGBohPR2DaO1s
+ hash: v1.k794b7964.3dffc02502a9a4bb1ac49cf8dababd01a8379dded0d143de942164eca57a1298.aXF8p8fd1gaVtuv-EX8zoS6iGMf7BYqaAQV8qCVzozk
products-posthog-ai-threadview-quill--streaming-turn--light:
- hash: v1.k794b7964.caabab4d290dda51a4d3c302bfdcd4f16a6a54cc9f613da835afab3b8f2c60d3.6KgDrcJZ1u-Sm9NkUS-sUti399TsxKBCytKuU_A-EmU
+ hash: v1.k794b7964.170f245d77e0f8bf368f519669a3ca15fd3d9de222d2ce3fda52735e10570cbe.qSVE3iQhhhWTc-4zQsv8LvNQsZSYC7Wah6oZTeVsjxQ
products-posthog-ai-turnsuggestioncard--alert-suggestion--dark:
hash: v1.k794b7964.1d792984be0657f406e45722e1b4799905c474a28f8c985c8e406377a8dd97e7.gQ65VeoKFMTS04UA7UjbntfuL7nkr6Zpk-mhvoTf9X4
products-posthog-ai-turnsuggestioncard--alert-suggestion--light:
@@ -14337,9 +14337,9 @@ snapshots:
scenes-app-posthog-ai--shared-thread--light:
hash: v1.k794b7964.08f4d570bad30aeabec4558d538fb3f87ad127f5ad28c37d60805c6f306615ba.Y9cV3pW4s0aPCq6v1FZ3z13bqJaRbABUQIbnJQDCCXI
scenes-app-posthog-ai--thread--dark:
- hash: v1.k794b7964.e8beb6bd9da0bd16dfc3b5b2db1cc3d869f2cd938bea753255d54c6fc0b5a8ed.a3ffEB8_YFnO3mggktU7mxg1tCCrukSty165R7rhG4Y
+ hash: v1.k794b7964.7e4119b8d4a9d0fa13f6766eee2fa34b6648a05a8daeb886850a16ea0fb343a1.JcepCXnx9hBCQk4gj_2NolDnARJcpzadLiuPOmkJokk
scenes-app-posthog-ai--thread--light:
- hash: v1.k794b7964.e51c1eff8d54ee2a21d1b31e33c5952e08f38119efec07231dc0b516921902be.oY9R9XRff38x5pP0OkOWJs-uZg6amO0dHlhd5thaWCI
+ hash: v1.k794b7964.e1634750116e9a68c58a0faf1dd19c03e1663b606fe7d3c606a098c7565df35c.Xt7_Pk5CFvoD1b3Y9GpnFNplQfRwKlELeALVlKXuRSE
scenes-app-posthog-ai--thread-scrolls-to-bottom-on-new-messages--dark:
hash: v1.k794b7964.6308f9e71b7f609897baee5c5fe5af1deb321882ecb0761fbf22051bb6531999.YXmikTdEmed3mJWRiglAFw66r284ajZbdJI5sT8kUAI
scenes-app-posthog-ai--thread-scrolls-to-bottom-on-new-messages--light:
@@ -14401,53 +14401,57 @@ 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.54ad5b18104e4e01d20da34010c667dcf6b8d59fd87173f7e61f95c20b1002c1.iWbOqOU6gY7a9E8-MTwfRZ760Q7h_XzAzklb5lMPOl8
+ hash: v1.k794b7964.523c2a2ef4f76164b2dfcc5a083b618ec34cc895b5ec87abca1cbd6ab0ce0ad9.CxH8-EVzEHWh8TVPzCRIA9lCUNhm05_bLwPKZRaObGM
scenes-app-posthog-ai-forms--thread-with-mixed-field-type-form--light:
- hash: v1.k794b7964.d9f3d49bfce307430ffb7fb05bfa861878e094eef5c2d84d77f69b75a4399053.QNo2yPY91q2TffO7F30d3B6IVLMDe2JXPWTgCWnyjRs
+ hash: v1.k794b7964.97a1d309353d0186627a8f27481206ac6bb5f84a44d028554c004e6eb7aa2367.MYfsMixDE2Cron27YIngV0_CavWx2JDauKDP0WnCQ3U
scenes-app-posthog-ai-forms--thread-with-multi-field-question--dark:
- hash: v1.k794b7964.ac11d0dd43e72ff466a356a9640bd7569c532dc1fe086aeef18132bbb5cae6ac.YIBQMSjdhF21LUGV3UlU1ty3FHw_asqf-BgiGvHmx8E
+ hash: v1.k794b7964.c727db6ff3c372400f1b34a00251e01e6bd29e13936e993143fc858ccdc80264.81OYYDEWfHzmgGLHcSBdd1XY9bR2bkDIJGHBkydxtno
scenes-app-posthog-ai-forms--thread-with-multi-field-question--light:
- hash: v1.k794b7964.24814c5ea4efc80778bd8edb5d61399338d9c70c50f7547336e9aa74bf87ad8d.nwFiSigNwHgXqt2C9P8RPf9eDRMkSOwAc7vfC41GAOg
+ hash: v1.k794b7964.390e2490b57ab8336ec66f2873d24d651b60fb3e0ead2c83af6175d503c64cbc.9EK94nnfWTuYz_KGqA_mZpy0Kpur73GOgvq1oVFq6kA
scenes-app-posthog-ai-forms--thread-with-multi-question-form--dark:
- hash: v1.k794b7964.e8fa9e5aceb1344f978d9fbe209234696c2cdc92d114168c8d70627744a855fa.0dx_62KFf-Kk7Zp6V6jYOpg2tUcYLgW1zFvDtkEBAds
+ hash: v1.k794b7964.5a9e507db6bee515ff6da7325ce27fc20f4dc2b32ee42d0926542914f4fb2afe.pY9XM3qewsWv7YuGHZVa4GSbEe0355hWoflfV-tKBdI
scenes-app-posthog-ai-forms--thread-with-multi-question-form--light:
- hash: v1.k794b7964.2abebca8398e2ec23af9994a45756613c782fbb88ee3339da17950e713e53f5f.Ri7ss3lQU-d2FgzVBlqkqeYyjw_XH3j9fvru5FQxNI0
+ hash: v1.k794b7964.32128e2ea47f97204495c30e51d9e81aa613a56ea35afe8c16db32c2577dd427.BgHGmw1p_NUn9gEmjbbiIWQr0NdvOi902xZuo5aoGQM
scenes-app-posthog-ai-forms--thread-with-multi-question-form-long-content--dark:
- hash: v1.k794b7964.a13a9caf409ab069110395c7b42be5fe5b645ee943e417fcfc79a8422145097a.wlDJMASmpreQ8MzoQCLUT4qhJXkZ8L4swUOdJ6jelWs
+ hash: v1.k794b7964.6023d1634955c4f09ccef94da92f7f09113a2544b15e6ed42cf4f8661e4ad6ea.PaVHOwnCauWz1g3f-Q3mR6BJvtdv1ZUoZ6yxBy8e1L8
scenes-app-posthog-ai-forms--thread-with-multi-question-form-long-content--light:
- hash: v1.k794b7964.93726239c3e3576be4ec9eddfa1bb8c7d0a37c1aee986fa65bc1ccb969c36382.NmP3bKZIjIF8r87L06YTEbSqIN6WGnXrCkFqUNN9cXs
+ hash: v1.k794b7964.20a86d89b06c4f2b7ef47f9366cef604af41f5b622900efe8df74a1d2ddd4041.IkUaXseOoOH80rSQxcpbjGeLNkCG3EI8eNsToD1RTwA
scenes-app-posthog-ai-forms--thread-with-multi-question-form-no-custom-answer--dark:
- hash: v1.k794b7964.eddbff8ce7e256fe4e46832326fa06c2c70ada68e22811a9b305c30954dd9e33.2f7Ov_ilzSj3tf3MQCNACgB6bKkrpboeJ0kbhbjZPaU
+ hash: v1.k794b7964.eb037f15adb875f997b1d3fa61bae1286f6e2f012b798caae2dbd4f483ed26de.qrSk-RWkARDsDToItVnJA5jQD4-K2Gy8TcTx3htFgyU
scenes-app-posthog-ai-forms--thread-with-multi-question-form-no-custom-answer--light:
- hash: v1.k794b7964.f8557f29128754128c086b5263c1c6b4485daabbacd9dee43fe1acd0f15a34aa.mTkIO4T5h3EvP-kDhA6mQ7cWL_E9JckkXsHxSqfEEWk
+ hash: v1.k794b7964.bfeeda7c48fbd7e605f84ccd1bea36095a510b0e6a74d5a00e92966fd7e066db.DVrniib-0vqLpnWsO8dPRmwZ3K6D-4QyY-gy8mtYyCM
scenes-app-posthog-ai-forms--thread-with-single-question-form--dark:
- hash: v1.k794b7964.e830a8740c4b0f36caaf39984d7d352fe3187f3f5810283543332f6f833b028d.N1kGYK6zVyTRFKqmNcbU71ZoRk3uNC97qSDGqGk0Jdk
+ hash: v1.k794b7964.7295f1f5ea51cfc634b67911b88b2fb86af248724d9057f7947444eef3e99eb0.sqxerD88nAwkiwSd7C6YxE4fl1jy-klFGx-PkLRZdWU
scenes-app-posthog-ai-forms--thread-with-single-question-form--light:
- hash: v1.k794b7964.651890737222ba6f727262dab6f99acdde180762e7f6b77cc31ea561eceb4632.bOFAlQQzkNG3w9fi3NAa3bN5A8C6uPIYgKwqji3nHJk
+ hash: v1.k794b7964.e1bc73233ca81b50074dbff1af48df45aff28c12fa96c7136e2542e61562f3d2.M5nPrKSGs1yaY3xvZEFUdwPIHA1fxxKoauuEZRb4ZFE
scenes-app-posthog-ai-forms--thread-with-slider-form--dark:
- hash: v1.k794b7964.5481a40b96036d21a09f5a29dfe20b003c8ef7cc84abddc438886643ada6746c.kEv1RYfuUWE_RyPK9OrqZ3NyV17zbWJHCNUymy77n3A
+ hash: v1.k794b7964.418a2ebf90f73f5634d758462c6ce975c98561fa09ef4203358058534b41f746.IVBTiydvu7fU3dhEsJbB4lJ3LE-GA7z382EGDSE-93w
scenes-app-posthog-ai-forms--thread-with-slider-form--light:
- hash: v1.k794b7964.dd203a8a15076c07f8e807ab85ce46e7036e3251b44a95f246c8ea4936c56982.s-dVkPNhcN58zMgn9MGOOlMXqa-Y9a_voS5i5xH2L4g
+ hash: v1.k794b7964.0fa0cfa796f3490386b7a311d5c186502bcbb8c1cb96080c9644ae433ff7f4ec.SIDdv62xlzQk8d7MdVOgydLKxCmPXKI9obtrG6OhMcs
scenes-app-posthog-ai-forms--thread-with-text-and-number-form--dark:
- hash: v1.k794b7964.69a1e5eea52abebae062fbccdfcd613e24760bd0843e54c1576cecbee868cc5d.DWFG-7lnbtlTvNy2hvY4v-IliU1BjPk9VaDqkQt4Bh0
+ hash: v1.k794b7964.facd192bb03d3df6b38f20e6013b1fceba68dc2dd34db0fc9cee305c0a341126.znEaknxEodm1Dnsk7410w3PUaacVaJltTxWwWHwc2Kw
scenes-app-posthog-ai-forms--thread-with-text-and-number-form--light:
- hash: v1.k794b7964.aee1550de1b97850cb1d8c27d39e40db81c28d4fe6116a13f48d45672c143710.M1lWbiiqC33CbFfL0ZdteiJH328flmdL2oPxzwPsJgw
+ hash: v1.k794b7964.10721901188497f184bda24ccfd799dd03cbcccccb1fdabbd86d0fb293375b38.OPA1aN19eYGYgdieSvoRpgYStJ7fpWXezR_IxCi4QA4
+ scenes-app-posthog-ai-quill-comparison--side-by-side--dark:
+ hash: v1.k794b7964.285adf0ae8b771153c6b737edb7b96ccfa022d029d6ee14fbfcce958f258a4a0.Ef69aUVCi8HIwRkcDv3AYumZ5zMiRVCLMYEqh_wXdqk
+ scenes-app-posthog-ai-quill-comparison--side-by-side--light:
+ hash: v1.k794b7964.e737cb1b7f07e629b193eb2b6a14a6555e5f2821d5a21c123cc5574f7266afe6.waj5w9YazP7PM-zFZNUbjS-45fxXf_BnCN7yWBBULOs
scenes-app-posthog-ai-tools--changelog-only--dark:
hash: v1.k794b7964.f17aec31dd25e93672f7d76b065a6b49052c643eb6da67458011462b883f1c9c.sYkAo1RWtXpQRQNxl5SzUkO4ELuuEshq9Kdbc0H1L0E
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.f22ce4e5d5c9f1a23d800afe1586984e5878639b5a3b0d88bdb0d7291b589971.AZJgwIxLFW2rvV37QZkNPgE6Aw47kXI80HiIZ8yt5nI
+ hash: v1.k794b7964.233f79eb96a107a7560461392a0c7c356051b90d5354cb5323ccefc31625ac09.lCsCKT7yJloySC6KehC_mVgjQ_XiVA9P4qkz6KTF974
scenes-app-posthog-ai-tools--dangerous-operation-pending-approval--light:
- hash: v1.k794b7964.05ad5fbe902c60249adb5303164e33fae7a10ee6dde04096c042ad187bfa113a.xo9-nsBdzZYhOABl8MJBrTxZIQuJayACJj6yZ7UYGNw
+ hash: v1.k794b7964.5b1105c4114ff5baf21101ec10bed3d54cfd9d68a3a55a2d203a45cbd3507374.Ni_zh0MUr_8IHcOhUO_OcIPla-TMXxRKA4taKTYTW8Y
scenes-app-posthog-ai-tools--dangerous-operation-pending-approval-long-content--dark:
- hash: v1.k794b7964.0422d91f81327d88a231d23c5ccb5fd44263f8e57ce310bcef9323e20bba09d0.Vx-lCyyHe3RgnfIdke2DtmXQnq94flXe64wsicpjE4U
+ hash: v1.k794b7964.91c9caf297cc2f6dd25b2eb5e349dc48f5b40399fc35636822d2703cae1aad70.WkR9qrQr7EiTafMQJkvQOIJEVyRku50dq7iEDplXfs8
scenes-app-posthog-ai-tools--dangerous-operation-pending-approval-long-content--light:
- hash: v1.k794b7964.1ea5f8d8c313c7f673940c6edfc836738cc9c527b05dfbdf6b5838c5596e66c3.nypVmBTG9h__aSzNLsIU2YoiTuj3XCbxYku4o11eQsA
+ hash: v1.k794b7964.8ea79991ba5dc44bc7218828bb8fa0f26db718994aef41c2595bd497db803149.v4stIrNCAajX7P3BWHnia1vrVXO3sK66-PTEadmyQUs
scenes-app-posthog-ai-tools--multi-visualization-in-thread--dark:
- hash: v1.k794b7964.6becd54faf97831df4f4a778c5e8de44acd297727ab9c1def058323cd071be33.PqDN2G62zNR4yAmnMU-xdjNsPU82m7BmBuYCveOsw6E
+ hash: v1.k794b7964.00d804501870cdda13575a74c0ed35a4083ec6cb0c7c341326ebdfafe89ebee9.DpOGQxpeTFEfcjAgj3KQlTrStnSr0fWnDb-5NRbl-GE
scenes-app-posthog-ai-tools--multi-visualization-in-thread--light:
- hash: v1.k794b7964.7bd16ac554b0ef6a0f9abf8e8e7d5bc460369c2b0c3dd778776e4bf63ec97bc0.94NsDXj_srsigHAu8uGEMBlarn0ZQnIfJnyADZELmkM
+ hash: v1.k794b7964.284e0580265a0239ec68dafbe4561e244fa89ed79e169f2279a45a52589c1d7f.6vmLRTHcMlDoJezr1fLjsWh9t1Ba3CqoIrMBWpySIyA
scenes-app-posthog-ai-tools--notebook-artifact-markdown-only--dark:
hash: v1.k794b7964.153ef583b440b6078bd4d7c0fda71f34388699df02b964f464f82754b883f2d2.Th0lXC3c1DSCIyk2A7Di_YHPboZhWXtudWM0qHA5934
scenes-app-posthog-ai-tools--notebook-artifact-markdown-only--light:
@@ -14493,9 +14497,9 @@ snapshots:
scenes-app-posthog-ai-tools--task-execution-component--light:
hash: v1.k794b7964.15f7de2d5b8a2522e95dfc9b81723eb672d95a1ac90f7693a015cf417eab632f.o04xZc4nuuAE4151LWgMT0JfBwWqowDZdUHmHAJhHAE
scenes-app-posthog-ai-tools--task-execution-with-failure--dark:
- hash: v1.k794b7964.d2b80939730bde72f5200735588819e4da983497a862733565d1a00b91e844ee.yU8y1RdwfXtNoHThRJqU0fpryNDpmphW06Jj_NWENTQ
+ hash: v1.k794b7964.117bdc02138060df6f09128fde836fd9f4c9835b7073c7dc36407199d371726a._sGmJoN5t7TJYP-NfumsFmtRYG_0osRTKsC5bKZ1tJU
scenes-app-posthog-ai-tools--task-execution-with-failure--light:
- hash: v1.k794b7964.e56bc7d3257f75c155232b600debac6d5a1ed42b70475d04b18623807c6cb87f.52_GqnYfKz8PCs66PWQSCwFAiSFvh-99lxxlotFnQe4
+ hash: v1.k794b7964.0bee710d2ade365a3622befc67925c06f3a26fea1e5f7a63e0a90ea38f20cf11.XW_llxkl-w6Hq-cfR2vyajjCrHHSHtvu0-zi4NUXW60
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/frontend/src/lib/components/CodeSnippet/index.ts b/frontend/src/lib/components/CodeSnippet/index.ts
index f19b17547496..e217ddee76dc 100644
--- a/frontend/src/lib/components/CodeSnippet/index.ts
+++ b/frontend/src/lib/components/CodeSnippet/index.ts
@@ -1 +1 @@
-export { CodeSnippet, Language, getLanguage } from './CodeSnippet'
+export { CodeLine, CodeSnippet, Language, getLanguage } from './CodeSnippet'
diff --git a/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.scss b/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.scss
index dc3ae00ef8aa..9c8e5e58b455 100644
--- a/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.scss
+++ b/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.scss
@@ -91,38 +91,40 @@
overflow-x: auto;
}
- table {
+ // Only LemonMarkdown's own table carries the class, so a table a caller swaps in through `components`
+ // keeps its own styling.
+ .LemonMarkdown__table {
border-spacing: 0;
border-collapse: separate;
border: 1px solid var(--border);
border-radius: var(--radius);
- }
-
- th,
- td {
- // Stops one long prose cell from taking all the width from the short columns.
- max-width: 40rem;
- padding: 0.375rem 0.75rem;
- color: var(--default);
- text-align: left;
-
- // `anywhere` lets a column shrink to one character. `break-word` keeps the longest word as the minimum.
- overflow-wrap: break-word;
- vertical-align: top;
- border-right: 1px solid var(--border);
- border-bottom: 1px solid var(--border);
- &:last-child {
- border-right: none;
+ th,
+ td {
+ // Stops one long prose cell from taking all the width from the short columns.
+ max-width: 40rem;
+ padding: 0.375rem 0.75rem;
+ color: var(--default);
+ text-align: left;
+
+ // `anywhere` lets a column shrink to one character. `break-word` keeps the longest word as the minimum.
+ overflow-wrap: break-word;
+ vertical-align: top;
+ border-right: 1px solid var(--border);
+ border-bottom: 1px solid var(--border);
+
+ &:last-child {
+ border-right: none;
+ }
}
- }
- th {
- font-weight: 600;
- }
+ th {
+ font-weight: 600;
+ }
- tbody tr:last-child td {
- border-bottom: none;
+ tbody tr:last-child td {
+ border-bottom: none;
+ }
}
.LemonMarkdown__task {
diff --git a/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.tsx b/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.tsx
index 443239d642d6..0f2b60bb1974 100644
--- a/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.tsx
+++ b/frontend/src/lib/lemon-ui/LemonMarkdown/LemonMarkdown.tsx
@@ -2,7 +2,7 @@ import './LemonMarkdown.scss'
import clsx from 'clsx'
import React, { memo, useMemo } from 'react'
-import ReactMarkdown, { defaultUrlTransform } from 'react-markdown'
+import ReactMarkdown, { type Components, defaultUrlTransform } from 'react-markdown'
import remarkBreaks from 'remark-breaks'
import remarkGfm from 'remark-gfm'
@@ -69,6 +69,8 @@ function LemonMarkdownContainer({ children, className }: LemonMarkdownContainerP
return <div className={clsx('LemonMarkdown', className)}>{children}</div>
}
+export type LemonMarkdownComponents = Partial<Components>
+
export interface LemonMarkdownProps {
children: string
/** Whether headings should just be <strong> text. Recommended for item descriptions. */
@@ -116,6 +118,16 @@ export interface LemonMarkdownProps {
renderChartRef?: (chartId: string, sourceOffset?: number) => React.ReactNode
/** Without it, or on a nullish return, a `t:<ms>` target renders as its label. */
renderTimestampRef?: (timestampMs: number) => React.ReactNode
+ /**
+ * Optional renderer for fenced code blocks other than mermaid, after `codeMaxLines` is applied. When
+ * omitted, a block renders as a compact `CodeSnippet`. Inline code is never passed to it.
+ */
+ renderCodeBlock?: (code: string, language: Language) => React.ReactNode
+ /**
+ * Element renderers that replace the built-in ones, e.g. a design system's table. Pass a stable
+ * (module-level) object: a new one each render re-renders every block.
+ */
+ components?: LemonMarkdownComponents
}
const HEADING_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const
@@ -158,6 +170,8 @@ const LemonMarkdownRenderer = memo(function LemonMarkdownRenderer({
renderMermaid,
renderChartRef,
renderTimestampRef,
+ renderCodeBlock,
+ components: componentOverrides,
}: LemonMarkdownProps): JSX.Element {
const components = useMemo(
() => ({
@@ -195,6 +209,9 @@ const LemonMarkdownRenderer = memo(function LemonMarkdownRenderer({
const lines = value.split('\n')
const displayedValue =
codeMaxLines && lines.length > codeMaxLines ? lines.slice(0, codeMaxLines).join('\n') : value
+ if (renderCodeBlock) {
+ return <>{renderCodeBlock(displayedValue, language)}</>
+ }
return (
<CodeSnippet language={language} wrap={wrapCode} compact>
{displayedValue}
@@ -248,7 +265,7 @@ const LemonMarkdownRenderer = memo(function LemonMarkdownRenderer({
: {}),
table: ({ node, ...props }: any): JSX.Element => (
<div className="LemonMarkdown__table-wrapper">
- <table {...props} />
+ <table {...props} className="LemonMarkdown__table" />
</div>
),
span: ({ className, ...props }: any): JSX.Element => {
@@ -316,8 +333,10 @@ const LemonMarkdownRenderer = memo(function LemonMarkdownRenderer({
])
)
: {}),
+ ...componentOverrides,
}),
[
+ componentOverrides,
disableImages,
disableLinks,
lowKeyHeadings,
@@ -327,6 +346,7 @@ const LemonMarkdownRenderer = memo(function LemonMarkdownRenderer({
renderMermaid,
renderChartRef,
renderTimestampRef,
+ renderCodeBlock,
]
)
@@ -369,6 +389,8 @@ function LemonMarkdownComponent({
renderMermaid,
renderChartRef,
renderTimestampRef,
+ renderCodeBlock,
+ components,
className,
}: LemonMarkdownProps): JSX.Element {
return (
@@ -384,6 +406,8 @@ function LemonMarkdownComponent({
renderMermaid={renderMermaid}
renderChartRef={renderChartRef}
renderTimestampRef={renderTimestampRef}
+ renderCodeBlock={renderCodeBlock}
+ components={components}
>
{children}
</LemonMarkdownRenderer>
diff --git a/frontend/src/lib/lemon-ui/LemonMarkdown/index.ts b/frontend/src/lib/lemon-ui/LemonMarkdown/index.ts
index 68705c4e8d5d..ce4b1cd61e11 100644
--- a/frontend/src/lib/lemon-ui/LemonMarkdown/index.ts
+++ b/frontend/src/lib/lemon-ui/LemonMarkdown/index.ts
@@ -1,6 +1,7 @@
export {
CHART_REF_PREFIX,
LemonMarkdown,
+ type LemonMarkdownComponents,
type LemonMarkdownProps,
TIMESTAMP_REF_PREFIX,
slugifyHeading,
diff --git a/frontend/src/scenes/max/AGENTS.md b/frontend/src/scenes/max/AGENTS.md
index d4e35bb19bd2..bcdc4689bf0c 100644
--- a/frontend/src/scenes/max/AGENTS.md
+++ b/frontend/src/scenes/max/AGENTS.md
@@ -26,6 +26,11 @@ Per-concern mapping, `langgraph` (LEGACY, frozen) → `sandbox` (NEW, build here
New behavior — new tools, new context types, new UI affordances — goes on the **sandbox** path. The LangGraph runtime is slated for removal once sandbox reaches parity; keeping its surface from growing makes the eventual deletion a clean removal rather than an untangling.
- ✅ Bugfixes that keep existing LangGraph conversations working.
+- ✅ The quill skin of the LangGraph thread and composer behind `phai-quill` or `today-rail-nav`: `Thread.tsx`, `QuillQuestionInput.tsx`,
+ the `Quill*` siblings in `components/` and `messages/quill/` fork only the view, and share behavior through `useQuestionInput`,
+ `useModeSelector`, `useAnswerRating` and the surface's shared presenters.
+ A message presenter that has both skins switches on `useQuillThread()` at its top, like `PlanningAnswer`, and keeps its quill body in `messages/quill/`.
+ Code outside the thread (the composer, `Intro`, the suggestion badges) has no thread context, so it switches on `useThreadSkin()` from `api/logics`, which reads the flags. It stays out of `api/primitives` because the homepage composer loads eagerly.
- ❌ Net-new capability on the LangGraph path.
- ❌ New fields on `MaxUIContext` for a sandbox feature — use `AttachedContext` instead.
- ❌ No new MaxTools.
diff --git a/frontend/src/scenes/max/Intro.tsx b/frontend/src/scenes/max/Intro.tsx
index e5fc5602e6a1..aef6d3dda0a5 100644
--- a/frontend/src/scenes/max/Intro.tsx
+++ b/frontend/src/scenes/max/Intro.tsx
@@ -1,7 +1,11 @@
import { useValues } from 'kea'
+import { Heading, Text } from '@posthog/quill'
+
import { Logomark } from 'lib/brand'
+import { useThreadSkin } from 'products/posthog_ai/frontend/api/logics'
+
import { AILiabilityNotice } from './components/AILiabilityNotice'
import { MaxChangelog } from './components/MaxChangelog'
import { maxLogic } from './maxLogic'
@@ -14,6 +18,7 @@ export function Intro({
forceSubheadline?: string | null
}): JSX.Element {
const { headline } = useValues(maxLogic)
+ const skin = useThreadSkin()
const headlineToUse = forceHeadline || headline
const subheadlineToUse = forceSubheadline === null ? null : forceSubheadline || 'Build something people want.'
@@ -22,12 +27,26 @@ export function Intro({
<div className="flex p-2">
<Logomark jumpOnClick size="md" />
</div>
- <div className="text-center mb-1">
- <h2 className="text-xl @2xl/main-content:text-2xl font-bold mb-2 text-balance">{headlineToUse}</h2>
- {subheadlineToUse && (
- <div className="text-sm italic text-tertiary text-pretty py-0.5">{subheadlineToUse}</div>
- )}
- </div>
+ {skin === 'quill' ? (
+ <div data-quill className="mb-1 flex flex-col items-center gap-2 text-center">
+ <Heading size="xl" render={<h2 className="m-0 text-balance @2xl/main-content:text-2xl" />}>
+ {headlineToUse}
+ </Heading>
+ {subheadlineToUse && (
+ <Text size="sm" variant="muted" className="m-0 italic text-pretty">
+ {subheadlineToUse}
+ </Text>
+ )}
+ </div>
+ ) : (
+ <div className="text-center mb-1">
+ <h2 className="text-xl @2xl/main-content:text-2xl font-bold mb-2 text-balance">{headlineToUse}</h2>
+ {subheadlineToUse && (
+ <div className="text-sm italic text-tertiary text-pretty py-0.5">{subheadlineToUse}</div>
+ )}
+ </div>
+ )}
+ {/* The notice and the changelog stay lemon banners in the quill skin until they get one of their own. */}
<AILiabilityNotice />
<MaxChangelog />
</>
diff --git a/frontend/src/scenes/max/Max.tsx b/frontend/src/scenes/max/Max.tsx
index 067a7c48b951..1886d3be7c82 100644
--- a/frontend/src/scenes/max/Max.tsx
+++ b/frontend/src/scenes/max/Max.tsx
@@ -284,7 +284,7 @@ export const MaxInstance = React.memo(function MaxInstance({
</LemonBanner>
</div>
)}
- <Thread className={cn('p-3', sidePanel && 'p-1')} />
+ <Thread compact={sidePanel} />
<SandboxComposerSurfaces />
{!conversation?.has_unsupported_content && (
<SidebarQuestionInput isSticky sidePanel={sidePanel} />
diff --git a/frontend/src/scenes/max/PostHogAiQuillComparison.stories.tsx b/frontend/src/scenes/max/PostHogAiQuillComparison.stories.tsx
new file mode 100644
index 000000000000..c576b5fda3ac
--- /dev/null
+++ b/frontend/src/scenes/max/PostHogAiQuillComparison.stories.tsx
@@ -0,0 +1,224 @@
+import {
+ COMPARISON_CONVERSATION_ID,
+ COMPARISON_PANEL_ID,
+ COMPARISON_RUN_ID,
+ COMPARISON_TASK_ID,
+ comparisonConversation,
+ comparisonQueryResponse,
+ comparisonRun,
+ comparisonRunLogBody,
+ comparisonTask,
+} from './__mocks__/quillComparison.mocks'
+import { MOCK_DEFAULT_BASIC_USER, MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
+import { Meta, StoryObj } from '@storybook/react'
+import { useActions } from 'kea'
+import { HttpResponse } from 'msw'
+import { type ReactNode, useEffect, useState } from 'react'
+
+import { LemonSlider } from 'lib/lemon-ui/LemonSlider'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import { type ThreadSkin, ThreadSkinOverrideContext } from 'products/posthog_ai/frontend/api/logics'
+import { EmbeddedRunner } from 'products/posthog_ai/frontend/api/runner'
+
+import conversationList from './__mocks__/conversationList.json'
+import { AiFirstMaxInstance } from './components/AiFirstMaxInstance'
+import { maxLogic } from './maxLogic'
+
+/**
+ * One investigation, three chats: the legacy chat as the flag-off majority sees it, the same chat in the quill
+ * skin that `today-rail-nav` turns on, and the sandbox runner ("PostHog AI 2.0") in the same skin. The gaps
+ * list under each quill column names what still renders in LemonUI there.
+ */
+
+async function queryHandler({ request }: { request: Request }): Promise<[number, Record<string, unknown>] | undefined> {
+ const body = (await request.json()) as { query?: Record<string, unknown> }
+ const response = body.query ? comparisonQueryResponse(body.query) : null
+ return response ? [200, response] : undefined
+}
+
+const meta: Meta = {
+ title: 'Scenes-App/PostHog AI/Quill comparison',
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/organizations/@current/': () => [
+ 200,
+ { ...MOCK_DEFAULT_ORGANIZATION, is_ai_data_processing_approved: true },
+ ],
+ '/api/environments/:team_id/conversations/': () => [200, conversationList],
+ [`/api/environments/:team_id/conversations/${COMPARISON_CONVERSATION_ID}/`]: () => [
+ 200,
+ comparisonConversation(),
+ ],
+ '/api/code/invites/check-access/': { has_access: true, has_loops_access: false },
+ '/api/projects/:team_id/tasks/': { count: 1, next: null, previous: null, results: [comparisonTask()] },
+ '/api/projects/:team_id/tasks/repositories/': { repositories: [] },
+ '/api/projects/:team_id/tasks/@me/config/': { ai_run_preferences: {}, resolved_ai_run_defaults: {} },
+ '/api/projects/:team_id/integrations/': { results: [] },
+ [`/api/projects/:team_id/tasks/${COMPARISON_TASK_ID}/`]: comparisonTask(),
+ [`/api/projects/:team_id/tasks/${COMPARISON_TASK_ID}/runs/`]: {
+ count: 1,
+ next: null,
+ previous: null,
+ results: [comparisonRun()],
+ },
+ [`/api/projects/:team_id/tasks/${COMPARISON_TASK_ID}/runs/${COMPARISON_RUN_ID}/`]: comparisonRun(),
+ [`/api/projects/:team_id/tasks/${COMPARISON_TASK_ID}/runs/${COMPARISON_RUN_ID}/logs`]: () =>
+ new HttpResponse(comparisonRunLogBody()),
+ [`/api/projects/:team_id/tasks/${COMPARISON_TASK_ID}/runs/${COMPARISON_RUN_ID}/logs/`]: () =>
+ new HttpResponse(comparisonRunLogBody()),
+ '/api/users/@me/': () => [200, { ...MOCK_DEFAULT_BASIC_USER, is_staff: false }],
+ },
+ post: {
+ '/api/environments/:team_id/query/': queryHandler,
+ '/api/environments/:team_id/query/:kind/': queryHandler,
+ },
+ }),
+ ],
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2024-03-15T14:10:00Z',
+ // Three live threads with charts: a snapshot of this page would be slow and flaky, and the story is a
+ // review surface, not a regression gate.
+ testOptions: { skip: true },
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof meta>
+
+const SHARED_GAPS = [
+ 'Context chips are LemonTags inside the quill composer',
+ 'The @-picker opens the Lemon taxonomic filter',
+ 'Insight charts and tables keep their Lemon controls',
+]
+
+const LEGACY_QUILL_GAPS = [
+ ...SHARED_GAPS,
+ 'Feedback prompt, ticket prompt and approval card stay Lemon cards',
+ 'Notebook artifacts and the memory settings dialog stay Lemon',
+ 'Mode tooltips lose their tool lists in the quill menu',
+ 'Slash-command autocomplete is a Lemon menu',
+]
+
+const SANDBOX_QUILL_GAPS = [
+ ...SHARED_GAPS,
+ 'No welcome header or suggestion row in the quill composer',
+ 'Plan card and permission card are Lemon inside the quill thread',
+]
+
+function Column({
+ title,
+ caption,
+ gaps,
+ skin,
+ width,
+ children,
+}: {
+ title: string
+ caption: string
+ gaps?: string[]
+ skin: ThreadSkin
+ width: number
+ children: ReactNode
+}): JSX.Element {
+ return (
+ // eslint-disable-next-line react/forbid-dom-props
+ <section className="flex shrink-0 flex-col gap-2" style={{ width }}>
+ <header className="flex flex-col gap-1 px-1">
+ <h2 className="m-0 text-base font-semibold">{title}</h2>
+ <p className="m-0 text-xs text-secondary">{caption}</p>
+ </header>
+ <div className="flex h-[880px] flex-col overflow-hidden rounded border bg-surface-primary">
+ <ThreadSkinOverrideContext.Provider value={skin}>{children}</ThreadSkinOverrideContext.Provider>
+ </div>
+ {gaps && gaps.length > 0 && (
+ <details className="rounded border px-3 py-2 text-xs" open>
+ <summary className="cursor-pointer font-semibold">Still Lemon in this column</summary>
+ <ul className="mb-0 mt-1 list-disc pl-4 text-secondary">
+ {gaps.map((gap) => (
+ <li key={gap}>{gap}</li>
+ ))}
+ </ul>
+ </details>
+ )}
+ </section>
+ )
+}
+
+/** The legacy chat scene, pointed at the comparison conversation. Both legacy columns share one logic. */
+function LegacyChat(): JSX.Element {
+ const { setConversationId } = useActions(maxLogic({ panelId: COMPARISON_PANEL_ID }))
+ useEffect(() => {
+ setConversationId(COMPARISON_CONVERSATION_ID)
+ }, [setConversationId])
+ return <AiFirstMaxInstance tabId={COMPARISON_PANEL_ID} />
+}
+
+function SandboxChat(): JSX.Element {
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <EmbeddedRunner taskId={COMPARISON_TASK_ID} />
+ </div>
+ )
+}
+
+// Down to 320px, narrower than the side panel, so the narrow layouts can be checked here.
+const MIN_COLUMN_WIDTH = 320
+const MAX_COLUMN_WIDTH = 800
+
+function SideBySideComparison(): JSX.Element {
+ const [width, setWidth] = useState(600)
+ return (
+ <div className="flex flex-col gap-4 p-6">
+ <div className="flex w-[480px] items-center gap-3 text-xs">
+ <span className="shrink-0 font-semibold">Column width</span>
+ <LemonSlider
+ value={width}
+ onChange={setWidth}
+ min={MIN_COLUMN_WIDTH}
+ max={MAX_COLUMN_WIDTH}
+ step={10}
+ className="flex-1"
+ />
+ <span className="w-12 shrink-0 text-right tabular-nums">{width}px</span>
+ </div>
+ <div className="flex items-start gap-6 overflow-x-auto">
+ <Column
+ title="PostHog AI now"
+ caption="Flag off, the majority today: the LangGraph conversation in LemonUI."
+ skin="lemon"
+ width={width}
+ >
+ <LegacyChat />
+ </Column>
+ <Column
+ title="PostHog AI quill"
+ caption="phai-quill or today-rail-nav on: the same LangGraph conversation in the quill skin."
+ gaps={LEGACY_QUILL_GAPS}
+ skin="quill"
+ width={width}
+ >
+ <LegacyChat />
+ </Column>
+ <Column
+ title="PostHog AI 2.0 quill"
+ caption="phai-sandbox-mode and today-rail-nav on: the sandbox runner in the quill skin."
+ gaps={SANDBOX_QUILL_GAPS}
+ skin="quill"
+ width={width}
+ >
+ <SandboxChat />
+ </Column>
+ </div>
+ </div>
+ )
+}
+
+export const SideBySide: Story = {
+ render: () => <SideBySideComparison />,
+}
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index ff7a392dcac9..c0372f98c634 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -1,95 +1,64 @@
import clsx from 'clsx'
-import { BindLogic, useActions, useValues } from 'kea'
-import posthog from 'posthog-js'
-import React, { useCallback, useLayoutEffect, useMemo, useState } from 'react'
+import { BindLogic, useValues } from 'kea'
+import React, { useCallback, useMemo, useState } from 'react'
+import { IconChevronRight, IconWarning, IconWrench } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonDivider, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
import {
- IconChevronRight,
- IconCollapse,
- IconCopy,
- IconExpand,
- IconEye,
- IconHide,
- IconNotebook,
- IconRefresh,
- IconThumbsDown,
- IconThumbsDownFilled,
- IconThumbsUp,
- IconThumbsUpFilled,
- IconWarning,
- IconWrench,
- IconX,
-} from '@posthog/icons'
-import {
- LemonBanner,
- LemonButton,
- LemonButtonPropsBase,
- LemonCheckbox,
- LemonDialog,
- LemonDivider,
- LemonInput,
- LemonSkeleton,
- Tooltip,
-} from '@posthog/lemon-ui'
+ ChatBubble,
+ ChatBubbleContent,
+ ChatMarker,
+ ChatMarkerContent,
+ ChatMessage,
+ ChatMessageContent,
+ Skeleton,
+} from '@posthog/quill'
-import {
- InsightBreakdownSummary,
- PropertiesSummary,
- SeriesSummary,
-} from 'lib/components/Cards/InsightCard/InsightDetails'
-import { TopHeading } from 'lib/components/Cards/InsightCard/TopHeading'
import { NotFound } from 'lib/components/NotFound'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { cn } from 'lib/utils/css-classes'
-import { pluralize } from 'lib/utils/strings'
-import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { sceneLogic } from 'scenes/sceneLogic'
-import { urls } from 'scenes/urls'
-import { userLogic } from 'scenes/userLogic'
-import { copyToClipboard } from '~/lib/utils/copyToClipboard'
-import { stripMarkdown } from '~/lib/utils/markdown'
-import { Query } from '~/queries/Query/Query'
import {
- AssistantForm,
AssistantMessage,
AssistantToolCallMessage,
TaskExecutionStatus as ExecutionStatus,
FailureMessage,
MultiQuestionForm,
- MultiVisualizationMessage,
- PlanningStep,
- PlanningStepStatus,
} from '~/queries/schema/schema-assistant-messages'
-import { DataVisualizationNode, InsightVizNode } from '~/queries/schema/schema-general'
-import { isDataVisualizationNode, isHogQLQuery } from '~/queries/utils'
-import { PendingApproval, RecordingUniversalFilters, Region } from '~/types'
+import { PendingApproval, RecordingUniversalFilters } from '~/types'
import { RecordingsWidget } from 'products/posthog_ai/frontend/api/dataWidgets'
import {
AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM,
getThinkingMessageFromResponse,
- messageRatingsLogic,
runStreamLogic,
useAttachedContext,
useForegroundStream,
+ useThreadSkin,
} from 'products/posthog_ai/frontend/api/logics'
import {
AssistantFailureMessage,
ContextUsageChip,
MarkdownMessage,
MessageTemplate,
+ QuillAssistantBubble,
+ QuillAssistantMarkdown,
+ MessageReveal,
+ NotQuill,
+ QuillHumanBubble,
+ QuillThreadSkin,
ReasoningAnswer,
ThreadView,
TurnTrailerActions,
type TurnTrailer,
- useThreadSkin,
+ useQuillThread,
} from 'products/posthog_ai/frontend/api/primitives'
import { LogEntry } from 'products/posthog_ai/frontend/lib/parse-logs'
import { isPiTaskRuntime } from 'products/posthog_ai/frontend/types/taskTypes'
import { ReplayVisionScanWidget } from 'products/replay_vision/frontend/posthogAi/ReplayVisionScanWidget'
-import { LangGraphActivity, ShimmeringContent } from './components/Activity'
+import { LangGraphActivity } from './components/Activity'
import { FeedbackDisplay } from './components/FeedbackDisplay'
import { ContextSummary } from './Context'
import { DangerousOperationApprovalCard } from './DangerousOperationApprovalCard'
@@ -98,15 +67,20 @@ import { EnhancedToolCall, ToolRegistration, getToolDefinitionFromToolCall } fro
import { maxGlobalLogic } from './maxGlobalLogic'
import { SIDE_PANEL_PANEL_ID, ThreadMessage, maxLogic } from './maxLogic'
import { maxThreadLogic } from './maxThreadLogic'
+import { AssistantMessageForm } from './messages/AssistantMessageForm'
import { MultiQuestionFormRecap } from './messages/MultiQuestionForm'
+import { MultiVisualizationAnswer } from './messages/MultiVisualizationAnswer'
import { NotebookArtifactAnswer } from './messages/NotebookArtifactAnswer'
+import { PlanningAnswer } from './messages/PlanningAnswer'
+import { RetriableFailureActions } from './messages/RetriableFailureActions'
+import { SuccessActions } from './messages/SuccessActions'
import { isRenderableUIPayloadTool } from './messages/UIPayloadAnswer'
import { VisualizationArtifact } from './messages/VisualizationArtifact'
import { MAX_SLASH_COMMANDS, SlashCommandName } from './slash-commands'
import { TicketPrompt } from './TicketPrompt'
import { getTicketPromptData, getTicketSummaryData, isTicketConfirmationMessage } from './ticketUtils'
import { ToolCallWidgetDef, getToolCallDescriptionAndWidgetDef } from './toolCallDisplay'
-import { TraceIdProvider, useTraceId } from './TraceIdContext'
+import { TraceIdProvider } from './TraceIdContext'
import { useFeedback } from './useFeedback'
import {
isArtifactMessage,
@@ -118,7 +92,6 @@ import {
isMultiVisualizationMessage,
isNotebookArtifactContent,
isVisualizationArtifactContent,
- visualizationTypeToQuery,
} from './utils'
// Helper function to check if a message is an error or failure
@@ -126,10 +99,31 @@ function isErrorMessage(message: ThreadMessage): boolean {
return message.type !== 'human' && (message.status === 'error' || message.type === 'ai/failure')
}
-export function Thread({ className }: { className?: string }): JSX.Element | null {
+/** A short assistant-side note (a feedback nudge, a retry notice): a lemon bubble, or quill ghost prose. */
+function AssistantNote({
+ children,
+ boxClassName,
+}: {
+ children: React.ReactNode
+ /** Lemon only: extra classes on the bubble's box. */
+ boxClassName?: string
+}): JSX.Element {
+ const quill = useQuillThread()
+ if (quill) {
+ return <QuillAssistantBubble>{children}</QuillAssistantBubble>
+ }
+ return (
+ <MessageTemplate type="ai" boxClassName={boxClassName}>
+ {children}
+ </MessageTemplate>
+ )
+}
+
+export function Thread({ compact = false }: { compact?: boolean }): JSX.Element | null {
const { conversation, sandboxConversationKey, isConvertedConversation } = useValues(maxThreadLogic)
const { panelId } = useValues(maxLogic)
const threadSkin = useThreadSkin()
+ const quill = threadSkin === 'quill'
const isSandboxRuntime = conversation?.agent_runtime === 'sandbox'
const isPiTask = isPiTaskRuntime(conversation?.task?.runtime)
@@ -145,9 +139,12 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul
active: panelId === SIDE_PANEL_PANEL_ID && rendersSandboxThread,
})
+ // The quill thread spaces its rows like PostHog Desktop, with the 2.0 thread's side gutter; the lemon
+ // thread keeps its tighter rhythm.
const containerClassName = cn(
- '@container/thread flex flex-col items-stretch w-full max-w-180 self-center gap-1.5 grow mx-auto',
- className
+ '@container/thread flex flex-col items-stretch w-full max-w-180 self-center grow mx-auto',
+ quill ? 'gap-4 px-4' : 'gap-1.5',
+ quill ? (compact ? 'py-1' : 'py-3') : compact ? 'p-1' : 'p-3'
)
// Feedback identity: always the task, matching `$ai_session_id` on other surfaces.
@@ -191,22 +188,39 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul
if (!sandboxConversationKey) {
return null
}
- return (
- <div className={containerClassName}>
+ const converted = (
+ <>
<LegacyThread showTrailers={false} />
- <LemonDivider dashed label="Message history was converted to the new format" className="my-3" />
+ {quill ? (
+ <ChatMarker variant="separator" className="before:min-w-4 after:min-w-4">
+ <ChatMarkerContent className="max-w-[80%] shrink">
+ Message history was converted to the new format
+ </ChatMarkerContent>
+ </ChatMarker>
+ ) : (
+ <LemonDivider dashed label="Message history was converted to the new format" className="my-3" />
+ )}
<BindLogic
logic={runStreamLogic}
props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}
>
<ThreadView virtualized={false} renderTurnTrailer={renderTurnTrailer} skin={threadSkin} />
</BindLogic>
- </div>
+ </>
+ )
+ return quill ? (
+ <QuillThreadSkin className={containerClassName}>{converted}</QuillThreadSkin>
+ ) : (
+ <div className={containerClassName}>{converted}</div>
)
}
// Pure LangGraph conversation.
- return (
+ return quill ? (
+ <QuillThreadSkin className={containerClassName}>
+ <LegacyThread showTrailers />
+ </QuillThreadSkin>
+ ) : (
<div className={containerClassName}>
<LegacyThread showTrailers />
</div>
@@ -340,38 +354,44 @@ function LegacyThread({ showTrailers }: { showTrailers: boolean }): JSX.Element
(ticketSummaryData.discarded ? (
<p className="m-0 ml-1 mt-1 text-xs text-muted italic">Ticket creation discarded</p>
) : (
- <TicketPrompt
- conversationId={conversationId}
- traceId={traceId}
- summary={ticketSummaryData.summary}
- />
+ <NotQuill>
+ <TicketPrompt
+ conversationId={conversationId}
+ traceId={traceId}
+ summary={ticketSummaryData.summary}
+ />
+ </NotQuill>
))}
</React.Fragment>
)
})
})()}
{showTrailers && conversationId && isPromptVisible && !streamingActive && (
- <MessageTemplate type="ai">
+ <AssistantNote>
<div className="flex flex-col gap-2">
<span className="text-xs text-muted">How is PostHog AI doing? (optional)</span>
<FeedbackDisplay conversationId={conversationId} />
</div>
- </MessageTemplate>
+ </AssistantNote>
)}
{showTrailers && conversationId && isDetailedFeedbackVisible && !streamingActive && (
- <FeedbackPrompt conversationId={conversationId} traceId={traceId} />
+ <NotQuill>
+ <FeedbackPrompt conversationId={conversationId} traceId={traceId} />
+ </NotQuill>
)}
{showTrailers && conversationId && isThankYouVisible && !streamingActive && (
- <MessageTemplate type="ai">
+ <AssistantNote>
<p className="m-0 text-sm text-secondary">Thanks for your feedback and using PostHog AI!</p>
- </MessageTemplate>
+ </AssistantNote>
)}
{showTrailers && conversationId && ticketPromptData.needed && (
- <TicketPrompt
- conversationId={conversationId}
- traceId={traceId}
- initialText={ticketPromptData.initialText}
- />
+ <NotQuill>
+ <TicketPrompt
+ conversationId={conversationId}
+ traceId={traceId}
+ initialText={ticketPromptData.initialText}
+ />
+ </NotQuill>
)}
</>
) : conversationId ? (
@@ -480,6 +500,7 @@ function MessageContainer({
children: React.ReactNode
className?: string
}): JSX.Element {
+ const quill = useQuillThread()
return (
<div
className={cn(
@@ -489,7 +510,8 @@ function MessageContainer({
// keystroke latency grow with thread length. `auto 100px` is only the pre-first-render
// estimate; after a message renders once, the browser remembers its real size.
'[content-visibility:auto] [contain-intrinsic-size:auto_100px]',
- groupType === 'human' ? 'flex-row-reverse ml-4 @md/thread:ml-10 ' : 'mr-4 @md/thread:mr-10',
+ // The quill bubbles align themselves and cap their own width, so the row stays full width.
+ !quill && (groupType === 'human' ? 'flex-row-reverse ml-4 @md/thread:ml-10 ' : 'mr-4 @md/thread:mr-10'),
className
)}
>
@@ -526,6 +548,7 @@ const Message = React.memo(function Message({
webSearchResultsByToolUseId,
} = useValues(maxThreadLogic)
const { conversationId } = useValues(maxLogic)
+ const quill = useQuillThread()
const groupType = message.type === 'human' ? 'human' : 'ai'
const key = message.id || 'no-id'
@@ -551,16 +574,17 @@ const Message = React.memo(function Message({
return null
}
return matchingApprovals.map((approval) => (
- <DangerousOperationApprovalCard
- key={`approval-${approval.proposal_id}`}
- operation={{
- status: 'pending_approval',
- proposalId: approval.proposal_id,
- toolName: approval.tool_name,
- preview: approval.preview,
- payload: approval.payload as Record<string, any>,
- }}
- />
+ <NotQuill key={`approval-${approval.proposal_id}`}>
+ <DangerousOperationApprovalCard
+ operation={{
+ status: 'pending_approval',
+ proposalId: approval.proposal_id,
+ toolName: approval.tool_name,
+ preview: approval.preview,
+ payload: approval.payload as Record<string, any>,
+ }}
+ />
+ </NotQuill>
))
}, [conversationId, message, pendingApprovalsData, resolvedApprovalStatuses])
@@ -588,6 +612,52 @@ const Message = React.memo(function Message({
const maybeCommand = MAX_SLASH_COMMANDS.find(
(cmd) => cmd.name === message.content.split(' ', 1)[0]
)
+ const contextSummary = message.ui_context && Object.keys(message.ui_context).length > 0 && (
+ <ContextSummary
+ insights={message.ui_context.insights}
+ dashboards={message.ui_context.dashboards}
+ events={message.ui_context.events}
+ actions={message.ui_context.actions}
+ notebooks={message.ui_context.notebooks}
+ useCurrentPageContext={false}
+ />
+ )
+ const humanContent = maybeCommand ? (
+ <div className="flex items-center">
+ <Tooltip
+ title={
+ <>
+ This is a PostHog AI command:
+ <br />
+ <i>{maybeCommand.description}</i>
+ </>
+ }
+ >
+ <span className="text-base mr-1.5">{maybeCommand.icon}</span>
+ </Tooltip>
+ <span className="font-mono">{message.content}</span>
+ </div>
+ ) : (
+ <MarkdownMessage content={message.content || '*No text.*'} id={message.id || 'no-text'} />
+ )
+
+ if (quill) {
+ return (
+ <MessageReveal key={key}>
+ <QuillHumanBubble
+ copyText={message.content || undefined}
+ before={contextSummary || undefined}
+ className={cn(
+ 'w-full',
+ message.status === 'error' &&
+ '[&_[data-slot=bubble-content]]:border-destructive-foreground'
+ )}
+ >
+ {humanContent}
+ </QuillHumanBubble>
+ </MessageReveal>
+ )
+ }
return (
<MessageTemplate
@@ -595,37 +665,8 @@ const Message = React.memo(function Message({
type="human"
boxClassName={message.status === 'error' ? 'border-danger' : undefined}
>
- {message.ui_context && Object.keys(message.ui_context).length > 0 && (
- <ContextSummary
- insights={message.ui_context.insights}
- dashboards={message.ui_context.dashboards}
- events={message.ui_context.events}
- actions={message.ui_context.actions}
- notebooks={message.ui_context.notebooks}
- useCurrentPageContext={false}
- />
- )}
- {maybeCommand ? (
- <div className="flex items-center">
- <Tooltip
- title={
- <>
- This is a PostHog AI command:
- <br />
- <i>{maybeCommand.description}</i>
- </>
- }
- >
- <span className="text-base mr-1.5">{maybeCommand.icon}</span>
- </Tooltip>
- <span className="font-mono">{message.content}</span>
- </div>
- ) : (
- <MarkdownMessage
- content={message.content || '*No text.*'}
- id={message.id || 'no-text'}
- />
- )}
+ {contextSummary}
+ {humanContent}
</MessageTemplate>
)
} else if (isAssistantMessage(message)) {
@@ -806,23 +847,26 @@ const Message = React.memo(function Message({
} else if (isArtifactMessage(message)) {
if (isVisualizationArtifactContent(message.content)) {
return (
- <VisualizationArtifact
- key={key}
- message={message}
- content={message.content}
- status={message.status}
- isEditingInsight={editInsightToolRegistered}
- activeSceneId={activeSceneId}
- />
+ // A chart card needs more room from the text around it than the thread's row gap gives.
+ <div key={key} className={quill ? 'my-2' : undefined}>
+ <VisualizationArtifact
+ message={message}
+ content={message.content}
+ status={message.status}
+ isEditingInsight={editInsightToolRegistered}
+ activeSceneId={activeSceneId}
+ />
+ </div>
)
} else if (isNotebookArtifactContent(message.content)) {
return (
- <NotebookArtifactAnswer
- key={key}
- content={message.content}
- status={message.status}
- artifactId={message.artifact_id}
- />
+ <NotQuill key={key} className="w-full">
+ <NotebookArtifactAnswer
+ content={message.content}
+ status={message.status}
+ artifactId={message.artifact_id}
+ />
+ </NotQuill>
)
}
return null
@@ -832,7 +876,7 @@ const Message = React.memo(function Message({
return null // We currently skip other types of messages
})()}
{isLastInGroup && message.status === 'error' && (
- <MessageTemplate type="ai" boxClassName="border-warning">
+ <AssistantNote boxClassName="border-warning">
<div className="flex items-center gap-1.5">
<IconWarning className="text-xl text-warning" />
<i>
@@ -840,7 +884,7 @@ const Message = React.memo(function Message({
failed.
</i>
</div>
- </MessageTemplate>
+ </AssistantNote>
)}
</div>
</MessageContainer>
@@ -854,6 +898,17 @@ function MessageGroupSkeleton({
groupType: 'human' | 'ai'
className?: string
}): JSX.Element {
+ const quill = useQuillThread()
+ if (quill) {
+ return (
+ <MessageContainer className={clsx('items-center', className)} groupType={groupType}>
+ <Skeleton
+ className={cn('h-10 w-3/5 rounded-lg', groupType === 'human' ? 'ml-auto' : 'mr-auto')}
+ aria-label="Loading messages"
+ />
+ </MessageContainer>
+ )
+ }
return (
<MessageContainer className={clsx('items-center', className)} groupType={groupType}>
<LemonSkeleton className="h-10 w-3/5 rounded-lg border" />
@@ -872,6 +927,7 @@ const TextAnswer = React.forwardRef<HTMLDivElement, TextAnswerProps>(function Te
{ message, interactable, isFinalGroup, withActions = true },
ref
) {
+ const quill = useQuillThread()
const retriable = !!(interactable && isFinalGroup)
const action = withActions
@@ -912,6 +968,26 @@ const TextAnswer = React.forwardRef<HTMLDivElement, TextAnswerProps>(function Te
)
}
+ if (quill) {
+ return (
+ <ChatMessage align="start" ref={ref} data-message-type="ai" className="w-full">
+ <ChatMessageContent className="gap-1">
+ <ChatBubble
+ variant="ghost"
+ className={cn(
+ message.status === 'error' && '[&_[data-slot=bubble-content]]:border-destructive-foreground'
+ )}
+ >
+ <ChatBubbleContent>
+ <QuillAssistantMarkdown content={message.content || ''} id={message.id || 'in-progress'} />
+ </ChatBubbleContent>
+ </ChatBubble>
+ {action}
+ </ChatMessageContent>
+ </ChatMessage>
+ )
+ }
+
return (
<MessageTemplate
type="ai"
@@ -924,132 +1000,6 @@ const TextAnswer = React.forwardRef<HTMLDivElement, TextAnswerProps>(function Te
)
})
-interface AssistantMessageFormProps {
- form: AssistantForm
- linksOnly?: boolean
-}
-
-function AssistantMessageForm({ form, linksOnly }: AssistantMessageFormProps): JSX.Element {
- const { askMax } = useActions(maxThreadLogic)
-
- const options = linksOnly ? form.options.filter((option) => option.href) : form.options
-
- return (
- // ml-1 is because buttons have radius of 0.375rem, while messages of 0.65rem, where diff = 0.25rem
- // Also makes it clear the form is subservient to the message. *Harmony*
- <div className="flex flex-wrap gap-1.5 ml-1 mt-1">
- {options.map((option) => (
- <LemonButton
- key={option.value}
- onClick={!option.href ? () => askMax(option.value) : undefined}
- to={option.href}
- size="small"
- targetBlank={!!option.href}
- type={
- option.variant && ['primary', 'secondary', 'tertiary'].includes(option.variant)
- ? (option.variant as LemonButtonPropsBase['type'])
- : 'secondary'
- }
- >
- {option.value}
- </LemonButton>
- ))}
- </div>
- )
-}
-
-interface PlanningAnswerProps {
- toolCall: EnhancedToolCall
- isLastPlanningMessage?: boolean
-}
-
-function PlanningAnswer({ toolCall, isLastPlanningMessage = true }: PlanningAnswerProps): JSX.Element {
- const [isExpanded, setIsExpanded] = useState(isLastPlanningMessage)
-
- useLayoutEffect(() => {
- setIsExpanded(isLastPlanningMessage)
- }, [isLastPlanningMessage])
-
- // Extract planning steps from tool call args
- // Assuming args has a 'todos' field with array of {content: string, status: string, activeForm: string}
- const steps: PlanningStep[] = Array.isArray(toolCall.args.todos)
- ? (
- toolCall.args.todos as Array<{
- content: string
- status: string
- activeForm: string
- }>
- ).map((todo) => ({
- description: todo.content,
- status: todo.status as PlanningStepStatus,
- }))
- : []
-
- const completedCount = steps.filter((step) => step.status === 'completed').length
- const totalCount = steps.length
- const hasMultipleSteps = steps.length > 1
-
- return (
- <div className="flex flex-col text-xs">
- <div
- className={clsx(
- 'flex items-center select-none',
- !hasMultipleSteps ? 'cursor-default' : 'cursor-pointer'
- )}
- onClick={!hasMultipleSteps ? undefined : () => setIsExpanded(!isExpanded)}
- aria-label={!hasMultipleSteps ? undefined : isExpanded ? 'Collapse plan' : 'Expand plan'}
- >
- <div className="flex items-center justify-center size-5">
- <IconNotebook />
- </div>
- <div className="flex items-center gap-1.5 flex-1 min-w-0">
- <span>Planning</span>
- <span className="text-muted">
- ({completedCount}/{totalCount})
- </span>
- {hasMultipleSteps && (
- <button className="cursor-pointer inline-flex items-center hover:opacity-70 transition-opacity flex-shrink-0">
- <span className={`transform transition-transform ${isExpanded ? 'rotate-90' : ''}`}>
- <IconChevronRight />
- </span>
- </button>
- )}
- </div>
- </div>
- {isExpanded && (
- <div className="mt-1.5 space-y-1.5 border-l-2 border-border-secondary pl-3.5 ml-2">
- {steps.map((step, index) => {
- const isCompleted = step.status === 'completed'
- const isInProgress = step.status === 'in_progress'
-
- return (
- <div key={index} className="flex items-start gap-2 animate-fade-in">
- <span className="flex-shrink-0">
- <LemonCheckbox checked={isCompleted} disabled size="xsmall" />
- </span>
- <span
- className={clsx(
- 'leading-relaxed',
- isCompleted && 'text-muted line-through',
- isInProgress && 'font-medium'
- )}
- >
- {step.description}
- {isInProgress && (
- <ShimmeringContent>
- <span className="text-muted ml-1">(in progress)</span>
- </ShimmeringContent>
- )}
- </span>
- </div>
- )
- })}
- </div>
- )}
- </div>
- )
-}
-
interface ToolCallsAnswerProps {
toolCalls: EnhancedToolCall[]
registeredToolMap: Record<string, ToolRegistration>
@@ -1104,368 +1054,6 @@ function ToolCallsAnswer({ toolCalls, registeredToolMap }: ToolCallsAnswerProps)
)
}
-const Visualization = React.memo(function Visualization({
- query,
- collapsed,
- editingChildren,
-}: {
- query: InsightVizNode | DataVisualizationNode
- collapsed?: boolean
- editingChildren?: React.ReactNode
-}): JSX.Element | null {
- const [isSummaryShown, setIsSummaryShown] = useState(false)
- const [isCollapsed, setIsCollapsed] = useState(collapsed ?? false)
-
- if (!query) {
- return null
- }
-
- return (
- <>
- {!isCollapsed && <Query query={query} readOnly embedded />}
- <div className={clsx('flex items-center justify-between', !isCollapsed && 'mt-2')}>
- <div className="flex items-center gap-1.5">
- <LemonButton
- sideIcon={isSummaryShown ? <IconCollapse /> : <IconExpand />}
- onClick={() => setIsSummaryShown(!isSummaryShown)}
- size="xsmall"
- className="-m-1 shrink"
- tooltip={isSummaryShown ? 'Hide definition' : 'Show definition'}
- >
- <h5 className="m-0 leading-none">
- <TopHeading query={query} />
- </h5>
- </LemonButton>
- </div>
- <div className="flex items-center gap-1.5">
- {editingChildren}
- <LemonButton
- icon={isCollapsed ? <IconEye /> : <IconHide />}
- onClick={() => setIsCollapsed(!isCollapsed)}
- size="xsmall"
- className="-m-1 shrink"
- tooltip={isCollapsed ? 'Show visualization' : 'Hide visualization'}
- />
- </div>
- </div>
- {isSummaryShown && !isDataVisualizationNode(query) && (
- <>
- <SeriesSummary query={query.source} heading={null} />
- {!isHogQLQuery(query.source) && (
- <div className="flex flex-wrap gap-4 mt-1 *:grow">
- <PropertiesSummary properties={query.source.properties} />
- <InsightBreakdownSummary query={query.source} />
- </div>
- )}
- </>
- )}
- </>
- )
-})
-
-interface MultiVisualizationAnswerProps {
- message: MultiVisualizationMessage
- className?: string
-}
-
-export function MultiVisualizationAnswer({ message, className }: MultiVisualizationAnswerProps): JSX.Element | null {
- const { visualizations } = message
- const insights = useMemo(() => {
- return visualizations
- .map((visualization, index) => {
- const query = visualizationTypeToQuery(visualization)
- if (query) {
- return {
- query,
- title: visualization.plan || `Insight #${index + 1}`,
- }
- }
- return null
- })
- .filter(Boolean) as Array<{
- query: InsightVizNode | DataVisualizationNode
- title: string
- }>
- }, [visualizations])
-
- const openModal = (): void => {
- LemonDialog.open({
- title: 'Insights',
- content: <MultiVisualizationModal insights={insights} />,
- primaryButton: null,
- width: '90%',
- maxWidth: 1400,
- })
- }
-
- if (visualizations.length === 0) {
- return null
- }
-
- // Render insights in a mosaic layout
- const renderMosaic = (): JSX.Element => {
- if (visualizations.length === 1) {
- // Single insight takes full width
- return (
- <div className="w-full relative">
- <Visualization query={insights[0].query} />
- </div>
- )
- }
- // Two or more insights, show in a grid layout
- // Currently, let's show a maximum of 4 insights inline with the following mapping
- // 2 insights: 50/50 split
- // 3 insights: 33/33/33 split
- // 4 insights: 25/25/25/25 split, sso basically 2x2 grid
- const insightsToShow = insights.slice(0, 4)
- const gridCols =
- insightsToShow.length === 2 ? 'grid-cols-2' : insightsToShow.length === 3 ? 'grid-cols-3' : 'grid-cols-2'
-
- return (
- <div className={`grid ${gridCols} gap-2`}>
- {insightsToShow.map((insight, index) => (
- <div key={index} className="relative min-h-[200px]">
- <Query query={insight.query} readOnly embedded />
- </div>
- ))}
- </div>
- )
- }
-
- return (
- <div className={clsx('flex flex-col gap-px w-full break-words', className)}>
- {/* Everything wrapped in a message bubble */}
- <div className="max-w-full border py-3 px-4 rounded-lg bg-surface-primary">
- <div className="space-y-2">
- <div className="w-full flex justify-between items-center">
- <h2 className="text-sm font-semibold text-secondary">
- {pluralize(visualizations.length, 'insight')} analyzed
- </h2>
-
- {visualizations.length > 1 && (
- <LemonButton
- icon={<IconExpand />}
- size="xsmall"
- type="tertiary"
- onClick={openModal}
- tooltip="View all insights in detail"
- >
- Expand
- </LemonButton>
- )}
- </div>
-
- {renderMosaic()}
-
- {message.commentary && <MarkdownMessage content={message.commentary} id="multi-viz-commentary" />}
- </div>
- </div>
- </div>
- )
-}
-
-// Modal for detailed view
-interface MultiVisualizationModalProps {
- insights: Array<{
- query: InsightVizNode | DataVisualizationNode
- title: string
- }>
-}
-
-function MultiVisualizationModal({ insights: messages }: MultiVisualizationModalProps): JSX.Element {
- const [selectedIndex, setSelectedIndex] = React.useState(0)
-
- return (
- <div className="flex">
- {/* Sidebar with visualization list */}
- <div className="w-64 border-r pr-4 overflow-y-auto">
- <h5 className="text-xs font-semibold text-muted mb-3">VISUALIZATIONS</h5>
- <div className="space-y-1">
- {messages.map((item, index) => (
- <button
- key={index}
- onClick={() => setSelectedIndex(index)}
- className={clsx(
- 'w-full text-left p-2 rounded transition-colors text-sm',
- selectedIndex === index
- ? 'bg-primary text-primary-inverted font-semibold'
- : 'hover:bg-surface-secondary'
- )}
- >
- {item.title}
- </button>
- ))}
- </div>
- </div>
-
- {/* Main content area */}
- <div className="flex-1 pl-4 overflow-auto">
- {messages[selectedIndex] && (
- <>
- <h4 className="text-base font-semibold mb-3">
- <TopHeading query={messages[selectedIndex].query} />
- </h4>
- <div className="min-h-80">
- <Query query={messages[selectedIndex].query} readOnly embedded />
- </div>
- </>
- )}
- </div>
- </div>
- )
-}
-
-function RetriableFailureActions(): JSX.Element {
- const { retryLastMessage } = useActions(maxThreadLogic)
-
- return (
- <LemonButton
- icon={<IconRefresh />}
- type="tertiary"
- size="xsmall"
- tooltip="Try again"
- onClick={() => retryLastMessage()}
- className="ml-1"
- >
- Try again
- </LemonButton>
- )
-}
-
-function SuccessActions({
- retriable,
- hideRatingAndRetry,
- content,
-}: {
- retriable: boolean
- hideRatingAndRetry?: boolean
- content?: string | null
-}): JSX.Element {
- const { traceId: logicTraceId } = useValues(maxThreadLogic)
- const { ratingForKey } = useValues(messageRatingsLogic)
- const { setRating } = useActions(messageRatingsLogic)
- const { retryLastMessage } = useActions(maxThreadLogic)
- const { user } = useValues(userLogic)
- const { isDev, preflight } = useValues(preflightLogic)
- const contextTraceId = useTraceId()
-
- // Use the context trace_id if available (for reloaded conversations), otherwise fall back to logic's traceId
- const traceId = contextTraceId || logicTraceId
-
- const rating = ratingForKey(traceId)
- const [feedback, setFeedback] = useState<string>('')
- const [feedbackInputStatus, setFeedbackInputStatus] = useState<'hidden' | 'pending' | 'submitted'>('hidden')
-
- function submitRating(newRating: 'good' | 'bad'): void {
- if (rating || !traceId) {
- return // Already rated
- }
- setRating({ key: traceId, rating: newRating })
- posthog.captureTraceMetric(traceId, 'quality', newRating)
- if (newRating === 'bad') {
- setFeedbackInputStatus('pending')
- }
- }
-
- function submitFeedback(): void {
- if (!feedback || !traceId) {
- return // Input is empty
- }
- posthog.captureTraceFeedback(traceId, feedback)
- setFeedbackInputStatus('submitted')
- }
-
- return (
- <>
- <div className="flex items-center ml-1">
- {content && (
- <LemonButton
- icon={<IconCopy />}
- type="tertiary"
- size="xsmall"
- tooltip="Copy answer"
- onClick={() => copyToClipboard(stripMarkdown(content))}
- />
- )}
- {!hideRatingAndRetry && rating !== 'bad' && (
- <LemonButton
- icon={rating === 'good' ? <IconThumbsUpFilled /> : <IconThumbsUp />}
- type="tertiary"
- size="xsmall"
- tooltip="Good answer"
- onClick={() => submitRating('good')}
- />
- )}
- {!hideRatingAndRetry && rating !== 'good' && (
- <LemonButton
- icon={rating === 'bad' ? <IconThumbsDownFilled /> : <IconThumbsDown />}
- type="tertiary"
- size="xsmall"
- tooltip="Bad answer"
- onClick={() => submitRating('bad')}
- />
- )}
- {!hideRatingAndRetry && retriable && (
- <LemonButton
- icon={<IconRefresh />}
- type="tertiary"
- size="xsmall"
- tooltip="Try again"
- onClick={() => retryLastMessage()}
- />
- )}
- {(user?.is_staff || isDev) && traceId && (
- <LemonButton
- to={`${preflight?.region === Region.EU ? 'https://us.posthog.com/project/2' : ''}${urls.aiObservabilityTrace(traceId)}`}
- icon={<IconEye />}
- type="tertiary"
- size="xsmall"
- tooltip="View trace in AI observability"
- />
- )}
- </div>
- {!hideRatingAndRetry && feedbackInputStatus !== 'hidden' && (
- <MessageTemplate type="ai">
- <div className="flex items-center gap-1">
- <h4 className="m-0 text-sm grow">
- {feedbackInputStatus === 'pending'
- ? 'What disappointed you about the answer?'
- : 'Thank you for your feedback!'}
- </h4>
- <LemonButton
- icon={<IconX />}
- type="tertiary"
- size="xsmall"
- onClick={() => {
- setFeedbackInputStatus('hidden')
- }}
- />
- </div>
- {feedbackInputStatus === 'pending' && (
- <div className="flex w-full gap-1.5 items-center mt-1.5">
- <LemonInput
- placeholder="Help us improve PostHog AI…"
- fullWidth
- value={feedback}
- onChange={(newValue) => setFeedback(newValue)}
- onPressEnter={() => submitFeedback()}
- autoFocus
- />
- <LemonButton
- type="primary"
- onClick={() => submitFeedback()}
- disabledReason={!feedback ? 'Please type a few words!' : undefined}
- >
- Submit
- </LemonButton>
- </div>
- )}
- </MessageTemplate>
- )}
- </>
- )
-}
-
function renderToolCallWidget(
widgetDef: ToolCallWidgetDef | null,
toolCallId: string,
diff --git a/frontend/src/scenes/max/__mocks__/quillComparison.mocks.ts b/frontend/src/scenes/max/__mocks__/quillComparison.mocks.ts
new file mode 100644
index 000000000000..0c93d847d6d5
--- /dev/null
+++ b/frontend/src/scenes/max/__mocks__/quillComparison.mocks.ts
@@ -0,0 +1,638 @@
+/**
+ * Invented data for the PostHog AI quill comparison story: one investigation told twice, once as the
+ * LangGraph conversation the legacy chat renders, once as the ACP log the sandbox runner renders.
+ * Nothing here comes from a real conversation.
+ */
+import { MOCK_DEFAULT_BASIC_USER } from 'lib/api.mock'
+
+import {
+ ArtifactContentType,
+ ArtifactSource,
+ AssistantMessageType,
+ type RootAssistantMessage,
+} from '~/queries/schema/schema-assistant-messages'
+import { NodeKind } from '~/queries/schema/schema-general'
+
+import {
+ OriginProduct,
+ type Task,
+ type TaskRun,
+ TaskRunEnvironment,
+ TaskRunStatus,
+} from 'products/posthog_ai/frontend/types/taskTypes'
+import type { StoredLogEntry } from 'products/posthog_ai/frontend/types/wireTypes'
+import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
+
+export const COMPARISON_PANEL_ID = 'quill-comparison'
+export const COMPARISON_CONVERSATION_ID = 'quill-comparison-conversation'
+export const COMPARISON_TASK_ID = '0199c0de-2222-7000-8000-00000000c0de'
+export const COMPARISON_RUN_ID = '0199c0de-3333-7000-8000-00000000c0de'
+
+const SIGNUP_FUNNEL_QUERY = {
+ kind: NodeKind.FunnelsQuery,
+ dateRange: { date_from: '-7d' },
+ series: [
+ { kind: NodeKind.EventsNode, event: 'landing page viewed', name: 'landing page viewed' },
+ { kind: NodeKind.EventsNode, event: 'signup form opened', name: 'signup form opened' },
+ { kind: NodeKind.EventsNode, event: 'email submitted', name: 'email submitted' },
+ { kind: NodeKind.EventsNode, event: 'account created', name: 'account created' },
+ ],
+ funnelsFilter: { funnelVizType: 'steps', layout: 'horizontal' },
+}
+
+const SIGNUPS_PER_DAY_QUERY = {
+ kind: NodeKind.TrendsQuery,
+ dateRange: { date_from: '-14d' },
+ interval: 'day',
+ series: [{ kind: NodeKind.EventsNode, event: 'account created', name: 'account created' }],
+}
+
+const SIGNUPS_BY_SOURCE_QUERY = {
+ kind: NodeKind.TrendsQuery,
+ dateRange: { date_from: '-14d' },
+ interval: 'day',
+ series: [{ kind: NodeKind.EventsNode, event: 'account created', name: 'account created' }],
+ breakdownFilter: { breakdown: 'utm_source', breakdown_type: 'event' },
+}
+
+const SIGNUPS_SQL = `SELECT
+ toDate(timestamp) AS day,
+ count() AS signups,
+ countIf(properties.$browser = 'Safari') AS safari_signups
+FROM events
+WHERE event = 'account created'
+ AND timestamp >= now() - INTERVAL 14 DAY
+GROUP BY day
+ORDER BY day`
+
+const SIGNUPS_TABLE = `| day | signups | safari_signups |
+| --- | ---: | ---: |
+| 2024-03-04 | 412 | 96 |
+| 2024-03-05 | 398 | 91 |
+| 2024-03-06 | 405 | 94 |
+| 2024-03-07 | 421 | 99 |
+| 2024-03-08 | 389 | 88 |
+| 2024-03-09 | 251 | 44 |
+| 2024-03-10 | 243 | 41 |
+| 2024-03-11 | 302 | 12 |
+| 2024-03-12 | 288 | 9 |
+| 2024-03-13 | 279 | 11 |
+| 2024-03-14 | 291 | 10 |
+| 2024-03-15 | 284 | 8 |`
+
+const FINDINGS_MARKDOWN = `Signups fell **27%** week over week, and nearly all of the loss sits at one step.
+
+### Funnel, this week vs last week
+
+| Step | Last week | This week | Change |
+| --- | ---: | ---: | ---: |
+| Landing page viewed | 18,420 | 18,105 | −1.7% |
+| Signup form opened | 6,210 | 6,088 | −2.0% |
+| Email submitted | 3,984 | 2,610 | **−34.5%** |
+| Account created | 2,803 | 2,044 | −27.1% |
+
+### What changed
+
+- The drop starts on **Monday the 11th**, the day the new email validation shipped.
+- Safari signups fell from ~95 a day to ~10 a day. Other browsers held steady.
+- The validation rejects addresses with a \`+\` sign, and Safari autofill inserts one for aliased addresses.
+
+\`\`\`sql
+${SIGNUPS_SQL}
+\`\`\`
+
+The funnel and the daily counts are below.`
+
+const ALERT_MARKDOWN = `Done. The alert **Daily signups below trend** now fires when the day's count is more than 20% under the trailing 7-day average.
+
+- Checks once a day at 09:00 in your project's timezone
+- Notifies the \`#growth\` channel through your Slack destination
+- Uses the \`account created\` event, so it tracks the same number as the funnel's last step`
+
+export function comparisonConversationMessages(): RootAssistantMessage[] {
+ return [
+ {
+ id: 'cmp-human-1',
+ type: AssistantMessageType.Human,
+ content:
+ 'Why did signups drop last week? Compare the signup funnel with the week before and tell me where people leave.',
+ trace_id: 'cmp-trace-1',
+ ui_context: {
+ dashboards: [{ id: 12, name: 'Growth overview', filters: {} }],
+ } as any,
+ },
+ {
+ id: 'cmp-ai-1',
+ type: AssistantMessageType.Assistant,
+ content: '',
+ meta: {
+ thinking: [
+ {
+ type: 'thinking',
+ thinking:
+ 'Compare the funnel week over week first. If one step moved much more than the others, look for a cause around that step: a release, a browser, a traffic source.',
+ },
+ ],
+ },
+ tool_calls: [
+ {
+ id: 'cmp-tool-plan',
+ type: 'tool_call',
+ name: 'todo_write',
+ args: {
+ todos: [
+ { content: 'Compare the signup funnel with the week before', status: 'completed' },
+ { content: 'Count signups per day and per browser', status: 'completed' },
+ { content: 'Match the drop against recent releases', status: 'completed' },
+ { content: 'Summarize the cause and suggest a fix', status: 'in_progress' },
+ ],
+ },
+ },
+ {
+ id: 'cmp-tool-funnel',
+ type: 'tool_call',
+ name: 'create_insight',
+ args: {
+ query_description: 'Signup funnel for the last 7 days compared with the 7 days before',
+ commentary: 'Comparing the signup funnel week over week',
+ },
+ },
+ {
+ id: 'cmp-tool-sql',
+ type: 'tool_call',
+ name: 'execute_sql',
+ args: { query: SIGNUPS_SQL, commentary: 'Counting signups per day and per browser' },
+ },
+ {
+ id: 'cmp-tool-search',
+ type: 'tool_call',
+ name: 'search',
+ args: {
+ kind: 'docs',
+ query: 'email validation release notes',
+ commentary: 'Checking recent releases',
+ },
+ },
+ ],
+ },
+ {
+ id: 'cmp-tool-plan-result',
+ type: AssistantMessageType.ToolCall,
+ tool_call_id: 'cmp-tool-plan',
+ content: 'Plan updated',
+ ui_payload: null,
+ },
+ {
+ id: 'cmp-tool-funnel-result',
+ type: AssistantMessageType.ToolCall,
+ tool_call_id: 'cmp-tool-funnel',
+ content: 'Created the insight "Signup funnel, this week vs last week"',
+ ui_payload: null,
+ },
+ {
+ id: 'cmp-artifact-funnel',
+ type: AssistantMessageType.Artifact,
+ artifact_id: 'cmp-funnel-artifact',
+ source: ArtifactSource.Artifact,
+ content: {
+ content_type: ArtifactContentType.Visualization,
+ query: SIGNUP_FUNNEL_QUERY as any,
+ name: 'Signup funnel, this week vs last week',
+ },
+ },
+ {
+ id: 'cmp-tool-sql-result',
+ type: AssistantMessageType.ToolCall,
+ tool_call_id: 'cmp-tool-sql',
+ content: SIGNUPS_TABLE,
+ ui_payload: { execute_sql: SIGNUPS_SQL },
+ },
+ {
+ id: 'cmp-tool-search-result',
+ type: AssistantMessageType.ToolCall,
+ tool_call_id: 'cmp-tool-search',
+ content:
+ 'Found 2 results: "Stricter email validation on signup" (changelog, 11 Mar) and "Signup form: autofill support" (docs).',
+ ui_payload: null,
+ },
+ {
+ id: 'cmp-ai-2',
+ type: AssistantMessageType.Assistant,
+ content: FINDINGS_MARKDOWN,
+ },
+ {
+ id: 'cmp-multi-viz',
+ type: AssistantMessageType.MultiVisualization,
+ visualizations: [
+ {
+ query: 'Signups per day',
+ plan: 'Signups per day, last 14 days',
+ answer: SIGNUPS_PER_DAY_QUERY as any,
+ },
+ {
+ query: 'Signups by source',
+ plan: 'Signups per day by traffic source',
+ answer: SIGNUPS_BY_SOURCE_QUERY as any,
+ },
+ ],
+ commentary:
+ 'Both charts bend on the 11th. Paid and organic sources fall by the same share, so the cause is on the form, not in acquisition.',
+ },
+ {
+ id: 'cmp-human-2',
+ type: AssistantMessageType.Human,
+ content: 'Set up an alert when daily signups fall more than 20% below the 7-day average.',
+ trace_id: 'cmp-trace-2',
+ },
+ {
+ id: 'cmp-failure-1',
+ type: AssistantMessageType.Failure,
+ content: 'PostHog AI could not reach the alerts service. Please try again.',
+ },
+ {
+ id: 'cmp-human-3',
+ type: AssistantMessageType.Human,
+ content: 'Set up an alert when daily signups fall more than 20% below the 7-day average.',
+ trace_id: 'cmp-trace-3',
+ },
+ {
+ id: 'cmp-ai-3',
+ type: AssistantMessageType.Assistant,
+ content: ALERT_MARKDOWN,
+ tool_calls: [
+ {
+ id: 'cmp-tool-alert',
+ type: 'tool_call',
+ name: 'create_insight',
+ args: {
+ query_description: 'Daily signups with a 7-day moving average',
+ commentary: 'Creating the alert on daily signups',
+ },
+ },
+ ],
+ meta: {
+ form: {
+ options: [
+ { value: 'Show me recordings of Safari users who left at the email step' },
+ { value: 'Also alert on activation drops' },
+ ],
+ },
+ },
+ },
+ {
+ id: 'cmp-tool-alert-result',
+ type: AssistantMessageType.ToolCall,
+ tool_call_id: 'cmp-tool-alert',
+ content: 'Created the alert "Daily signups below trend"',
+ ui_payload: null,
+ },
+ ] as RootAssistantMessage[]
+}
+
+export function comparisonConversation(): Record<string, unknown> {
+ return {
+ id: COMPARISON_CONVERSATION_ID,
+ status: 'idle',
+ title: 'Why did signups drop last week?',
+ agent_runtime: 'langgraph',
+ created_at: '2024-03-15T14:02:10.000000Z',
+ updated_at: '2024-03-15T14:06:40.000000Z',
+ user: MOCK_DEFAULT_BASIC_USER,
+ messages: comparisonConversationMessages(),
+ }
+}
+
+// --- Sandbox runtime -------------------------------------------------------------------------------------
+
+function notification(timestamp: string, method: string, params: Record<string, unknown>): StoredLogEntry {
+ return { type: 'notification', timestamp, notification: { method, params } }
+}
+
+function update(timestamp: string, sessionUpdate: Record<string, unknown>): StoredLogEntry {
+ return notification(timestamp, 'session/update', { update: sessionUpdate })
+}
+
+function userMessage(timestamp: string, text: string): StoredLogEntry {
+ return update(timestamp, { sessionUpdate: 'user_message_chunk', content: { type: 'text', text } })
+}
+
+function agentMessage(timestamp: string, messageId: string, text: string): StoredLogEntry {
+ return update(timestamp, { sessionUpdate: 'agent_message_chunk', messageId, content: { type: 'text', text } })
+}
+
+function agentThought(timestamp: string, text: string): StoredLogEntry {
+ return update(timestamp, { sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text } })
+}
+
+function toolCall(
+ timestamp: string,
+ id: string,
+ toolName: string,
+ title: string,
+ rawInput: Record<string, unknown>,
+ kind?: string
+): StoredLogEntry {
+ return update(timestamp, {
+ sessionUpdate: 'tool_call',
+ toolCallId: id,
+ title,
+ kind,
+ status: 'in_progress',
+ rawInput,
+ _meta: { claudeCode: { toolName } },
+ })
+}
+
+function posthogCall(timestamp: string, id: string, tool: string, args: object, context: string): StoredLogEntry {
+ return update(timestamp, {
+ sessionUpdate: 'tool_call',
+ toolCallId: id,
+ title: 'exec',
+ kind: 'other',
+ status: 'in_progress',
+ rawInput: { command: `call ${tool} ${JSON.stringify(args)}`, context },
+ _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },
+ })
+}
+
+function toolResult(timestamp: string, id: string, status: string, text: string, rawOutput?: unknown): StoredLogEntry {
+ return update(timestamp, {
+ sessionUpdate: 'tool_call_update',
+ toolCallId: id,
+ status,
+ content: [{ type: 'content', content: { type: 'text', text } }],
+ ...(rawOutput !== undefined ? { rawOutput } : {}),
+ })
+}
+
+export function comparisonRunLog(): StoredLogEntry[] {
+ return [
+ userMessage(
+ '2024-03-15T14:02:10Z',
+ 'Why did signups drop last week? Compare the signup funnel with the week before and tell me where people leave.'
+ ),
+ notification('2024-03-15T14:02:11Z', '_posthog/status', { status: 'sdk_initialization' }),
+ agentThought(
+ '2024-03-15T14:02:12Z',
+ 'Compare the funnel week over week first. If one step moved much more than the others, look for a cause around that step.'
+ ),
+ toolCall(
+ '2024-03-15T14:02:13Z',
+ 'cmp-run-plan',
+ 'TodoWrite',
+ 'Update plan',
+ {
+ todos: [
+ { content: 'Compare the signup funnel with the week before', status: 'completed' },
+ { content: 'Count signups per day and per browser', status: 'completed' },
+ { content: 'Match the drop against recent releases', status: 'completed' },
+ { content: 'Summarize the cause and suggest a fix', status: 'in_progress' },
+ ],
+ },
+ 'other'
+ ),
+ toolResult('2024-03-15T14:02:13Z', 'cmp-run-plan', 'completed', 'Plan updated'),
+ posthogCall(
+ '2024-03-15T14:02:17Z',
+ 'cmp-run-sql',
+ 'execute-sql',
+ { query: SIGNUPS_SQL },
+ 'Count signups per day and per browser'
+ ),
+ toolResult('2024-03-15T14:02:19Z', 'cmp-run-sql', 'completed', SIGNUPS_TABLE, {
+ query: { kind: NodeKind.HogQLQuery, query: SIGNUPS_SQL },
+ results: { columns: ['day', 'signups', 'safari_signups'] },
+ }),
+ toolCall(
+ '2024-03-15T14:02:20Z',
+ 'cmp-run-grep',
+ 'Grep',
+ 'Search the changelog for the email validation release',
+ { pattern: 'email validation', path: 'changelog/' },
+ 'search'
+ ),
+ toolResult(
+ '2024-03-15T14:02:21Z',
+ 'cmp-run-grep',
+ 'completed',
+ 'changelog/2024-03-11.md:3: Stricter email validation on signup'
+ ),
+ toolCall(
+ '2024-03-15T14:02:22Z',
+ 'cmp-run-read',
+ 'Read',
+ 'Read emailValidator.ts',
+ { file_path: 'frontend/src/signup/emailValidator.ts' },
+ 'read'
+ ),
+ toolResult(
+ '2024-03-15T14:02:23Z',
+ 'cmp-run-read',
+ 'completed',
+ 'export const EMAIL_PATTERN = /^[a-z0-9._-]+@[a-z0-9.-]+\\.[a-z]{2,}$/i'
+ ),
+ // The quill thread keeps only the last finished call of a run unfolded, so the chart goes last.
+ posthogCall(
+ '2024-03-15T14:02:24Z',
+ 'cmp-run-funnel',
+ 'query-funnel',
+ { series: SIGNUP_FUNNEL_QUERY.series, dateRange: SIGNUP_FUNNEL_QUERY.dateRange },
+ 'Compare the signup funnel week over week'
+ ),
+ toolResult('2024-03-15T14:02:26Z', 'cmp-run-funnel', 'completed', 'Funnel with 4 steps', {
+ query: SIGNUP_FUNNEL_QUERY,
+ _posthogUrl: '/project/1/insights/new',
+ }),
+ agentMessage('2024-03-15T14:02:30Z', 'cmp-run-findings', FINDINGS_MARKDOWN),
+ notification('2024-03-15T14:02:31Z', '_posthog/turn_complete', {}),
+ userMessage(
+ '2024-03-15T14:05:00Z',
+ 'Set up an alert when daily signups fall more than 20% below the 7-day average.'
+ ),
+ posthogCall(
+ '2024-03-15T14:05:02Z',
+ 'cmp-run-alert-failed',
+ 'alert-create',
+ { name: 'Daily signups below trend', threshold: { type: 'percentage', lower: -20 } },
+ 'Create the alert on daily signups'
+ ),
+ toolResult(
+ '2024-03-15T14:05:04Z',
+ 'cmp-run-alert-failed',
+ 'failed',
+ 'alerts service returned 503: temporarily unavailable'
+ ),
+ posthogCall(
+ '2024-03-15T14:05:05Z',
+ 'cmp-run-alert',
+ 'alert-create',
+ { name: 'Daily signups below trend', threshold: { type: 'percentage', lower: -20 } },
+ 'Retry creating the alert'
+ ),
+ toolResult('2024-03-15T14:05:07Z', 'cmp-run-alert', 'completed', 'Created alert "Daily signups below trend"', {
+ id: 'alert-42',
+ name: 'Daily signups below trend',
+ _posthogUrl: '/project/1/alerts/alert-42',
+ }),
+ agentMessage('2024-03-15T14:05:09Z', 'cmp-run-alert-answer', ALERT_MARKDOWN),
+ notification('2024-03-15T14:05:10Z', '_posthog/turn_complete', {}),
+ ]
+}
+
+export function comparisonRun(): TaskRun {
+ return {
+ id: COMPARISON_RUN_ID,
+ task: COMPARISON_TASK_ID,
+ stage: null,
+ branch: null,
+ status: TaskRunStatus.COMPLETED,
+ environment: TaskRunEnvironment.CLOUD,
+ runtime_adapter: null,
+ model: null,
+ reasoning_effort: null,
+ log_url: null,
+ error_message: null,
+ output: null,
+ task_summary: null,
+ task_tags: [],
+ state: {},
+ artifacts: [],
+ created_at: '2024-03-15T14:02:05Z',
+ updated_at: '2024-03-15T14:05:10Z',
+ completed_at: '2024-03-15T14:05:10Z',
+ }
+}
+
+export function comparisonTask(): Task {
+ return {
+ id: COMPARISON_TASK_ID,
+ task_number: 7,
+ slug: 'TASK-7',
+ title: 'Why did signups drop last week?',
+ description:
+ 'Why did signups drop last week? Compare the signup funnel with the week before and tell me where people leave.',
+ origin_product: OriginProduct.USER_CREATED,
+ runtime: TaskRuntimeEnumApi.Acp,
+ repository: null,
+ github_integration: null,
+ signal_report: null,
+ json_schema: null,
+ internal: false,
+ latest_run: comparisonRun(),
+ created_at: '2024-03-15T14:02:05Z',
+ updated_at: '2024-03-15T14:05:10Z',
+ created_by: {
+ id: MOCK_DEFAULT_BASIC_USER.id,
+ uuid: MOCK_DEFAULT_BASIC_USER.uuid,
+ distinct_id: MOCK_DEFAULT_BASIC_USER.distinct_id,
+ first_name: MOCK_DEFAULT_BASIC_USER.first_name,
+ email: MOCK_DEFAULT_BASIC_USER.email,
+ },
+ }
+}
+
+/** The JSONL body the `logs/` endpoint returns. */
+export function comparisonRunLogBody(): string {
+ return comparisonRunLog()
+ .map((entry) => JSON.stringify(entry))
+ .join('\n')
+}
+
+// --- Query API ---------------------------------------------------------------------------------------------
+
+const DAYS = Array.from({ length: 14 }, (_, index) => `2024-03-${String(2 + index).padStart(2, '0')}`)
+const SIGNUPS = [418, 402, 412, 398, 405, 421, 389, 251, 243, 302, 288, 279, 291, 284]
+
+function dayLabel(day: string): string {
+ const [, month, date] = day.split('-')
+ return `${Number(date)}-${month === '03' ? 'Mar' : month}-2024`
+}
+
+function trendSeries(label: string, data: number[], breakdownValue?: string): Record<string, unknown> {
+ return {
+ action: { id: 'account created', type: 'events', order: 0, name: 'account created', properties: {} },
+ label,
+ count: data.reduce((sum, value) => sum + value, 0),
+ data,
+ labels: DAYS.map(dayLabel),
+ days: DAYS,
+ ...(breakdownValue !== undefined ? { breakdown_value: breakdownValue } : {}),
+ }
+}
+
+function funnelStep(name: string, order: number, count: number): Record<string, unknown> {
+ return {
+ action_id: name,
+ name,
+ custom_name: null,
+ order,
+ people: [],
+ count,
+ type: 'events',
+ average_conversion_time: order === 0 ? null : 120 * order,
+ median_conversion_time: order === 0 ? null : 90 * order,
+ }
+}
+
+function sourceOf(query: Record<string, unknown>): Record<string, unknown> {
+ const source = query.source
+ return source && typeof source === 'object' ? (source as Record<string, unknown>) : query
+}
+
+/** The query API's answer for every query the comparison story runs; `null` for a query it does not know. */
+export function comparisonQueryResponse(query: Record<string, unknown>): Record<string, unknown> | null {
+ const source = sourceOf(query)
+ switch (source.kind) {
+ case NodeKind.FunnelsQuery:
+ return {
+ results: [
+ funnelStep('landing page viewed', 0, 18105),
+ funnelStep('signup form opened', 1, 6088),
+ funnelStep('email submitted', 2, 2610),
+ funnelStep('account created', 3, 2044),
+ ],
+ }
+ case NodeKind.TrendsQuery: {
+ const breakdown = source.breakdownFilter as { breakdown?: string } | undefined
+ if (breakdown?.breakdown) {
+ return {
+ results: [
+ trendSeries(
+ 'account created - organic',
+ SIGNUPS.map((value) => Math.round(value * 0.46)),
+ 'organic'
+ ),
+ trendSeries(
+ 'account created - paid',
+ SIGNUPS.map((value) => Math.round(value * 0.34)),
+ 'paid'
+ ),
+ trendSeries(
+ 'account created - referral',
+ SIGNUPS.map((value) => Math.round(value * 0.2)),
+ 'referral'
+ ),
+ ],
+ }
+ }
+ return { results: [trendSeries('account created', SIGNUPS)] }
+ }
+ case NodeKind.HogQLQuery:
+ return {
+ columns: ['day', 'signups', 'safari_signups'],
+ types: [
+ ['day', 'Date'],
+ ['signups', 'UInt64'],
+ ['safari_signups', 'UInt64'],
+ ],
+ results: DAYS.map((day, index) => [
+ day,
+ SIGNUPS[index],
+ index < 9 ? Math.round(SIGNUPS[index] * 0.23) : 10,
+ ]),
+ hogql: SIGNUPS_SQL,
+ }
+ default:
+ return null
+ }
+}
diff --git a/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx b/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx
index e645775a282d..0b4ecdb92132 100644
--- a/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx
+++ b/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx
@@ -56,19 +56,23 @@ export function LangGraphActivity({
))
: []
- const activityChildren = (
- <>
- {widget}
- {!!uiPayload?.summarize_website_interactions && result && (
- <UIPayloadAnswer
- toolCallId={result.tool_call_id}
- toolName="summarize_website_interactions"
- toolPayload={uiPayload.summarize_website_interactions}
- embedded
- />
- )}
- </>
- )
+ const summary =
+ !!uiPayload?.summarize_website_interactions && result ? (
+ <UIPayloadAnswer
+ toolCallId={result.tool_call_id}
+ toolName="summarize_website_interactions"
+ toolPayload={uiPayload.summarize_website_interactions}
+ embedded
+ />
+ ) : null
+ // Null, not an empty fragment, so the activity draws no empty widget slot under the title.
+ const activityChildren =
+ widget || summary ? (
+ <>
+ {widget}
+ {summary}
+ </>
+ ) : null
// The tool call's details — UI payload, SQL, args, and result — live behind the chevron and only
// surface once the call has produced a result. An in-flight call shows just the shimmering title,
diff --git a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
index 6dd0c7caf5e3..fb49acce5cd5 100644
--- a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
+++ b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
@@ -15,8 +15,9 @@ import { DROPDOWN_PARTS } from '~/layout/today/todayMenuParts'
import { TodayPanelMoveMenuItems } from '~/layout/today/TodayPanelMoveMenuItems'
import { todayShellLogic } from '~/layout/today/todayShellLogic'
+import { useThreadSkin } from 'products/posthog_ai/frontend/api/logics'
import { DebugLogsMenuItem } from 'products/posthog_ai/frontend/api/menus'
-import { DebugLogsMenu, useThreadSkin } from 'products/posthog_ai/frontend/api/primitives'
+import { DebugLogsMenu } from 'products/posthog_ai/frontend/api/primitives'
import { EmbeddedRunner } from 'products/posthog_ai/frontend/api/runner'
import { aiSceneView } from '../aiSceneView'
@@ -270,7 +271,7 @@ function ChatArea({ threadVisible, conversation, onStartNewConversation }: ChatA
</LemonBanner>
</div>
)}
- <Thread className="p-3" />
+ <Thread />
</ThreadAutoScroller>
)}
diff --git a/frontend/src/scenes/max/components/ModeSelector.tsx b/frontend/src/scenes/max/components/ModeSelector.tsx
index 10d02cff9c14..4a0f12da496c 100644
--- a/frontend/src/scenes/max/components/ModeSelector.tsx
+++ b/frontend/src/scenes/max/components/ModeSelector.tsx
@@ -22,7 +22,7 @@ import {
} from '../max-constants'
import { maxThreadLogic } from '../maxThreadLogic'
-type ModeValue = AgentMode | SpecialMode | null
+export type ModeValue = AgentMode | SpecialMode | null
function buildModeTooltip(description: string, tools: ToolDefinition[]): JSX.Element {
return (
@@ -118,53 +118,56 @@ interface GetModeOptionsParams {
hasExistingMessages: boolean
}
-function getModeOptions({
+/** One mode the selector offers, as plain data so each skin draws it its own way. */
+export interface ModeChoice {
+ value: ModeValue
+ name: string
+ description: string
+ icon: JSX.Element
+ beta?: boolean
+ alpha?: boolean
+ /** The tools the lemon tooltip lists; empty for research mode, which has no tool list. */
+ tools: ToolDefinition[]
+}
+
+export interface ModeChoiceSection {
+ options: ModeChoice[]
+}
+
+function getModeChoices({
planModeEnabled,
researchEnabled,
featureFlags,
hasExistingMessages,
-}: GetModeOptionsParams): LemonSelectSection<ModeValue>[] {
- const specialOptions = [
+}: GetModeOptionsParams): ModeChoiceSection[] {
+ const specialOptions: ModeChoice[] = [
{
- value: null as ModeValue,
- label: SPECIAL_MODES.auto.name as string | JSX.Element,
+ value: null,
+ name: SPECIAL_MODES.auto.name,
+ description: SPECIAL_MODES.auto.description,
icon: SPECIAL_MODES.auto.icon,
- tooltip: buildModeTooltip(SPECIAL_MODES.auto.description, getDefaultTools()),
+ tools: getDefaultTools(),
},
]
if (planModeEnabled) {
specialOptions.push({
- value: 'plan' as ModeValue,
- label: (
- <span className="flex items-center gap-1">
- {SPECIAL_MODES.plan.name}
- {SPECIAL_MODES.plan.beta && (
- <LemonTag size="small" type="warning">
- BETA
- </LemonTag>
- )}
- </span>
- ),
+ value: 'plan',
+ name: SPECIAL_MODES.plan.name,
+ description: SPECIAL_MODES.plan.description,
icon: SPECIAL_MODES.plan.icon,
- tooltip: buildModeTooltip(SPECIAL_MODES.plan.description, getDefaultTools()),
+ beta: SPECIAL_MODES.plan.beta,
+ tools: getDefaultTools(),
})
}
if (researchEnabled && !hasExistingMessages) {
specialOptions.push({
- value: 'research' as ModeValue,
- label: (
- <span className="flex items-center gap-1">
- {SPECIAL_MODES.research.name}
- {SPECIAL_MODES.research.beta && (
- <LemonTag size="small" type="warning">
- BETA
- </LemonTag>
- )}
- </span>
- ),
+ value: 'research',
+ name: SPECIAL_MODES.research.name,
+ description: SPECIAL_MODES.research.description,
icon: SPECIAL_MODES.research.icon,
- tooltip: <div>{SPECIAL_MODES.research.description}</div>,
+ beta: SPECIAL_MODES.research.beta,
+ tools: [],
})
}
@@ -180,32 +183,62 @@ function getModeOptions({
{
options: modeEntries.map(([mode, def]) => ({
value: mode as AgentMode,
- label:
- def.beta || def.alpha ? (
- <span className="flex items-center gap-1">
- {def.name}
- {def.beta && (
- <LemonTag size="small" type="warning">
- BETA
- </LemonTag>
- )}
- {def.alpha && (
- <LemonTag size="small" type="danger">
- ALPHA
- </LemonTag>
- )}
- </span>
- ) : (
- def.name
- ),
+ name: def.name,
+ description: def.description,
icon: def.icon,
- tooltip: buildModeTooltip(def.description, getToolsForMode(mode as AgentMode)),
+ beta: def.beta,
+ alpha: def.alpha,
+ tools: getToolsForMode(mode as AgentMode),
})),
},
]
}
-export function ModeSelector(): JSX.Element | null {
+function toLemonSelectSections(sections: ModeChoiceSection[]): LemonSelectSection<ModeValue>[] {
+ return sections.map((section) => ({
+ options: section.options.map((choice) => ({
+ value: choice.value,
+ label:
+ choice.beta || choice.alpha ? (
+ <span className="flex items-center gap-1">
+ {choice.name}
+ {choice.beta && (
+ <LemonTag size="small" type="warning">
+ BETA
+ </LemonTag>
+ )}
+ {choice.alpha && (
+ <LemonTag size="small" type="danger">
+ ALPHA
+ </LemonTag>
+ )}
+ </span>
+ ) : (
+ choice.name
+ ),
+ icon: choice.icon,
+ tooltip:
+ choice.value === 'research' ? (
+ <div>{choice.description}</div>
+ ) : (
+ buildModeTooltip(choice.description, choice.tools)
+ ),
+ })),
+ }))
+}
+
+export interface ModeSelectorController {
+ value: ModeValue
+ sections: ModeChoiceSection[]
+ disabledReason: string | undefined
+ onChange: (value: ModeValue) => void
+}
+
+/**
+ * The mode selector's state, shared by its lemon and quill skins: which modes are offered, which is
+ * selected, why the control may be disabled, and the change handler with its telemetry.
+ */
+export function useModeSelector(): ModeSelectorController {
const { agentMode, contextDisabledReason, conversation, threadMessageCount } = useValues(maxThreadLogic)
const { setAgentMode } = useActions(maxThreadLogic)
const { featureFlags } = useValues(featureFlagLogic)
@@ -213,9 +246,9 @@ export function ModeSelector(): JSX.Element | null {
const planModeEnabled = useFeatureFlag('PHAI_PLAN_MODE')
const hasExistingMessages = threadMessageCount > 0
- const modeOptions = useMemo(
+ const sections = useMemo(
() =>
- getModeOptions({
+ getModeChoices({
planModeEnabled,
researchEnabled,
featureFlags,
@@ -224,7 +257,7 @@ export function ModeSelector(): JSX.Element | null {
[planModeEnabled, researchEnabled, featureFlags, hasExistingMessages]
)
- const handleChange = useCallback(
+ const onChange = useCallback(
(value: ModeValue): void => {
posthog.capture('phai mode switched', {
previous_mode: agentMode,
@@ -237,18 +270,28 @@ export function ModeSelector(): JSX.Element | null {
const isDeepResearch = conversation?.type === ConversationType.DeepResearch
+ return {
+ value: isDeepResearch ? 'research' : agentMode,
+ sections,
+ disabledReason: isDeepResearch
+ ? "You're in research mode, start a new conversation to change mode"
+ : contextDisabledReason,
+ onChange,
+ }
+}
+
+export function ModeSelector(): JSX.Element | null {
+ const { value, sections, disabledReason, onChange } = useModeSelector()
+ const modeOptions = useMemo(() => toLemonSelectSections(sections), [sections])
+
return (
<LemonSelect
- value={isDeepResearch ? 'research' : agentMode}
- onChange={handleChange}
+ value={value}
+ onChange={onChange}
options={modeOptions}
size="xxsmall"
type="tertiary"
- disabledReason={
- isDeepResearch
- ? "You're in research mode, start a new conversation to change mode"
- : contextDisabledReason
- }
+ disabledReason={disabledReason}
tooltip={buildGeneralTooltip(
'Select a mode to focus PostHog AI on a specific product or task. Each mode unlocks specialized capabilities, tools, and expertise.',
getDefaultTools()
diff --git a/frontend/src/scenes/max/components/QuestionInput.test.tsx b/frontend/src/scenes/max/components/QuestionInput.test.tsx
index b7767bb4007f..1b322ec42f1b 100644
--- a/frontend/src/scenes/max/components/QuestionInput.test.tsx
+++ b/frontend/src/scenes/max/components/QuestionInput.test.tsx
@@ -18,6 +18,7 @@ import { maxLogic } from '../maxLogic'
import { maxThreadLogic } from '../maxThreadLogic'
import { maxMocks } from '../testUtils'
import { QuestionInput } from './QuestionInput'
+import { QuillQuestionInput } from './QuillQuestionInput'
jest.mock(
'@posthog/hogvm',
@@ -28,7 +29,11 @@ jest.mock(
{ virtual: true }
)
-describe('QuestionInput', () => {
+// Both skins share `useQuestionInput`, so the same behavior holds whichever one the flags pick.
+describe.each([
+ ['lemon', QuestionInput],
+ ['quill', QuillQuestionInput],
+])('QuestionInput (%s)', (_skin, Composer) => {
let maxLogicInstance: ReturnType<typeof maxLogic.build>
let threadLogicInstance: ReturnType<typeof maxThreadLogic.build>
@@ -51,7 +56,7 @@ describe('QuestionInput', () => {
<Provider>
<BindLogic logic={maxLogic} props={{ panelId: 'test' }}>
<BindLogic logic={maxThreadLogic} props={threadProps}>
- <QuestionInput />
+ <Composer />
</BindLogic>
</BindLogic>
</Provider>
@@ -71,9 +76,12 @@ describe('QuestionInput', () => {
const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
it('offers file selection before the first message and preserves the current draft', async () => {
- expect(screen.queryByText('Attach', { exact: true })).not.toBeInTheDocument()
+ // The flag outlives the previous skin's run of this test, so start from flags off.
+ act(() => featureFlagLogic.actions.setFeatureFlags([], {}))
+ const attachButton = (): Element | null => document.querySelector('[data-attr="max-new-chat-attach-file"]')
+ expect(attachButton()).not.toBeInTheDocument()
act(() => featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true }))
- expect(screen.getByText('Attach', { exact: true })).toBeInTheDocument()
+ expect(attachButton()).toBeInTheDocument()
const file = new File(['demo'], 'notes.txt', { type: 'text/plain' })
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Read these notes' } })
const fileInput = document.querySelector('[data-attr="max-new-chat-attach-input"]') as HTMLInputElement
diff --git a/frontend/src/scenes/max/components/QuestionInput.tsx b/frontend/src/scenes/max/components/QuestionInput.tsx
index 86cdfe45f849..150539dde050 100644
--- a/frontend/src/scenes/max/components/QuestionInput.tsx
+++ b/frontend/src/scenes/max/components/QuestionInput.tsx
@@ -1,10 +1,8 @@
import './QuestionInput.scss'
import { offset } from '@floating-ui/react'
-import { useActions, useValues } from 'kea'
-import posthog from 'posthog-js'
-import React, { ReactNode, useEffect, useMemo, useRef, useState } from 'react'
-import { useDebouncedCallback } from 'use-debounce'
+import { useActions } from 'kea'
+import React, { ReactNode, useEffect, useRef, useState } from 'react'
import { IconArrowRight, IconCheck, IconPencil, IconStopFilled, IconTrash, IconUpload, IconX } from '@posthog/icons'
import { LemonButton, LemonSwitch, LemonTextArea, Spinner } from '@posthog/lemon-ui'
@@ -12,25 +10,19 @@ import { LemonButton, LemonSwitch, LemonTextArea, Spinner } from '@posthog/lemon
import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcut'
import { cn } from 'lib/utils/css-classes'
import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
-import { userLogic } from 'scenes/userLogic'
-
-import { AgentMode } from '~/queries/schema/schema-assistant-messages'
-import { ConversationQueueMessage } from '~/types'
import { ContextDisplay } from '../Context'
-import { MAX_MESSAGE_LENGTH, MESSAGE_TOO_LONG, messageLength } from '../max-constants'
-import { maxGlobalLogic } from '../maxGlobalLogic'
-import { maxLogic } from '../maxLogic'
import { maxThreadLogic } from '../maxThreadLogic'
-import { MAX_SLASH_COMMANDS } from '../slash-commands'
+import {
+ QUEUED_MESSAGES_HEADING,
+ RESEARCH_BETA_NOTICE,
+ SUPPORT_OVERRIDE_LABEL,
+ SUPPORT_SESSION_NOTICE,
+ composerPlaceholder,
+} from './composerCopy'
import { FillInHint } from './FillInHint'
import { SlashCommandAutocomplete } from './SlashCommandAutocomplete'
-
-/**
- * Show the character counter only once the message gets close to the limit. A permanent counter
- * under every composer would be noise: almost every message is a couple of hundred characters.
- */
-const LENGTH_COUNTER_THRESHOLD = MAX_MESSAGE_LENGTH * 0.9
+import { type QueuedMessageEditProps, useQuestionInput } from './useQuestionInput'
interface QuestionInputProps {
isSticky?: boolean
@@ -45,19 +37,7 @@ interface QuestionInputProps {
onSubmit?: () => void
}
-function QueuedMessageItem({
- message,
- isEditing,
- onEdit,
- onCancel,
- onSave,
-}: {
- message: ConversationQueueMessage
- isEditing: boolean
- onEdit: () => void
- onCancel: () => void
- onSave: (messageId: string, content: string) => void
-}): JSX.Element {
+function QueuedMessageItem({ message, isEditing, onEdit, onCancel, onSave }: QueuedMessageEditProps): JSX.Element {
const { deleteQueuedMessage } = useActions(maxThreadLogic)
const [draft, setDraft] = useState(message.content)
const textAreaRef = useRef<HTMLTextAreaElement | null>(null)
@@ -148,153 +128,57 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
},
ref
) {
- const { dataProcessingAccepted, isPhaiSandboxFlagOn } = useValues(maxGlobalLogic)
- const { question, fillInHint, typingSuggestion } = useValues(maxLogic)
- const { setQuestion, setFillInHint, cancelSuggestionTyping, attachFilesToNewChat } = useActions(maxLogic)
- const { user } = useValues(userLogic)
const {
+ inputValue,
+ handleQuestionChange,
+ hasQuestion,
+ fillInHint,
+ showFillInHint,
+ promptLength,
+ isOverLengthLimit,
+ maxMessageLength,
conversation,
threadLoading,
inputDisabled,
- contextDisabledReason,
- queueDisabledReason,
isSharedThread,
- cancelLoading,
- pendingPrompt,
- isImpersonatingExistingConversation,
- supportOverrideEnabled,
streamingActive,
- agentMode,
- threadMessageCount,
+ pendingPrompt,
+ dataProcessingAccepted,
+ showResearchBanner,
+ showAttachButton,
+ attachmentInputRef,
+ handleAttachmentChange,
queueingEnabled,
queuedMessages,
+ displayQueuedMessages,
queueSubmitting,
- } = useValues(maxThreadLogic)
- const {
- askMax,
- stopGeneration,
+ editingQueueId,
+ setEditingQueueId,
+ saveQueuedMessage,
+ isQueueingSubmission,
+ showStopButton,
+ disabledReason,
+ slashCommandIcon,
+ submit,
+ handleSendClick,
+ handlePressEnter,
+ handleKeyDown,
+ handleBlur,
completeThreadGeneration,
+ showAutocomplete,
+ closeAutocomplete,
+ isImpersonatedInternalConversation,
+ isImpersonatingExistingConversation,
+ supportOverrideEnabled,
setSupportOverrideEnabled,
- updateQueuedMessage,
- releaseSandboxPrewarm,
- } = useActions(maxThreadLogic)
- // Show info banner for conversations created during impersonation (marked as internal)
- const isImpersonatedInternalConversation = user?.is_impersonated && conversation?.is_internal
-
- const [showAutocomplete, setShowAutocomplete] = useState(false)
- // Tracks an explicit dismissal (e.g. Esc) so the popover stays closed while the
- // user keeps typing a message that still starts with "/". "/" + Esc is a valid path.
- const [autocompleteDismissed, setAutocompleteDismissed] = useState(false)
- const [editingQueueId, setEditingQueueId] = useState<string | null>(null)
- const displayQueuedMessages = useMemo(() => [...queuedMessages].reverse(), [queuedMessages])
-
- // Hold the textarea value in local state so each keystroke is an isolated, cheap re-render
- // rather than a global kea dispatch. Binding the input directly to kea made every keystroke
- // notify every store subscriber, so input lag grew with conversation length (more mounted
- // messages = more subscriptions to sweep). kea remains the source of truth for submit, slash
- // commands, and draft persistence — we sync to it on a debounce, immediately for slash
- // commands so the autocomplete stays responsive, and on submit/blur.
- const attachmentInputRef = useRef<HTMLInputElement>(null)
- const [inputValue, setInputValue] = useState(question)
- const debouncedSetQuestion = useDebouncedCallback((value: string) => setQuestion(value), 150)
-
- // Flush any pending debounce when the component unmounts so that a draft typed just
- // before programmatic navigation (no blur event) is still persisted to kea.
- useEffect(() => {
- return () => debouncedSetQuestion.flush()
- }, [debouncedSetQuestion])
-
- // Mirror external question changes (draft restore, slash command insertion, clear on submit)
- // back into local state. Writing the same value is a no-op, so the debounced sync below
- // doesn't cause an extra render.
- useEffect(() => {
- setInputValue(question)
- }, [question])
-
- const handleQuestionChange = (value: string): void => {
- setInputValue(value)
- // The user typing their own text ends the fill-in cue.
- if (fillInHint) {
- setFillInHint(null)
- }
- if (value.startsWith('/')) {
- // Slash commands drive the autocomplete off kea's `question`, so sync immediately.
- debouncedSetQuestion.cancel()
- setQuestion(value)
- } else {
- debouncedSetQuestion(value)
- }
- }
-
- const submit = (prompt: string): void => {
- // askMax reads the prompt arg directly and clears `question` afterwards, so drop any
- // pending debounce to stop it from re-populating the just-sent text.
- debouncedSetQuestion.cancel()
- // A suggestion is still typing itself in. The user picked that suggestion, so send all of
- // it rather than the prefix that happens to be on screen, and stop the animation writing
- // the rest into the composer after the message has gone.
- const content = typingSuggestion ?? prompt
- if (typingSuggestion) {
- cancelSuggestionTyping()
- }
- if (fillInHint) {
- setFillInHint(null)
- }
- askMax(content)
- }
-
- // Counting code points is O(n), so only pay for it near the limit. A string's UTF-16 length is
- // never below its code point count, so a shorter one can't be over the limit.
- const promptLength = useMemo(
- () => (inputValue.length >= LENGTH_COUNTER_THRESHOLD ? messageLength(inputValue) : null),
- [inputValue]
- )
- const isOverLengthLimit = promptLength !== null && promptLength > MAX_MESSAGE_LENGTH
-
- const hasQuestion = inputValue.trim().length > 0
- // A fill-in suggestion typed its prefix in and is waiting for the user to complete it.
- const showFillInHint = !!fillInHint
- const isQueueingSubmission = queueingEnabled && threadLoading && hasQuestion
- const showStopButton = threadLoading && !isQueueingSubmission && !cancelLoading
-
- // Mirrors maxThreadLogic's `submissionDisabledReason` selector, but using the local input
- // value so the submit guard stays correct while the debounced sync to kea is still pending.
- const submissionDisabledReason = contextDisabledReason
- ? contextDisabledReason
- : !inputValue
- ? 'I need some input first'
- : isOverLengthLimit
- ? MESSAGE_TOO_LONG
- : queueDisabledReason
-
- // Update autocomplete visibility when the input changes
- useEffect(() => {
- const isSlashCommand = inputValue[0] === '/'
- // Once the input is no longer a slash command, clear any prior dismissal so
- // typing "/" again later reopens the popover.
- if (!isSlashCommand && autocompleteDismissed) {
- setAutocompleteDismissed(false)
- }
- const shouldShow = isSlashCommand && !autocompleteDismissed
- if (shouldShow && !showAutocomplete) {
- posthog.capture('Max slash command autocomplete shown')
- }
- setShowAutocomplete(shouldShow)
- }, [inputValue, showAutocomplete, autocompleteDismissed])
-
- let disabledReason = submissionDisabledReason
- if (threadLoading && !isQueueingSubmission) {
- disabledReason = undefined
- }
- if (cancelLoading) {
- disabledReason = 'Cancelling...'
- }
-
- useEffect(() => {
- if (!streamingActive && textAreaRef?.current) {
- textAreaRef.current.focus()
- }
- }, [streamingActive]) // oxlint-disable-line react-hooks/exhaustive-deps
+ } = useQuestionInput({ textAreaRef, onSubmit })
+ const placeholderCopy = composerPlaceholder({
+ conversation,
+ isSharedThread,
+ threadLoading,
+ isThreadVisible,
+ placeholder,
+ })
return (
<div
@@ -315,15 +199,15 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
{/* Have to increase z-index to overlay ToolsDisplay */}
<div className="relative w-full flex flex-col z-1">
{children}
- {agentMode === AgentMode.Research && threadMessageCount === 0 && (
+ {showResearchBanner && (
<div className="flex justify-center items-center gap-1 w-full px-2 py-1.5 mb-2 bg-warning/10 text-primary text-xs rounded-lg border-primary">
- Research mode is a free beta feature with lower daily limits
+ {RESEARCH_BETA_NOTICE}
</div>
)}
{queueingEnabled && (queuedMessages.length > 0 || queueSubmitting) && (
<div className="px-3 py-2">
<div className="text-xs text-muted mb-1.5 flex items-center gap-1.5">
- Up next
+ {QUEUED_MESSAGES_HEADING}
{queueSubmitting && <Spinner size="small" />}
</div>
<div className="space-y-1.5">
@@ -338,10 +222,7 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
onCancel={() => {
setEditingQueueId(null)
}}
- onSave={(messageId, content) => {
- updateQueuedMessage(messageId, content)
- setEditingQueueId(null)
- }}
+ onSave={saveQueuedMessage}
/>
))}
</div>
@@ -358,46 +239,29 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
!streamingActive && '[--input-ring-color:var(--color-ai)]'
)}
>
- <SlashCommandAutocomplete
- visible={showAutocomplete}
- onClose={() => {
- setShowAutocomplete(false)
- setAutocompleteDismissed(true)
- }}
- >
+ <SlashCommandAutocomplete visible={showAutocomplete} onClose={closeAutocomplete}>
<div className="relative w-full">
{!inputValue && (
<div
id="textarea-hint"
className="text-secondary absolute top-4 left-4 text-sm pointer-events-none"
>
- {conversation && isSharedThread ? (
- `This thread was shared with you by ${conversation.user.first_name} ${conversation.user.last_name}`
- ) : threadLoading ? (
- 'Thinking…'
- ) : isThreadVisible ? (
- placeholder || (
- <>
- Ask follow-up{' '}
- <span className="text-tertiary opacity-80 contrast-more:opacity-100">
- or / for commands
- </span>
- </>
- )
- ) : (
+ {placeholderCopy.kind === 'prompt' ? (
<>
- Ask a question{' '}
+ {placeholderCopy.lead}{' '}
<span className="text-tertiary opacity-80 contrast-more:opacity-100">
- or / for commands
+ {placeholderCopy.hint}
</span>
</>
+ ) : (
+ placeholderCopy.text
)}
</div>
)}
{/* Postfix cue after a fill-in suggestion's typed-in prefix. */}
{showFillInHint && (
<div className="absolute top-4 left-4 right-4 overflow-hidden pointer-events-none">
- <FillInHint text={inputValue} hint={fillInHint} />
+ <FillInHint text={inputValue} hint={fillInHint ?? ''} />
</div>
)}
<LemonTextArea
@@ -407,54 +271,9 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
ref={textAreaRef}
value={isSharedThread ? '' : inputValue}
onChange={handleQuestionChange}
- onBlur={(e) => {
- debouncedSetQuestion.flush()
- // Release any sandbox pre-warm when the user leaves the
- // input without sending. No-op on LangGraph / unwarmed
- // conversations.
- //
- // But clicking the send button blurs the textarea *before*
- // its onClick fires the send — releasing here would cancel
- // the very warm Run the send is about to consume. When focus
- // moves to the send button, skip the release and let the send
- // path consume the warm (it does so without a DELETE).
- const next = e.relatedTarget as HTMLElement | null
- if (next?.closest('[data-attr="max-send-message"]')) {
- return
- }
- releaseSandboxPrewarm()
- }}
- onPressEnter={() => {
- if (
- hasQuestion &&
- !submissionDisabledReason &&
- (!threadLoading || queueingEnabled)
- ) {
- onSubmit?.()
- submit(inputValue)
- }
- }}
- onKeyDown={(event) => {
- if (
- event.key === 'ArrowUp' &&
- !inputValue.trim() &&
- queuedMessages.length > 0 &&
- !editingQueueId
- ) {
- const target = event.currentTarget
- const atStart = target.selectionStart === 0 && target.selectionEnd === 0
- const isSingleLine = target.value.split('\n').length <= 1
- if (!atStart || !isSingleLine) {
- return
- }
- const nextMessageId = queuedMessages[0]?.id
- if (!nextMessageId) {
- return
- }
- event.preventDefault()
- setEditingQueueId(nextMessageId)
- }
- }}
+ onBlur={handleBlur}
+ onPressEnter={handlePressEnter}
+ onKeyDown={handleKeyDown}
disabled={inputDisabled}
minRows={1}
maxRows={10}
@@ -477,7 +296,7 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
<div className="flex-1 min-w-0">
<ContextDisplay size={contextDisplaySize} />
</div>
- {isPhaiSandboxFlagOn && !conversation && (
+ {showAttachButton && (
<div className="shrink-0">
<input
ref={attachmentInputRef}
@@ -485,11 +304,7 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
multiple
className="hidden"
data-attr="max-new-chat-attach-input"
- onChange={(event) => {
- const files = Array.from(event.target.files ?? [])
- event.target.value = ''
- attachFilesToNewChat(files, inputValue)
- }}
+ onChange={handleAttachmentChange}
/>
<LemonButton
size="xxsmall"
@@ -518,7 +333,7 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
isOverLengthLimit ? 'text-error' : 'text-secondary'
)}
>
- {promptLength.toLocaleString()} / {MAX_MESSAGE_LENGTH.toLocaleString()}
+ {promptLength.toLocaleString()} / {maxMessageLength.toLocaleString()}
</div>
)}
</div>
@@ -547,25 +362,7 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
<LemonButton
data-attr={showStopButton ? 'max-stop-generation' : 'max-send-message'}
type={(isThreadVisible && !hasQuestion) || showStopButton ? 'secondary' : 'primary'}
- onClick={() => {
- if (threadLoading) {
- if (isQueueingSubmission) {
- if (submissionDisabledReason) {
- textAreaRef?.current?.focus()
- return
- }
- submit(inputValue)
- return
- }
- stopGeneration()
- return
- }
- if (submissionDisabledReason) {
- textAreaRef?.current?.focus()
- return
- }
- submit(inputValue)
- }}
+ onClick={handleSendClick}
tooltip={
// If there's a disabled reason tooltip shown below, don't show a tooltip here
// Else, show the tooltip based on the button state
@@ -587,14 +384,7 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
disabledReason={disabledReason}
className={disabledReason ? 'opacity-[0.5]' : ''}
size="small"
- icon={
- showStopButton ? (
- <IconStopFilled />
- ) : (
- MAX_SLASH_COMMANDS.find((cmd) => cmd.name === inputValue.split(' ', 1)[0])
- ?.icon || <IconArrowRight />
- )
- }
+ icon={showStopButton ? <IconStopFilled /> : slashCommandIcon || <IconArrowRight />}
/>
</AIConsentPopoverWrapper>
</div>
@@ -602,7 +392,7 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
{/* Info banner for conversations created during impersonation (marked as internal) */}
{isImpersonatedInternalConversation && (
<div className="flex justify-start items-center gap-1 w-full px-2 py-1 bg-bg-light text-muted text-xs rounded-b-lg">
- Support agent session — this conversation won't be visible to the customer
+ {SUPPORT_SESSION_NOTICE}
</div>
)}
{/* Override checkbox - shown when impersonating and viewing existing customer conversation (not internal) */}
@@ -610,7 +400,7 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputProps
<div className="flex justify-start gap-1 w-full p-1 bg-warning-highlight rounded-b-lg">
<LemonSwitch
checked={supportOverrideEnabled}
- label="I understand this will add to the customer's conversation"
+ label={SUPPORT_OVERRIDE_LABEL}
onChange={(checked: boolean) => setSupportOverrideEnabled(checked)}
size="xxsmall"
tooltip="Support agents should create new conversations instead of using existing ones. Check this to override."
diff --git a/frontend/src/scenes/max/components/QuillContextPicker.tsx b/frontend/src/scenes/max/components/QuillContextPicker.tsx
new file mode 100644
index 000000000000..e61f41699703
--- /dev/null
+++ b/frontend/src/scenes/max/components/QuillContextPicker.tsx
@@ -0,0 +1,71 @@
+import { useActions, useValues } from 'kea'
+import { useId, useState } from 'react'
+
+import { IconAtSign } from '@posthog/icons'
+import { Button, Popover, PopoverContent, PopoverTrigger } from '@posthog/quill'
+
+import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'
+
+import { maxContextLogic } from '../maxContextLogic'
+import { maxThreadLogic } from '../maxThreadLogic'
+
+/**
+ * The legacy chat's context picker in the quill composer: the same taxonomic filter as the lemon
+ * `TaxonomicPopover`, in a quill popover with a quill trigger, bound to `maxContextLogic`.
+ */
+export function QuillContextPicker(): JSX.Element {
+ const [open, setOpen] = useState(false)
+ const filterKey = `posthog-ai-legacy-context-picker-${useId()}`
+ const { contextDisabledReason } = useValues(maxThreadLogic)
+ const { hasData, contextOptions, taxonomicGroupTypes, mainTaxonomicGroupType, toolContextItems } =
+ useValues(maxContextLogic)
+ const { handleTaxonomicFilterChange, openContextPicker } = useActions(maxContextLogic)
+ const showLabel = !hasData && toolContextItems.length === 0
+
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ if (next) {
+ openContextPicker()
+ }
+ setOpen(next)
+ }}
+ >
+ <PopoverTrigger
+ render={
+ <Button
+ variant="default"
+ size={showLabel ? 'sm' : 'icon-sm'}
+ aria-label="Add context"
+ tooltip="Add context to help PostHog AI answer your question"
+ disabledReason={contextDisabledReason}
+ data-attr="max-context-picker"
+ >
+ <IconAtSign />
+ {showLabel && <span className="@max-[480px]/composer:hidden">Add context</span>}
+ </Button>
+ }
+ />
+ <PopoverContent side="top" align="start" className="w-auto p-0">
+ {/* The filter is Lemon, so it keeps Lemon's colors inside the quill popover. */}
+ <div data-not-quill>
+ <TaxonomicFilter
+ taxonomicFilterLogicKey={filterKey}
+ groupType={mainTaxonomicGroupType}
+ taxonomicGroupTypes={taxonomicGroupTypes}
+ maxContextOptions={contextOptions}
+ onChange={({ type }, value, item) => {
+ if (value !== null) {
+ handleTaxonomicFilterChange(value, type, item)
+ }
+ setOpen(false)
+ }}
+ onClose={() => setOpen(false)}
+ width={450}
+ />
+ </div>
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/frontend/src/scenes/max/components/QuillModeSelector.tsx b/frontend/src/scenes/max/components/QuillModeSelector.tsx
new file mode 100644
index 000000000000..99d23d1a7935
--- /dev/null
+++ b/frontend/src/scenes/max/components/QuillModeSelector.tsx
@@ -0,0 +1,87 @@
+import { useState } from 'react'
+
+import {
+ Badge,
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ MenuLabel,
+} from '@posthog/quill'
+
+import { type ModeChoice, type ModeValue, useModeSelector } from './ModeSelector'
+
+const AUTO_MODE_KEY = '__auto__'
+
+function toMenuValue(value: ModeValue): string {
+ return value ?? AUTO_MODE_KEY
+}
+
+function fromMenuValue(value: string): ModeValue {
+ return value === AUTO_MODE_KEY ? null : (value as ModeValue)
+}
+
+/**
+ * The legacy chat's agent mode selector in the quill composer: the same choices as the lemon
+ * `ModeSelector`, as a quill dropdown of radio rows; each row's tooltip carries the mode's description.
+ */
+export function QuillModeSelector(): JSX.Element {
+ const [open, setOpen] = useState(false)
+ const { value, sections, disabledReason, onChange } = useModeSelector()
+ const choices = sections.flatMap((section) => section.options)
+ const selected: ModeChoice | undefined = choices.find((choice) => choice.value === value) ?? choices[0]
+
+ return (
+ <DropdownMenu open={open} onOpenChange={setOpen}>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ type="button"
+ variant="default"
+ size="sm"
+ aria-label="Mode"
+ tooltip="Select a mode to focus PostHog AI on a specific product or task."
+ disabledReason={disabledReason}
+ data-attr="max-mode-selector"
+ >
+ {selected?.icon}
+ <span className="@max-[400px]/composer:max-w-20 truncate">{selected?.name ?? 'Mode'}</span>
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="start" side="top" sideOffset={6} className="min-w-[220px]">
+ <MenuLabel>Mode</MenuLabel>
+ <DropdownMenuRadioGroup
+ value={toMenuValue(value)}
+ // Applied on pick, not after the menu closes, so a message sent during the close runs in the new mode.
+ onValueChange={(next) => {
+ onChange(fromMenuValue(next))
+ setOpen(false)
+ }}
+ >
+ {sections.map((section, index) => (
+ <div key={index}>
+ {index > 0 && <DropdownMenuSeparator />}
+ {section.options.map((choice) => (
+ <DropdownMenuRadioItem
+ key={toMenuValue(choice.value)}
+ value={toMenuValue(choice.value)}
+ tooltip={choice.description}
+ data-attr={`max-mode-${toMenuValue(choice.value)}`}
+ >
+ {choice.icon}
+ <span className="whitespace-nowrap">{choice.name}</span>
+ {choice.beta && <Badge variant="warning">Beta</Badge>}
+ {choice.alpha && <Badge variant="destructive">Alpha</Badge>}
+ </DropdownMenuRadioItem>
+ ))}
+ </div>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
diff --git a/frontend/src/scenes/max/components/QuillQuestionInput.tsx b/frontend/src/scenes/max/components/QuillQuestionInput.tsx
new file mode 100644
index 000000000000..fd2b2969828e
--- /dev/null
+++ b/frontend/src/scenes/max/components/QuillQuestionInput.tsx
@@ -0,0 +1,415 @@
+import { offset } from '@floating-ui/react'
+import { BindLogic, useActions, useValues } from 'kea'
+import React, { ReactNode, useEffect, useRef, useState } from 'react'
+
+import { IconArrowRight, IconCheck, IconPencil, IconPlus, IconStopFilled, IconTrash, IconX } from '@posthog/icons'
+import { LemonTextArea } from '@posthog/lemon-ui'
+import { Button, Spinner, Switch, Text } from '@posthog/quill'
+
+import { cn } from 'lib/utils/css-classes'
+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
+
+import { QuillComposerLayout } from 'products/posthog_ai/frontend/api/composer'
+
+import { ContextTags, ContextToolInfoTags, SandboxContextTags } from '../Context'
+import { maxThreadLogic } from '../maxThreadLogic'
+import { posthogAiContextLogic } from '../posthogAiContextLogic'
+import {
+ QUEUED_MESSAGES_HEADING,
+ RESEARCH_BETA_NOTICE,
+ SUPPORT_OVERRIDE_LABEL,
+ SUPPORT_SESSION_NOTICE,
+ composerPlaceholder,
+} from './composerCopy'
+import { FillInHint } from './FillInHint'
+import { QuillContextPicker } from './QuillContextPicker'
+import { QuillModeSelector } from './QuillModeSelector'
+import { SlashCommandAutocomplete } from './SlashCommandAutocomplete'
+import { type QueuedMessageEditProps, useQuestionInput } from './useQuestionInput'
+
+interface QuillQuestionInputProps {
+ isSticky?: boolean
+ placeholder?: string
+ children?: ReactNode
+ isThreadVisible?: boolean
+ textAreaRef?: React.RefObject<HTMLTextAreaElement>
+ containerClassName?: string
+ onSubmit?: () => void
+}
+
+function QuillQueuedMessageItem({ message, isEditing, onEdit, onCancel, onSave }: QueuedMessageEditProps): JSX.Element {
+ const { deleteQueuedMessage } = useActions(maxThreadLogic)
+ const [draft, setDraft] = useState(message.content)
+ const textAreaRef = useRef<HTMLTextAreaElement | null>(null)
+
+ useEffect(() => {
+ setDraft(message.content)
+ }, [message.content])
+
+ useEffect(() => {
+ if (isEditing) {
+ textAreaRef.current?.focus()
+ textAreaRef.current?.select()
+ }
+ }, [isEditing])
+
+ const canSave = draft.trim().length > 0
+
+ if (isEditing) {
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonTextArea
+ ref={textAreaRef}
+ value={draft}
+ onChange={setDraft}
+ minRows={1}
+ maxRows={4}
+ autoFocus
+ onPressCmdEnter={() => {
+ if (!canSave) {
+ return
+ }
+ onSave(message.id, draft)
+ }}
+ />
+ <div className="flex gap-1">
+ <Button
+ size="sm"
+ variant="primary"
+ onClick={() => onSave(message.id, draft)}
+ disabledReason={canSave ? undefined : 'Message cannot be empty'}
+ >
+ <IconCheck />
+ Save
+ </Button>
+ <Button size="sm" variant="outline" onClick={onCancel}>
+ <IconX />
+ Cancel
+ </Button>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="group flex items-center gap-2 rounded-md px-2 py-1 hover:bg-fill-hover">
+ <Text size="xs" variant="muted" className="m-0 flex-1 truncate">
+ {message.content}
+ </Text>
+ <div className="flex gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">
+ <Button
+ size="icon-xs"
+ variant="default"
+ aria-label="Edit message"
+ tooltip="Edit message"
+ onClick={onEdit}
+ >
+ <IconPencil />
+ </Button>
+ <Button
+ size="icon-xs"
+ variant="default"
+ aria-label="Remove from queue"
+ tooltip="Remove from queue"
+ onClick={() => deleteQueuedMessage(message.id)}
+ >
+ <IconTrash />
+ </Button>
+ </div>
+ </div>
+ )
+}
+
+/** The context chips of the legacy composer, as the lemon composer draws them; the pickers moved to the quill controls row. */
+function QuillContextChips(): JSX.Element | null {
+ const { showContextUI, conversation, sandboxConversationKey } = useValues(maxThreadLogic)
+ if (!showContextUI) {
+ return null
+ }
+ if (conversation?.agent_runtime === 'sandbox') {
+ return sandboxConversationKey ? (
+ <BindLogic logic={posthogAiContextLogic} props={{ conversationId: sandboxConversationKey }}>
+ <SandboxContextTags />
+ </BindLogic>
+ ) : null
+ }
+ return (
+ <>
+ <ContextToolInfoTags />
+ <ContextTags />
+ </>
+ )
+}
+
+/**
+ * The legacy PostHog AI composer in the quill skin, drawn like the sandbox runner's composer: one bordered
+ * input group with an inline send button and a controls row beneath. Behavior comes from `useQuestionInput`,
+ * which the lemon `QuestionInput` shares.
+ */
+export const QuillQuestionInput = React.forwardRef<HTMLDivElement, QuillQuestionInputProps>(function QuillQuestionInput(
+ { isSticky, placeholder, children, isThreadVisible, textAreaRef, containerClassName, onSubmit },
+ ref
+) {
+ const groupRef = useRef<HTMLDivElement>(null)
+ const internalTextAreaRef = useRef<HTMLTextAreaElement>(null)
+ const resolvedTextAreaRef = textAreaRef ?? internalTextAreaRef
+ const { showContextUI } = useValues(maxThreadLogic)
+ const {
+ inputValue,
+ handleQuestionChange,
+ fillInHint,
+ showFillInHint,
+ promptLength,
+ isOverLengthLimit,
+ maxMessageLength,
+ conversation,
+ threadLoading,
+ inputDisabled,
+ isSharedThread,
+ pendingPrompt,
+ dataProcessingAccepted,
+ showResearchBanner,
+ showAttachButton,
+ attachmentInputRef,
+ handleAttachmentChange,
+ queueingEnabled,
+ displayQueuedMessages,
+ queuedMessages,
+ queueSubmitting,
+ editingQueueId,
+ setEditingQueueId,
+ saveQueuedMessage,
+ isQueueingSubmission,
+ showStopButton,
+ disabledReason,
+ slashCommandIcon,
+ submit,
+ handleSendClick,
+ handlePressEnter,
+ handleKeyDown,
+ handleBlur,
+ completeThreadGeneration,
+ showAutocomplete,
+ closeAutocomplete,
+ isImpersonatedInternalConversation,
+ isImpersonatingExistingConversation,
+ supportOverrideEnabled,
+ setSupportOverrideEnabled,
+ } = useQuestionInput({ textAreaRef: resolvedTextAreaRef, onSubmit })
+
+ const placeholderCopy = composerPlaceholder({
+ conversation,
+ isSharedThread,
+ threadLoading,
+ isThreadVisible,
+ placeholder,
+ })
+ const placeholderText =
+ placeholderCopy.kind === 'prompt' ? `${placeholderCopy.lead}, ${placeholderCopy.hint}` : placeholderCopy.text
+
+ const sendLabel = showStopButton ? 'Stop' : isQueueingSubmission ? 'Queue message' : 'Send message'
+ const sendButton = showStopButton ? (
+ <Button
+ type="button"
+ variant="destructive"
+ size="icon"
+ aria-label="Stop"
+ tooltip={disabledReason ?? 'Stop'}
+ onClick={handleSendClick}
+ data-attr="max-stop-generation"
+ >
+ <IconStopFilled />
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ variant="primary"
+ size="icon"
+ // Looks disabled like the sandbox send button, but stays clickable (see below).
+ className={cn('rounded-xs', disabledReason && 'opacity-50')}
+ aria-label={sendLabel}
+ tooltip={disabledReason ?? sendLabel}
+ loading={threadLoading && !dataProcessingAccepted}
+ // The button stays clickable while disabled: the click puts focus back in the field.
+ aria-disabled={!!disabledReason}
+ onClick={handleSendClick}
+ data-attr="max-send-message"
+ >
+ {slashCommandIcon ?? <IconArrowRight className="-rotate-90" />}
+ </Button>
+ )
+
+ return (
+ <div
+ ref={ref}
+ data-quill
+ className={cn(
+ 'w-full px-3',
+ (isSticky || isThreadVisible) && 'sticky bottom-0 z-10 max-w-180 self-center',
+ // containerClassName last so callers can override (e.g. sidePanel's px-0).
+ containerClassName
+ )}
+ >
+ <div className="relative z-1 flex w-full flex-col gap-2">
+ {children}
+ {showResearchBanner && (
+ <Text
+ size="xs"
+ className="m-0 rounded-lg bg-warning px-2 py-1.5 text-center text-warning-foreground"
+ >
+ {RESEARCH_BETA_NOTICE}
+ </Text>
+ )}
+ {queueingEnabled && (queuedMessages.length > 0 || queueSubmitting) && (
+ <div className="flex flex-col gap-1 px-1">
+ <Text size="xs" variant="muted" className="m-0 flex items-center gap-1.5">
+ {QUEUED_MESSAGES_HEADING}
+ {queueSubmitting && <Spinner />}
+ </Text>
+ {displayQueuedMessages.map((message) => (
+ <QuillQueuedMessageItem
+ key={message.id}
+ message={message}
+ isEditing={editingQueueId === message.id}
+ onEdit={() => setEditingQueueId(message.id)}
+ onCancel={() => setEditingQueueId(null)}
+ onSave={saveQueuedMessage}
+ />
+ ))}
+ </div>
+ )}
+ <SlashCommandAutocomplete visible={showAutocomplete} onClose={closeAutocomplete}>
+ <div className="w-full">
+ <QuillComposerLayout
+ groupRef={groupRef}
+ textAreaRef={resolvedTextAreaRef}
+ // No wrapper element, so the chip row stays empty and hides itself when there are no chips.
+ chips={!isSharedThread && showContextUI ? <QuillContextChips /> : undefined}
+ field={
+ <>
+ {!inputValue && (
+ <div
+ data-slot="composer-placeholder"
+ id="question-input-hint"
+ className="pointer-events-none absolute text-sm text-muted-foreground"
+ >
+ {placeholderText}
+ </div>
+ )}
+ {/* Postfix cue after a fill-in suggestion's typed-in prefix. */}
+ {showFillInHint && fillInHint && (
+ <div className="pointer-events-none absolute inset-x-0 top-2 overflow-hidden">
+ <FillInHint text={inputValue} hint={fillInHint} />
+ </div>
+ )}
+ <LemonTextArea
+ aria-describedby={!inputValue ? 'question-input-hint' : undefined}
+ id="question-input"
+ data-attr="max-chat-input"
+ ref={resolvedTextAreaRef}
+ value={isSharedThread ? '' : inputValue}
+ onChange={handleQuestionChange}
+ onBlur={handleBlur}
+ onPressEnter={handlePressEnter}
+ onKeyDown={handleKeyDown}
+ disabled={inputDisabled}
+ minRows={1}
+ maxRows={10}
+ className={cn(
+ '!border-none !bg-transparent py-2 pl-2 resize-none',
+ // Hide the native caret so only the enlarged fill-in caret shows.
+ showFillInHint && 'caret-transparent'
+ )}
+ hideFocus
+ />
+ </>
+ }
+ send={
+ isSharedThread ? (
+ <></>
+ ) : (
+ <AIConsentPopoverWrapper
+ placement="bottom-end"
+ showArrow
+ ignoreDismissal
+ onApprove={() => submit(pendingPrompt || inputValue)}
+ onDismiss={() => completeThreadGeneration()}
+ middleware={[
+ offset((state) => ({
+ mainAxis: state.placement.includes('top') ? 30 : 1,
+ })),
+ ]}
+ hidden={!threadLoading && !pendingPrompt}
+ >
+ {/* The consent popover anchors to a plain element, as the sandbox send button does. */}
+ <span className="flex">{sendButton}</span>
+ </AIConsentPopoverWrapper>
+ )
+ }
+ controls={
+ !isSharedThread && showContextUI ? (
+ <>
+ {showAttachButton && (
+ <>
+ <input
+ ref={attachmentInputRef}
+ type="file"
+ multiple
+ className="hidden"
+ data-attr="max-new-chat-attach-input"
+ onChange={handleAttachmentChange}
+ />
+ <Button
+ size="icon-sm"
+ variant="default"
+ aria-label="Attach files"
+ tooltip="Attach files in new PostHog AI. Your draft moves with you."
+ onClick={() => attachmentInputRef.current?.click()}
+ data-attr="max-new-chat-attach-file"
+ >
+ <IconPlus />
+ </Button>
+ </>
+ )}
+ <QuillContextPicker />
+ <QuillModeSelector />
+ </>
+ ) : undefined
+ }
+ meta={
+ promptLength !== null ? (
+ <Text
+ size="xs"
+ variant={isOverLengthLimit ? 'destructive' : 'muted'}
+ className="m-0"
+ >
+ {promptLength.toLocaleString()} / {maxMessageLength.toLocaleString()}
+ </Text>
+ ) : undefined
+ }
+ />
+ </div>
+ </SlashCommandAutocomplete>
+ {/* Info banner for conversations created during impersonation (marked as internal) */}
+ {isImpersonatedInternalConversation && (
+ <Text size="xs" variant="muted" className="m-0 px-2">
+ {SUPPORT_SESSION_NOTICE}
+ </Text>
+ )}
+ {/* Override switch - shown when impersonating and viewing an existing customer conversation (not internal) */}
+ {!conversation?.is_internal && (isImpersonatingExistingConversation || supportOverrideEnabled) && (
+ <label className="flex items-center gap-2 rounded-lg bg-warning px-2 py-1 text-warning-foreground">
+ <Switch
+ checked={supportOverrideEnabled}
+ onCheckedChange={(checked: boolean) => setSupportOverrideEnabled(checked)}
+ aria-label={SUPPORT_OVERRIDE_LABEL}
+ />
+ <Text size="xs" className="m-0">
+ {SUPPORT_OVERRIDE_LABEL}
+ </Text>
+ </label>
+ )}
+ </div>
+ </div>
+ )
+})
diff --git a/frontend/src/scenes/max/components/QuillTopicBadges.tsx b/frontend/src/scenes/max/components/QuillTopicBadges.tsx
new file mode 100644
index 000000000000..37ab65be1ff0
--- /dev/null
+++ b/frontend/src/scenes/max/components/QuillTopicBadges.tsx
@@ -0,0 +1,109 @@
+import { IconCode } from '@posthog/icons'
+import { Badge, Button, Card, CardGroup, Text, cn } from '@posthog/quill'
+
+import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
+import { FileSystemIconType } from '~/queries/schema/schema-general'
+
+import { SelfDrivingIntroModal } from 'products/signals/frontend/inbox/components/onboarding/SelfDrivingIntroModal'
+
+import { SuggestionTopic } from '../suggestionTopics'
+import { COLORFUL_ICONS, type TopicBadgesProps, type TopicSuggestionsProps } from './TopicBadges'
+import { useCodeBadge } from './useCodeBadge'
+
+function badgeIcon(topic: SuggestionTopic): JSX.Element {
+ return topic.icon ?? iconForType(topic.iconType)
+}
+
+// pinned: the `capability-*` data-attr values below predate the topic naming and are frozen;
+// autocapture dashboards depend on them, so the rename stops at code symbols.
+
+/** The topic badge row in the quill skin: outline buttons that press in when selected. */
+export function QuillTopicBadges({ topics, selectedKey, onSelect, className }: TopicBadgesProps): JSX.Element | null {
+ const codeBadge = useCodeBadge()
+
+ if (!topics.length) {
+ return null
+ }
+
+ return (
+ <div
+ data-quill
+ className={cn(
+ 'flex flex-wrap items-center justify-center gap-1.5 max-w-[500px] px-3 pt-[2px]',
+ COLORFUL_ICONS,
+ className
+ )}
+ >
+ {topics.map((topic) => (
+ <Button
+ key={topic.key}
+ size="sm"
+ variant="outline"
+ className={cn(selectedKey === topic.key && 'bg-fill-selected')}
+ aria-pressed={selectedKey === topic.key}
+ onClick={() => onSelect(selectedKey === topic.key ? null : topic.key)}
+ data-attr={`capability-badge-${topic.key}`}
+ >
+ {badgeIcon(topic)}
+ {topic.label}
+ </Button>
+ ))}
+
+ {codeBadge.visible && (
+ <>
+ <Button size="sm" variant="outline" onClick={codeBadge.openIntro} data-attr="capability-badge-code">
+ <IconCode />
+ {codeBadge.label}
+ <Badge variant="warning">Beta</Badge>
+ </Button>
+
+ <SelfDrivingIntroModal isOpen={codeBadge.introOpen} onClose={codeBadge.closeIntro} />
+ </>
+ )}
+ </div>
+ )
+}
+
+/** The suggestion rows for a selected topic in the quill skin: one card per suggestion, each a full-width button. */
+export function QuillTopicSuggestions({ topic, onRun, className }: TopicSuggestionsProps): JSX.Element {
+ const isDocs = topic.variant === 'docs'
+ return (
+ <CardGroup
+ size="sm"
+ data-quill
+ className={cn('w-full px-3', COLORFUL_ICONS, className)}
+ data-attr="capability-suggestions"
+ >
+ {topic.suggestions.map((suggestion) => {
+ const iconType: FileSystemIconType = suggestion.iconType ?? topic.iconType
+ return (
+ <Card key={suggestion.content} size="sm" className="p-0">
+ <button
+ type="button"
+ className="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-fill-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={() => onRun(suggestion)}
+ data-attr={`capability-suggestion-${topic.key}`}
+ >
+ {!isDocs && <span className="flex shrink-0 text-base">{iconForType(iconType)}</span>}
+ <span className="flex min-w-0 flex-col leading-tight">
+ <Text
+ size="sm"
+ weight={isDocs ? 'normal' : 'semibold'}
+ className="m-0 truncate"
+ render={<span />}
+ >
+ {isDocs ? suggestion.content : (suggestion.title ?? suggestion.content)}
+ </Text>
+ {!isDocs && suggestion.description && (
+ <Text size="xs" variant="muted" className="m-0 truncate" render={<span />}>
+ {suggestion.description}
+ </Text>
+ )}
+ </span>
+ </button>
+ </Card>
+ )
+ })}
+ </CardGroup>
+ )
+}
diff --git a/frontend/src/scenes/max/components/SidebarQuestionInput.tsx b/frontend/src/scenes/max/components/SidebarQuestionInput.tsx
index a97ebdc2d75c..c7968339d539 100644
--- a/frontend/src/scenes/max/components/SidebarQuestionInput.tsx
+++ b/frontend/src/scenes/max/components/SidebarQuestionInput.tsx
@@ -10,12 +10,14 @@ import { LemonButton } from '@posthog/lemon-ui'
import { useAnimatedPresence } from 'lib/hooks/useAnimatedPresence'
import { cn } from 'lib/utils/css-classes'
+import { useThreadSkin } from 'products/posthog_ai/frontend/api/logics'
import { isPiTaskRuntime } from 'products/posthog_ai/frontend/types/taskTypes'
import { SuggestionGroup, maxLogic } from '../maxLogic'
import { maxThreadLogic } from '../maxThreadLogic'
import { InputFormArea, SandboxModeBadge } from './InputFormArea'
import { QuestionInput } from './QuestionInput'
+import { QuillQuestionInput } from './QuillQuestionInput'
export function SidebarQuestionInput({
isSticky = false,
@@ -25,6 +27,7 @@ export function SidebarQuestionInput({
sidePanel?: boolean
}): JSX.Element | null {
const { focusCounter, threadVisible } = useValues(maxLogic)
+ const skin = useThreadSkin()
// Use raw state values instead of selector to ensure re-renders on state changes
const {
@@ -73,6 +76,18 @@ export function SidebarQuestionInput({
// Show form area directly when there's a pending form/approval (even if showInput is false)
if (activeMultiQuestionForm || hasApprovalToShow || hasSandboxPermissionToShow) {
+ if (skin === 'quill') {
+ return (
+ <div
+ data-quill
+ className="w-full max-w-180 self-center px-3 mx-auto bg-[var(--background)]/50 backdrop-blur-sm"
+ >
+ <div className="rounded-lg border border-border bg-card">
+ <InputFormArea />
+ </div>
+ </div>
+ )
+ }
return (
<div className="w-full max-w-180 self-center px-3 mx-auto bg-[var(--scene-layout-background)]/50 backdrop-blur-sm">
<div className="border border-primary rounded-lg bg-surface-primary">
@@ -82,6 +97,20 @@ export function SidebarQuestionInput({
)
}
+ if (skin === 'quill') {
+ return (
+ <QuillQuestionInput
+ isSticky={isSticky}
+ textAreaRef={textAreaRef}
+ containerClassName={cn('mx-auto self-center backdrop-blur-sm z-50', sidePanel && 'px-0')}
+ isThreadVisible={threadVisible}
+ >
+ <SandboxModeBadge />
+ <SuggestionsList />
+ </QuillQuestionInput>
+ )
+ }
+
return (
<QuestionInput
isSticky={isSticky}
diff --git a/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx b/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx
index 78cfe92a2c8b..efb1d289f699 100644
--- a/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx
+++ b/frontend/src/scenes/max/components/SidebarQuestionInputWithSuggestions.tsx
@@ -4,6 +4,7 @@ import { useState } from 'react'
import { IconGear } from '@posthog/icons'
import { LemonButton, LemonModal } from '@posthog/lemon-ui'
+import { Text } from '@posthog/quill'
import { cn } from 'lib/utils/css-classes'
import { MaxMemorySettings } from 'scenes/settings/environment/MaxMemorySettings'
@@ -11,10 +12,13 @@ import { maxSettingsLogic } from 'scenes/settings/environment/maxSettingsLogic'
import { AgentMode } from '~/queries/schema/schema-assistant-messages'
+import { useThreadSkin } from 'products/posthog_ai/frontend/api/logics'
+
import { QUESTION_SUGGESTIONS_DATA, RESEARCH_SUGGESTIONS_DATA, maxLogic } from '../maxLogic'
import { maxThreadLogic } from '../maxThreadLogic'
import { HOMEPAGE_SUGGESTION_TOPICS } from '../suggestionTopics'
import { FloatingSuggestionsDisplay } from './FloatingSuggestionsDisplay'
+import { QuillTopicBadges, QuillTopicSuggestions } from './QuillTopicBadges'
import { SidebarQuestionInput } from './SidebarQuestionInput'
import { SUGGESTION_CARDS_HEIGHT_PX, TopicBadges, TopicSuggestions } from './TopicBadges'
@@ -27,6 +31,9 @@ export function SidebarQuestionInputWithSuggestions({
const { setActiveGroup, setFillInHint, runSuggestion } = useActions(maxLogic)
const { agentMode } = useValues(maxThreadLogic)
const { coreMemory, coreMemoryLoading, coreMemoryLoadError } = useValues(maxSettingsLogic)
+ const skin = useThreadSkin()
+ const Badges = skin === 'quill' ? QuillTopicBadges : TopicBadges
+ const Suggestions = skin === 'quill' ? QuillTopicSuggestions : TopicSuggestions
const [settingsModalOpen, setSettingsModalOpen] = useState(false)
const [selectedTopic, setSelectedTopic] = useState<string | null>(null)
@@ -65,10 +72,16 @@ export function SidebarQuestionInputWithSuggestions({
hideSuggestions && 'opacity-0'
)}
>
- <h3 className="text-center text-xs font-medium mb-0 text-secondary">{tip}</h3>
+ {skin === 'quill' ? (
+ <Text size="xs" variant="muted" weight="medium" className="m-0 text-center" data-quill>
+ {tip}
+ </Text>
+ ) : (
+ <h3 className="text-center text-xs font-medium mb-0 text-secondary">{tip}</h3>
+ )}
{showBadges ? (
<div className="flex flex-col items-center gap-6 w-full">
- <TopicBadges
+ <Badges
topics={HOMEPAGE_SUGGESTION_TOPICS}
selectedKey={selectedTopic}
onSelect={(key) => {
@@ -78,7 +91,7 @@ export function SidebarQuestionInputWithSuggestions({
/>
{selectedTopicData && (
<div className="w-full overflow-hidden" style={{ height: SUGGESTION_CARDS_HEIGHT_PX }}>
- <TopicSuggestions topic={selectedTopicData} onRun={runSuggestion} />
+ <Suggestions topic={selectedTopicData} onRun={runSuggestion} />
</div>
)}
</div>
diff --git a/frontend/src/scenes/max/components/TopicBadges.tsx b/frontend/src/scenes/max/components/TopicBadges.tsx
index 69e714417aa5..fe95136cf8e3 100644
--- a/frontend/src/scenes/max/components/TopicBadges.tsx
+++ b/frontend/src/scenes/max/components/TopicBadges.tsx
@@ -1,12 +1,6 @@
-import { useValues } from 'kea'
-import { useState } from 'react'
-
import { IconCode } from '@posthog/icons'
import { LemonButton, LemonTag } from '@posthog/lemon-ui'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { cn } from 'lib/utils/css-classes'
import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
@@ -14,8 +8,9 @@ import { FileSystemIconType } from '~/queries/schema/schema-general'
import { SelfDrivingIntroModal } from 'products/signals/frontend/inbox/components/onboarding/SelfDrivingIntroModal'
-import { CODE_BADGE, SuggestionTopic, TopicSuggestion } from '../suggestionTopics'
+import { SuggestionTopic, TopicSuggestion } from '../suggestionTopics'
import { SuggestionCard } from './SuggestionCard'
+import { useCodeBadge } from './useCodeBadge'
// Colors the product icons (via iconForType's ProductIconWrapper). Applied inside the components so
// they look identical on every surface, not only where an ancestor happens to set it (e.g. /home).
@@ -43,18 +38,7 @@ export interface TopicBadgesProps {
/** Row of PostHog AI topic badges (+ the Desktop beta badge). Selection is owned by the parent. */
export function TopicBadges({ topics, selectedKey, onSelect, className }: TopicBadgesProps): JSX.Element | null {
- const isProductAutonomyEnabled = useFeatureFlag('PRODUCT_AUTONOMY')
- const { featureFlags } = useValues(featureFlagLogic)
- // Intro-modal visibility is pure view state, so it stays local instead of in a logic
- const [codeIntroOpen, setCodeIntroOpen] = useState(false)
-
- // Experiment: does labeling the badge by outcome beat the neutral "Code" for self-driving
- // setup? Short-circuit on the autonomy gate so the flag (and its exposure event) is only
- // evaluated for users who actually see the badge.
- const codeBadgeLabel =
- isProductAutonomyEnabled && featureFlags[FEATURE_FLAGS.CODE_BADGE_SELF_DRIVING_LABEL] === 'self-driving'
- ? 'Self-driving'
- : CODE_BADGE.label
+ const codeBadge = useCodeBadge()
if (!topics.length) {
return null
@@ -83,24 +67,24 @@ export function TopicBadges({ topics, selectedKey, onSelect, className }: TopicB
</LemonButton>
))}
- {isProductAutonomyEnabled && (
+ {codeBadge.visible && (
<>
<LemonButton
size="small"
type="secondary"
- onClick={() => setCodeIntroOpen(true)}
+ onClick={codeBadge.openIntro}
icon={<IconCode />}
data-attr="capability-badge-code"
>
<span className="flex items-center gap-1.5">
- {codeBadgeLabel}
+ {codeBadge.label}
<LemonTag type="warning" size="small">
Beta
</LemonTag>
</span>
</LemonButton>
- <SelfDrivingIntroModal isOpen={codeIntroOpen} onClose={() => setCodeIntroOpen(false)} />
+ <SelfDrivingIntroModal isOpen={codeBadge.introOpen} onClose={codeBadge.closeIntro} />
</>
)}
</div>
diff --git a/frontend/src/scenes/max/components/composerCopy.ts b/frontend/src/scenes/max/components/composerCopy.ts
new file mode 100644
index 000000000000..4904442ab4f2
--- /dev/null
+++ b/frontend/src/scenes/max/components/composerCopy.ts
@@ -0,0 +1,40 @@
+import type { Conversation } from '~/types'
+
+export const RESEARCH_BETA_NOTICE = 'Research mode is a free beta feature with lower daily limits'
+export const QUEUED_MESSAGES_HEADING = 'Up next'
+export const SUPPORT_SESSION_NOTICE = "Support agent session — this conversation won't be visible to the customer"
+export const SUPPORT_OVERRIDE_LABEL = "I understand this will add to the customer's conversation"
+
+export type ComposerPlaceholder =
+ | { kind: 'shared'; text: string }
+ | { kind: 'thinking'; text: string }
+ | { kind: 'custom'; text: string }
+ | { kind: 'prompt'; lead: string; hint: string }
+
+export function composerPlaceholder({
+ conversation,
+ isSharedThread,
+ threadLoading,
+ isThreadVisible,
+ placeholder,
+}: {
+ conversation: Conversation | null
+ isSharedThread: boolean
+ threadLoading: boolean
+ isThreadVisible?: boolean
+ placeholder?: string
+}): ComposerPlaceholder {
+ if (conversation && isSharedThread) {
+ return {
+ kind: 'shared',
+ text: `This thread was shared with you by ${conversation.user.first_name} ${conversation.user.last_name}`,
+ }
+ }
+ if (threadLoading) {
+ return { kind: 'thinking', text: 'Thinking…' }
+ }
+ if (isThreadVisible && placeholder) {
+ return { kind: 'custom', text: placeholder }
+ }
+ return { kind: 'prompt', lead: isThreadVisible ? 'Ask follow-up' : 'Ask a question', hint: 'or / for commands' }
+}
diff --git a/frontend/src/scenes/max/components/useCodeBadge.ts b/frontend/src/scenes/max/components/useCodeBadge.ts
new file mode 100644
index 000000000000..45f065a23e05
--- /dev/null
+++ b/frontend/src/scenes/max/components/useCodeBadge.ts
@@ -0,0 +1,39 @@
+import { useValues } from 'kea'
+import { useState } from 'react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { CODE_BADGE } from '../suggestionTopics'
+
+export interface CodeBadge {
+ visible: boolean
+ label: string
+ introOpen: boolean
+ openIntro: () => void
+ closeIntro: () => void
+}
+
+export function useCodeBadge(): CodeBadge {
+ const visible = useFeatureFlag('PRODUCT_AUTONOMY')
+ const { featureFlags } = useValues(featureFlagLogic)
+ // Intro-modal visibility is pure view state, so it stays local instead of in a logic
+ const [introOpen, setIntroOpen] = useState(false)
+
+ // Experiment: does labeling the badge by outcome beat the neutral "Code" for self-driving
+ // setup? Short-circuit on the autonomy gate so the flag (and its exposure event) is only
+ // evaluated for users who actually see the badge.
+ const label =
+ visible && featureFlags[FEATURE_FLAGS.CODE_BADGE_SELF_DRIVING_LABEL] === 'self-driving'
+ ? 'Self-driving'
+ : CODE_BADGE.label
+
+ return {
+ visible,
+ label,
+ introOpen,
+ openIntro: () => setIntroOpen(true),
+ closeIntro: () => setIntroOpen(false),
+ }
+}
diff --git a/frontend/src/scenes/max/components/useQuestionInput.ts b/frontend/src/scenes/max/components/useQuestionInput.ts
new file mode 100644
index 000000000000..60654fb9b815
--- /dev/null
+++ b/frontend/src/scenes/max/components/useQuestionInput.ts
@@ -0,0 +1,376 @@
+import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
+import React, { useEffect, useMemo, useRef, useState } from 'react'
+import { useDebouncedCallback } from 'use-debounce'
+
+import { userLogic } from 'scenes/userLogic'
+
+import { AgentMode } from '~/queries/schema/schema-assistant-messages'
+import { Conversation, ConversationQueueMessage } from '~/types'
+
+import { MAX_MESSAGE_LENGTH, MESSAGE_TOO_LONG, messageLength } from '../max-constants'
+import { maxGlobalLogic } from '../maxGlobalLogic'
+import { maxLogic } from '../maxLogic'
+import { maxThreadLogic } from '../maxThreadLogic'
+import { MAX_SLASH_COMMANDS } from '../slash-commands'
+
+/**
+ * Show the character counter only once the message gets close to the limit. A permanent counter
+ * under every composer would be noise: almost every message is a couple of hundred characters.
+ */
+const LENGTH_COUNTER_THRESHOLD = MAX_MESSAGE_LENGTH * 0.9
+
+export interface QuestionInputController {
+ // Draft
+ inputValue: string
+ handleQuestionChange: (value: string) => void
+ hasQuestion: boolean
+ fillInHint: string | null
+ showFillInHint: boolean
+ promptLength: number | null
+ isOverLengthLimit: boolean
+ maxMessageLength: number
+ // Conversation state
+ conversation: Conversation | null
+ threadLoading: boolean
+ inputDisabled: boolean
+ isSharedThread: boolean
+ streamingActive: boolean
+ pendingPrompt: string | null
+ dataProcessingAccepted: boolean
+ showResearchBanner: boolean
+ // Attachments (only offered on a fresh chat while the sandbox flag is on)
+ showAttachButton: boolean
+ attachmentInputRef: React.RefObject<HTMLInputElement>
+ handleAttachmentChange: (event: React.ChangeEvent<HTMLInputElement>) => void
+ // Queue
+ queueingEnabled: boolean
+ queuedMessages: ConversationQueueMessage[]
+ displayQueuedMessages: ConversationQueueMessage[]
+ queueSubmitting: boolean
+ editingQueueId: string | null
+ setEditingQueueId: (id: string | null) => void
+ saveQueuedMessage: (messageId: string, content: string) => void
+ // Send / stop
+ isQueueingSubmission: boolean
+ showStopButton: boolean
+ submissionDisabledReason: string | undefined
+ disabledReason: string | undefined
+ slashCommandIcon: JSX.Element | undefined
+ submit: (prompt: string) => void
+ handleSendClick: () => void
+ handlePressEnter: () => void
+ handleKeyDown: (event: React.KeyboardEvent<HTMLTextAreaElement>) => void
+ handleBlur: (event: React.FocusEvent<HTMLTextAreaElement>) => void
+ completeThreadGeneration: () => void
+ // Slash commands
+ showAutocomplete: boolean
+ closeAutocomplete: () => void
+ // Support / impersonation
+ isImpersonatedInternalConversation: boolean
+ isImpersonatingExistingConversation: boolean
+ supportOverrideEnabled: boolean
+ setSupportOverrideEnabled: (enabled: boolean) => void
+}
+
+export interface UseQuestionInputOptions {
+ textAreaRef?: React.RefObject<HTMLTextAreaElement>
+ onSubmit?: () => void
+}
+
+/**
+ * The behavior of the legacy PostHog AI composer, shared by its lemon and quill skins: the local draft and
+ * its debounced sync to kea, the slash-command autocomplete, the fill-in hint, the message queue, the
+ * send/stop/queue decision, the length guard, and the sandbox pre-warm release on blur. Each skin only
+ * draws what this returns.
+ */
+export function useQuestionInput({ textAreaRef, onSubmit }: UseQuestionInputOptions): QuestionInputController {
+ const { dataProcessingAccepted, isPhaiSandboxFlagOn } = useValues(maxGlobalLogic)
+ const { question, fillInHint, typingSuggestion } = useValues(maxLogic)
+ const { setQuestion, setFillInHint, cancelSuggestionTyping, attachFilesToNewChat } = useActions(maxLogic)
+ const { user } = useValues(userLogic)
+ const {
+ conversation,
+ threadLoading,
+ inputDisabled,
+ contextDisabledReason,
+ queueDisabledReason,
+ isSharedThread,
+ cancelLoading,
+ pendingPrompt,
+ isImpersonatingExistingConversation,
+ supportOverrideEnabled,
+ streamingActive,
+ agentMode,
+ threadMessageCount,
+ queueingEnabled,
+ queuedMessages,
+ queueSubmitting,
+ } = useValues(maxThreadLogic)
+ const {
+ askMax,
+ stopGeneration,
+ completeThreadGeneration,
+ setSupportOverrideEnabled,
+ updateQueuedMessage,
+ releaseSandboxPrewarm,
+ } = useActions(maxThreadLogic)
+ // Show info banner for conversations created during impersonation (marked as internal)
+ const isImpersonatedInternalConversation = !!user?.is_impersonated && !!conversation?.is_internal
+
+ const [showAutocomplete, setShowAutocomplete] = useState(false)
+ // Tracks an explicit dismissal (e.g. Esc) so the popover stays closed while the
+ // user keeps typing a message that still starts with "/". "/" + Esc is a valid path.
+ const [autocompleteDismissed, setAutocompleteDismissed] = useState(false)
+ const [editingQueueId, setEditingQueueId] = useState<string | null>(null)
+ const displayQueuedMessages = useMemo(() => [...queuedMessages].reverse(), [queuedMessages])
+
+ // Hold the textarea value in local state so each keystroke is an isolated, cheap re-render
+ // rather than a global kea dispatch. Binding the input directly to kea made every keystroke
+ // notify every store subscriber, so input lag grew with conversation length (more mounted
+ // messages = more subscriptions to sweep). kea remains the source of truth for submit, slash
+ // commands, and draft persistence — we sync to it on a debounce, immediately for slash
+ // commands so the autocomplete stays responsive, and on submit/blur.
+ const attachmentInputRef = useRef<HTMLInputElement>(null)
+ const [inputValue, setInputValue] = useState(question)
+ const debouncedSetQuestion = useDebouncedCallback((value: string) => setQuestion(value), 150)
+
+ // Flush any pending debounce when the component unmounts so that a draft typed just
+ // before programmatic navigation (no blur event) is still persisted to kea.
+ useEffect(() => {
+ return () => debouncedSetQuestion.flush()
+ }, [debouncedSetQuestion])
+
+ // Mirror external question changes (draft restore, slash command insertion, clear on submit)
+ // back into local state. Writing the same value is a no-op, so the debounced sync below
+ // doesn't cause an extra render.
+ useEffect(() => {
+ setInputValue(question)
+ }, [question])
+
+ const handleQuestionChange = (value: string): void => {
+ setInputValue(value)
+ // The user typing their own text ends the fill-in cue.
+ if (fillInHint) {
+ setFillInHint(null)
+ }
+ if (value.startsWith('/')) {
+ // Slash commands drive the autocomplete off kea's `question`, so sync immediately.
+ debouncedSetQuestion.cancel()
+ setQuestion(value)
+ } else {
+ debouncedSetQuestion(value)
+ }
+ }
+
+ const submit = (prompt: string): void => {
+ // askMax reads the prompt arg directly and clears `question` afterwards, so drop any
+ // pending debounce to stop it from re-populating the just-sent text.
+ debouncedSetQuestion.cancel()
+ // A suggestion is still typing itself in. The user picked that suggestion, so send all of
+ // it rather than the prefix that happens to be on screen, and stop the animation writing
+ // the rest into the composer after the message has gone.
+ const content = typingSuggestion ?? prompt
+ if (typingSuggestion) {
+ cancelSuggestionTyping()
+ }
+ if (fillInHint) {
+ setFillInHint(null)
+ }
+ askMax(content)
+ }
+
+ // Counting code points is O(n), so only pay for it near the limit. A string's UTF-16 length is
+ // never below its code point count, so a shorter one can't be over the limit.
+ const promptLength = useMemo(
+ () => (inputValue.length >= LENGTH_COUNTER_THRESHOLD ? messageLength(inputValue) : null),
+ [inputValue]
+ )
+ const isOverLengthLimit = promptLength !== null && promptLength > MAX_MESSAGE_LENGTH
+
+ const hasQuestion = inputValue.trim().length > 0
+ // A fill-in suggestion typed its prefix in and is waiting for the user to complete it.
+ const showFillInHint = !!fillInHint
+ const isQueueingSubmission = queueingEnabled && threadLoading && hasQuestion
+ const showStopButton = threadLoading && !isQueueingSubmission && !cancelLoading
+
+ // Mirrors maxThreadLogic's `submissionDisabledReason` selector, but using the local input
+ // value so the submit guard stays correct while the debounced sync to kea is still pending.
+ const submissionDisabledReason = contextDisabledReason
+ ? contextDisabledReason
+ : !inputValue
+ ? 'I need some input first'
+ : isOverLengthLimit
+ ? MESSAGE_TOO_LONG
+ : queueDisabledReason
+
+ // Update autocomplete visibility when the input changes
+ useEffect(() => {
+ const isSlashCommand = inputValue[0] === '/'
+ // Once the input is no longer a slash command, clear any prior dismissal so
+ // typing "/" again later reopens the popover.
+ if (!isSlashCommand && autocompleteDismissed) {
+ setAutocompleteDismissed(false)
+ }
+ const shouldShow = isSlashCommand && !autocompleteDismissed
+ if (shouldShow && !showAutocomplete) {
+ posthog.capture('Max slash command autocomplete shown') // [PostHog] Event: "Max slash command autocomplete shown"
+ }
+ setShowAutocomplete(shouldShow)
+ }, [inputValue, showAutocomplete, autocompleteDismissed])
+
+ let disabledReason = submissionDisabledReason
+ if (threadLoading && !isQueueingSubmission) {
+ disabledReason = undefined
+ }
+ if (cancelLoading) {
+ disabledReason = 'Cancelling...'
+ }
+
+ useEffect(() => {
+ if (!streamingActive && textAreaRef?.current) {
+ textAreaRef.current.focus()
+ }
+ }, [streamingActive]) // oxlint-disable-line react-hooks/exhaustive-deps
+
+ const closeAutocomplete = (): void => {
+ setShowAutocomplete(false)
+ setAutocompleteDismissed(true)
+ }
+
+ const handleBlur = (e: React.FocusEvent<HTMLTextAreaElement>): void => {
+ debouncedSetQuestion.flush()
+ // Release any sandbox pre-warm when the user leaves the
+ // input without sending. No-op on LangGraph / unwarmed
+ // conversations.
+ //
+ // But clicking the send button blurs the textarea *before*
+ // its onClick fires the send — releasing here would cancel
+ // the very warm Run the send is about to consume. When focus
+ // moves to the send button, skip the release and let the send
+ // path consume the warm (it does so without a DELETE).
+ const next = e.relatedTarget as HTMLElement | null
+ if (next?.closest('[data-attr="max-send-message"]')) {
+ return
+ }
+ releaseSandboxPrewarm()
+ }
+
+ const handlePressEnter = (): void => {
+ if (hasQuestion && !submissionDisabledReason && (!threadLoading || queueingEnabled)) {
+ onSubmit?.()
+ submit(inputValue)
+ }
+ }
+
+ const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>): void => {
+ if (event.key === 'ArrowUp' && !inputValue.trim() && queuedMessages.length > 0 && !editingQueueId) {
+ const target = event.currentTarget
+ const atStart = target.selectionStart === 0 && target.selectionEnd === 0
+ const isSingleLine = target.value.split('\n').length <= 1
+ if (!atStart || !isSingleLine) {
+ return
+ }
+ const nextMessageId = queuedMessages[0]?.id
+ if (!nextMessageId) {
+ return
+ }
+ event.preventDefault()
+ setEditingQueueId(nextMessageId)
+ }
+ }
+
+ const handleSendClick = (): void => {
+ if (threadLoading) {
+ if (isQueueingSubmission) {
+ if (submissionDisabledReason) {
+ textAreaRef?.current?.focus()
+ return
+ }
+ submit(inputValue)
+ return
+ }
+ stopGeneration()
+ return
+ }
+ if (submissionDisabledReason) {
+ textAreaRef?.current?.focus()
+ return
+ }
+ submit(inputValue)
+ }
+
+ const handleAttachmentChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
+ const files = Array.from(event.target.files ?? [])
+ event.target.value = ''
+ attachFilesToNewChat(files, inputValue)
+ }
+
+ const saveQueuedMessage = (messageId: string, content: string): void => {
+ updateQueuedMessage(messageId, content)
+ setEditingQueueId(null)
+ }
+
+ const slashCommandIcon = MAX_SLASH_COMMANDS.find((cmd) => cmd.name === inputValue.split(' ', 1)[0])?.icon
+
+ return {
+ // Draft
+ inputValue,
+ handleQuestionChange,
+ hasQuestion,
+ fillInHint,
+ showFillInHint,
+ promptLength,
+ isOverLengthLimit,
+ maxMessageLength: MAX_MESSAGE_LENGTH,
+ // Conversation state
+ conversation,
+ threadLoading,
+ inputDisabled,
+ isSharedThread,
+ streamingActive,
+ pendingPrompt,
+ dataProcessingAccepted,
+ showResearchBanner: agentMode === AgentMode.Research && threadMessageCount === 0,
+ // Attachments (only offered on a fresh chat while the sandbox flag is on)
+ showAttachButton: isPhaiSandboxFlagOn && !conversation,
+ attachmentInputRef,
+ handleAttachmentChange,
+ // Queue
+ queueingEnabled,
+ queuedMessages,
+ displayQueuedMessages,
+ queueSubmitting,
+ editingQueueId,
+ setEditingQueueId,
+ saveQueuedMessage,
+ // Send / stop
+ isQueueingSubmission,
+ showStopButton,
+ submissionDisabledReason,
+ disabledReason,
+ slashCommandIcon,
+ submit,
+ handleSendClick,
+ handlePressEnter,
+ handleKeyDown,
+ handleBlur,
+ completeThreadGeneration,
+ // Slash commands
+ showAutocomplete,
+ closeAutocomplete,
+ // Support / impersonation
+ isImpersonatedInternalConversation,
+ isImpersonatingExistingConversation,
+ supportOverrideEnabled,
+ setSupportOverrideEnabled,
+ }
+}
+
+export interface QueuedMessageEditProps {
+ message: ConversationQueueMessage
+ isEditing: boolean
+ onEdit: () => void
+ onCancel: () => void
+ onSave: (messageId: string, content: string) => void
+}
diff --git a/frontend/src/scenes/max/messages/AssistantMessageForm.tsx b/frontend/src/scenes/max/messages/AssistantMessageForm.tsx
new file mode 100644
index 000000000000..bd7b84225cf5
--- /dev/null
+++ b/frontend/src/scenes/max/messages/AssistantMessageForm.tsx
@@ -0,0 +1,47 @@
+import { useActions } from 'kea'
+
+import { LemonButton, LemonButtonPropsBase } from '@posthog/lemon-ui'
+
+import { AssistantForm } from '~/queries/schema/schema-assistant-messages'
+
+import { useQuillThread } from 'products/posthog_ai/frontend/api/primitives'
+
+import { maxThreadLogic } from '../maxThreadLogic'
+import { QuillAssistantMessageForm } from './quill/QuillAssistantMessageForm'
+
+export interface AssistantMessageFormProps {
+ form: AssistantForm
+ linksOnly?: boolean
+}
+
+export function AssistantMessageForm(props: AssistantMessageFormProps): JSX.Element {
+ return useQuillThread() ? <QuillAssistantMessageForm {...props} /> : <LemonAssistantMessageForm {...props} />
+}
+
+function LemonAssistantMessageForm({ form, linksOnly }: AssistantMessageFormProps): JSX.Element {
+ const { askMax } = useActions(maxThreadLogic)
+ const options = linksOnly ? form.options.filter((option) => option.href) : form.options
+
+ return (
+ // ml-1 is because buttons have radius of 0.375rem, while messages of 0.65rem, where diff = 0.25rem
+ // Also makes it clear the form is subservient to the message. *Harmony*
+ <div className="flex flex-wrap gap-1.5 ml-1 mt-1">
+ {options.map((option) => (
+ <LemonButton
+ key={option.value}
+ onClick={!option.href ? () => askMax(option.value) : undefined}
+ to={option.href}
+ size="small"
+ targetBlank={!!option.href}
+ type={
+ option.variant && ['primary', 'secondary', 'tertiary'].includes(option.variant)
+ ? (option.variant as LemonButtonPropsBase['type'])
+ : 'secondary'
+ }
+ >
+ {option.value}
+ </LemonButton>
+ ))}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/max/messages/MultiQuestionForm.tsx b/frontend/src/scenes/max/messages/MultiQuestionForm.tsx
index ad15649ccea2..7ebbc82af5fa 100644
--- a/frontend/src/scenes/max/messages/MultiQuestionForm.tsx
+++ b/frontend/src/scenes/max/messages/MultiQuestionForm.tsx
@@ -1,8 +1,10 @@
+import React from 'react'
+
import { IconCheck, IconX } from '@posthog/icons'
import { MultiQuestionForm as MultiQuestionFormType } from '~/queries/schema/schema-assistant-messages'
-import { MessageTemplate } from 'products/posthog_ai/frontend/api/primitives'
+import { MessageTemplate, QuillAssistantBubble, useQuillThread } from 'products/posthog_ai/frontend/api/primitives'
interface MultiQuestionFormRecapProps {
form: MultiQuestionFormType
@@ -21,6 +23,9 @@ export function MultiQuestionFormRecap({
formStatus,
}: MultiQuestionFormRecapProps): JSX.Element | null {
const questions = form.questions
+ const quill = useQuillThread()
+ // The recap is ghost prose in the quill thread and a bordered bubble in the lemon one.
+ const Shell = quill ? QuillAssistantBubble : LemonRecapShell
if (!questions || questions.length === 0) {
return null
@@ -28,7 +33,7 @@ export function MultiQuestionFormRecap({
if (formStatus === 'dismiss_form') {
return (
- <MessageTemplate type="ai">
+ <Shell>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1.5 text-xs text-muted">
<IconX />
@@ -36,12 +41,12 @@ export function MultiQuestionFormRecap({
</div>
<div className="text-sm text-muted">The user chose not to answer these questions.</div>
</div>
- </MessageTemplate>
+ </Shell>
)
}
return (
- <MessageTemplate type="ai">
+ <Shell>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-1.5 text-xs text-muted">
<IconCheck className="text-success" />
@@ -92,6 +97,10 @@ export function MultiQuestionFormRecap({
})}
</div>
</div>
- </MessageTemplate>
+ </Shell>
)
}
+
+function LemonRecapShell({ children }: { children: React.ReactNode }): JSX.Element {
+ return <MessageTemplate type="ai">{children}</MessageTemplate>
+}
diff --git a/frontend/src/scenes/max/messages/MultiVisualizationAnswer.tsx b/frontend/src/scenes/max/messages/MultiVisualizationAnswer.tsx
new file mode 100644
index 000000000000..4e6d8c7b468a
--- /dev/null
+++ b/frontend/src/scenes/max/messages/MultiVisualizationAnswer.tsx
@@ -0,0 +1,58 @@
+import clsx from 'clsx'
+
+import { IconExpand } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+
+import { MultiVisualizationMessage } from '~/queries/schema/schema-assistant-messages'
+
+import { MarkdownMessage, useQuillThread } from 'products/posthog_ai/frontend/api/primitives'
+
+import { useMultiVisualizationInsights } from './multiVisualizationInsights'
+import { openMultiVisualizationModal } from './MultiVisualizationModal'
+import { MultiVisualizationMosaic } from './MultiVisualizationMosaic'
+import { QuillMultiVisualizationAnswer } from './quill/QuillMultiVisualizationAnswer'
+
+export interface MultiVisualizationAnswerProps {
+ message: MultiVisualizationMessage
+ className?: string
+}
+
+export function MultiVisualizationAnswer(props: MultiVisualizationAnswerProps): JSX.Element | null {
+ const quill = useQuillThread()
+ if (props.message.visualizations.length === 0) {
+ return null
+ }
+ return quill ? <QuillMultiVisualizationAnswer {...props} /> : <LemonMultiVisualizationAnswer {...props} />
+}
+
+function LemonMultiVisualizationAnswer({ message, className }: MultiVisualizationAnswerProps): JSX.Element {
+ const insights = useMultiVisualizationInsights(message.visualizations)
+ return (
+ <div className={clsx('flex flex-col gap-px w-full break-words', className)}>
+ <div className="max-w-full border py-3 px-4 rounded-lg bg-surface-primary">
+ <div className="space-y-2">
+ <div className="w-full flex justify-between items-center">
+ <h2 className="text-sm font-semibold text-secondary">
+ {pluralize(message.visualizations.length, 'insight')} analyzed
+ </h2>
+ {message.visualizations.length > 1 && (
+ <LemonButton
+ icon={<IconExpand />}
+ size="xsmall"
+ type="tertiary"
+ onClick={() => openMultiVisualizationModal(insights)}
+ tooltip="View all insights in detail"
+ >
+ Expand
+ </LemonButton>
+ )}
+ </div>
+ <MultiVisualizationMosaic insights={insights} />
+ {message.commentary && <MarkdownMessage content={message.commentary} id="multi-viz-commentary" />}
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/max/messages/MultiVisualizationModal.tsx b/frontend/src/scenes/max/messages/MultiVisualizationModal.tsx
new file mode 100644
index 000000000000..b01269cf6b7f
--- /dev/null
+++ b/frontend/src/scenes/max/messages/MultiVisualizationModal.tsx
@@ -0,0 +1,63 @@
+import clsx from 'clsx'
+import React from 'react'
+
+import { LemonDialog } from '@posthog/lemon-ui'
+
+import { TopHeading } from 'lib/components/Cards/InsightCard/TopHeading'
+
+import { Query } from '~/queries/Query/Query'
+
+import type { MultiVisualizationInsight } from './multiVisualizationInsights'
+
+export function openMultiVisualizationModal(insights: MultiVisualizationInsight[]): void {
+ LemonDialog.open({
+ title: 'Insights',
+ content: <MultiVisualizationModal insights={insights} />,
+ primaryButton: null,
+ width: '90%',
+ maxWidth: 1400,
+ })
+}
+
+function MultiVisualizationModal({ insights: messages }: { insights: MultiVisualizationInsight[] }): JSX.Element {
+ const [selectedIndex, setSelectedIndex] = React.useState(0)
+
+ return (
+ <div className="flex">
+ {/* Sidebar with visualization list */}
+ <div className="w-64 border-r pr-4 overflow-y-auto">
+ <h5 className="text-xs font-semibold text-muted mb-3">VISUALIZATIONS</h5>
+ <div className="space-y-1">
+ {messages.map((item, index) => (
+ <button
+ key={index}
+ onClick={() => setSelectedIndex(index)}
+ className={clsx(
+ 'w-full text-left p-2 rounded transition-colors text-sm',
+ selectedIndex === index
+ ? 'bg-primary text-primary-inverted font-semibold'
+ : 'hover:bg-surface-secondary'
+ )}
+ >
+ {item.title}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Main content area */}
+ <div className="flex-1 pl-4 overflow-auto">
+ {messages[selectedIndex] && (
+ <>
+ <h4 className="text-base font-semibold mb-3">
+ <TopHeading query={messages[selectedIndex].query} />
+ </h4>
+ <div className="min-h-80">
+ <Query query={messages[selectedIndex].query} readOnly embedded />
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/max/messages/MultiVisualizationMosaic.tsx b/frontend/src/scenes/max/messages/MultiVisualizationMosaic.tsx
new file mode 100644
index 000000000000..774fa30a78bc
--- /dev/null
+++ b/frontend/src/scenes/max/messages/MultiVisualizationMosaic.tsx
@@ -0,0 +1,100 @@
+import clsx from 'clsx'
+import React, { useState } from 'react'
+
+import { IconCollapse, IconExpand, IconEye, IconHide } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import {
+ InsightBreakdownSummary,
+ PropertiesSummary,
+ SeriesSummary,
+} from 'lib/components/Cards/InsightCard/InsightDetails'
+import { TopHeading } from 'lib/components/Cards/InsightCard/TopHeading'
+
+import { Query } from '~/queries/Query/Query'
+import { DataVisualizationNode, InsightVizNode } from '~/queries/schema/schema-general'
+import { isDataVisualizationNode, isHogQLQuery } from '~/queries/utils'
+
+import type { MultiVisualizationInsight } from './multiVisualizationInsights'
+
+export function MultiVisualizationMosaic({ insights }: { insights: MultiVisualizationInsight[] }): JSX.Element {
+ if (insights.length === 1) {
+ return (
+ <div className="w-full relative">
+ <Visualization query={insights[0].query} />
+ </div>
+ )
+ }
+ const insightsToShow = insights.slice(0, 4)
+ const gridCols = insightsToShow.length === 3 ? 'grid-cols-3' : 'grid-cols-2'
+ return (
+ <div className={`grid ${gridCols} gap-2`}>
+ {insightsToShow.map((insight, index) => (
+ // The chart grows with `flex: 1`, so the cell is a fixed-height flex column; a block cell
+ // collapses it to a sliver.
+ <div key={index} className="relative flex h-[200px] flex-col">
+ <Query query={insight.query} readOnly embedded />
+ </div>
+ ))}
+ </div>
+ )
+}
+
+const Visualization = React.memo(function Visualization({
+ query,
+ collapsed,
+ editingChildren,
+}: {
+ query: InsightVizNode | DataVisualizationNode
+ collapsed?: boolean
+ editingChildren?: React.ReactNode
+}): JSX.Element | null {
+ const [isSummaryShown, setIsSummaryShown] = useState(false)
+ const [isCollapsed, setIsCollapsed] = useState(collapsed ?? false)
+
+ if (!query) {
+ return null
+ }
+
+ return (
+ <>
+ {!isCollapsed && <Query query={query} readOnly embedded />}
+ <div className={clsx('flex items-center justify-between', !isCollapsed && 'mt-2')}>
+ <div className="flex items-center gap-1.5">
+ <LemonButton
+ sideIcon={isSummaryShown ? <IconCollapse /> : <IconExpand />}
+ onClick={() => setIsSummaryShown(!isSummaryShown)}
+ size="xsmall"
+ className="-m-1 shrink"
+ tooltip={isSummaryShown ? 'Hide definition' : 'Show definition'}
+ >
+ <h5 className="m-0 leading-none">
+ <TopHeading query={query} />
+ </h5>
+ </LemonButton>
+ </div>
+ <div className="flex items-center gap-1.5">
+ {editingChildren}
+ <LemonButton
+ icon={isCollapsed ? <IconEye /> : <IconHide />}
+ onClick={() => setIsCollapsed(!isCollapsed)}
+ size="xsmall"
+ className="-m-1 shrink"
+ tooltip={isCollapsed ? 'Show visualization' : 'Hide visualization'}
+ />
+ </div>
+ </div>
+ {isSummaryShown && !isDataVisualizationNode(query) && (
+ <>
+ <SeriesSummary query={query.source} heading={null} />
+ {!isHogQLQuery(query.source) && (
+ <div className="flex flex-wrap gap-4 mt-1 *:grow">
+ <PropertiesSummary properties={query.source.properties} />
+ <InsightBreakdownSummary query={query.source} />
+ </div>
+ )}
+ </>
+ )}
+ </>
+ )
+})
diff --git a/frontend/src/scenes/max/messages/PlanningAnswer.tsx b/frontend/src/scenes/max/messages/PlanningAnswer.tsx
new file mode 100644
index 000000000000..b4454dbe99d0
--- /dev/null
+++ b/frontend/src/scenes/max/messages/PlanningAnswer.tsx
@@ -0,0 +1,94 @@
+import clsx from 'clsx'
+import { useLayoutEffect, useState } from 'react'
+
+import { IconChevronRight, IconNotebook } from '@posthog/icons'
+import { LemonCheckbox } from '@posthog/lemon-ui'
+
+import { useQuillThread } from 'products/posthog_ai/frontend/api/primitives'
+
+import { ShimmeringContent } from '../components/Activity'
+import { EnhancedToolCall } from '../max-constants'
+import { parsePlanningSteps } from './planningSteps'
+import { QuillPlanningAnswer } from './quill/QuillPlanningAnswer'
+
+export interface PlanningAnswerProps {
+ toolCall: EnhancedToolCall
+ isLastPlanningMessage?: boolean
+}
+
+export function PlanningAnswer(props: PlanningAnswerProps): JSX.Element {
+ return useQuillThread() ? <QuillPlanningAnswer {...props} /> : <LemonPlanningAnswer {...props} />
+}
+
+function LemonPlanningAnswer({ toolCall, isLastPlanningMessage = true }: PlanningAnswerProps): JSX.Element {
+ const [isExpanded, setIsExpanded] = useState(isLastPlanningMessage)
+
+ useLayoutEffect(() => {
+ setIsExpanded(isLastPlanningMessage)
+ }, [isLastPlanningMessage])
+
+ const steps = parsePlanningSteps(toolCall)
+ const completedCount = steps.filter((step) => step.status === 'completed').length
+ const totalCount = steps.length
+ const hasMultipleSteps = steps.length > 1
+
+ return (
+ <div className="flex flex-col text-xs">
+ <div
+ className={clsx(
+ 'flex items-center select-none',
+ !hasMultipleSteps ? 'cursor-default' : 'cursor-pointer'
+ )}
+ onClick={!hasMultipleSteps ? undefined : () => setIsExpanded(!isExpanded)}
+ aria-label={!hasMultipleSteps ? undefined : isExpanded ? 'Collapse plan' : 'Expand plan'}
+ >
+ <div className="flex items-center justify-center size-5">
+ <IconNotebook />
+ </div>
+ <div className="flex items-center gap-1.5 flex-1 min-w-0">
+ <span>Planning</span>
+ <span className="text-muted">
+ ({completedCount}/{totalCount})
+ </span>
+ {hasMultipleSteps && (
+ <button className="cursor-pointer inline-flex items-center hover:opacity-70 transition-opacity flex-shrink-0">
+ <span className={`transform transition-transform ${isExpanded ? 'rotate-90' : ''}`}>
+ <IconChevronRight />
+ </span>
+ </button>
+ )}
+ </div>
+ </div>
+ {isExpanded && (
+ <div className="mt-1.5 space-y-1.5 border-l-2 border-border-secondary pl-3.5 ml-2">
+ {steps.map((step, index) => {
+ const isCompleted = step.status === 'completed'
+ const isInProgress = step.status === 'in_progress'
+
+ return (
+ <div key={index} className="flex items-start gap-2 animate-fade-in">
+ <span className="flex-shrink-0">
+ <LemonCheckbox checked={isCompleted} disabled size="xsmall" />
+ </span>
+ <span
+ className={clsx(
+ 'leading-relaxed',
+ isCompleted && 'text-muted line-through',
+ isInProgress && 'font-medium'
+ )}
+ >
+ {step.description}
+ {isInProgress && (
+ <ShimmeringContent>
+ <span className="text-muted ml-1">(in progress)</span>
+ </ShimmeringContent>
+ )}
+ </span>
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/max/messages/RetriableFailureActions.tsx b/frontend/src/scenes/max/messages/RetriableFailureActions.tsx
new file mode 100644
index 000000000000..3d5bbd790a84
--- /dev/null
+++ b/frontend/src/scenes/max/messages/RetriableFailureActions.tsx
@@ -0,0 +1,37 @@
+import { useActions } from 'kea'
+
+import { IconRefresh } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+import { Button } from '@posthog/quill'
+
+import { useQuillThread } from 'products/posthog_ai/frontend/api/primitives'
+
+import { maxThreadLogic } from '../maxThreadLogic'
+
+export function RetriableFailureActions(): JSX.Element {
+ const { retryLastMessage } = useActions(maxThreadLogic)
+
+ if (useQuillThread()) {
+ return (
+ <div>
+ <Button variant="outline" size="sm" onClick={() => retryLastMessage()}>
+ <IconRefresh />
+ Try again
+ </Button>
+ </div>
+ )
+ }
+
+ return (
+ <LemonButton
+ icon={<IconRefresh />}
+ type="tertiary"
+ size="xsmall"
+ tooltip="Try again"
+ onClick={() => retryLastMessage()}
+ className="ml-1"
+ >
+ Try again
+ </LemonButton>
+ )
+}
diff --git a/frontend/src/scenes/max/messages/SuccessActions.tsx b/frontend/src/scenes/max/messages/SuccessActions.tsx
new file mode 100644
index 000000000000..48ea96b2d450
--- /dev/null
+++ b/frontend/src/scenes/max/messages/SuccessActions.tsx
@@ -0,0 +1,130 @@
+import { useActions } from 'kea'
+
+import {
+ IconCopy,
+ IconEye,
+ IconRefresh,
+ IconThumbsDown,
+ IconThumbsDownFilled,
+ IconThumbsUp,
+ IconThumbsUpFilled,
+ IconX,
+} from '@posthog/icons'
+import { LemonButton, LemonInput } from '@posthog/lemon-ui'
+
+import { copyToClipboard } from '~/lib/utils/copyToClipboard'
+import { stripMarkdown } from '~/lib/utils/markdown'
+
+import { MessageTemplate, useQuillThread } from 'products/posthog_ai/frontend/api/primitives'
+
+import { maxThreadLogic } from '../maxThreadLogic'
+import { QuillSuccessActions } from './quill/QuillSuccessActions'
+import { useAnswerRating } from './useAnswerRating'
+
+export interface SuccessActionsProps {
+ retriable: boolean
+ hideRatingAndRetry?: boolean
+ content?: string | null
+}
+
+export function SuccessActions(props: SuccessActionsProps): JSX.Element {
+ return useQuillThread() ? <QuillSuccessActions {...props} /> : <LemonSuccessActions {...props} />
+}
+
+function LemonSuccessActions({ retriable, hideRatingAndRetry, content }: SuccessActionsProps): JSX.Element {
+ const { retryLastMessage } = useActions(maxThreadLogic)
+ const {
+ traceId,
+ rating,
+ submitRating,
+ feedback,
+ setFeedback,
+ feedbackInputStatus,
+ closeFeedback,
+ submitFeedback,
+ traceUrl,
+ } = useAnswerRating()
+
+ return (
+ <>
+ <div className="flex items-center ml-1">
+ {content && (
+ <LemonButton
+ icon={<IconCopy />}
+ type="tertiary"
+ size="xsmall"
+ tooltip="Copy answer"
+ onClick={() => copyToClipboard(stripMarkdown(content))}
+ />
+ )}
+ {!hideRatingAndRetry && rating !== 'bad' && (
+ <LemonButton
+ icon={rating === 'good' ? <IconThumbsUpFilled /> : <IconThumbsUp />}
+ type="tertiary"
+ size="xsmall"
+ tooltip="Good answer"
+ onClick={() => submitRating('good')}
+ />
+ )}
+ {!hideRatingAndRetry && rating !== 'good' && (
+ <LemonButton
+ icon={rating === 'bad' ? <IconThumbsDownFilled /> : <IconThumbsDown />}
+ type="tertiary"
+ size="xsmall"
+ tooltip="Bad answer"
+ onClick={() => submitRating('bad')}
+ />
+ )}
+ {!hideRatingAndRetry && retriable && (
+ <LemonButton
+ icon={<IconRefresh />}
+ type="tertiary"
+ size="xsmall"
+ tooltip="Try again"
+ onClick={() => retryLastMessage()}
+ />
+ )}
+ {traceUrl && traceId && (
+ <LemonButton
+ to={traceUrl}
+ icon={<IconEye />}
+ type="tertiary"
+ size="xsmall"
+ tooltip="View trace in AI observability"
+ />
+ )}
+ </div>
+ {!hideRatingAndRetry && feedbackInputStatus !== 'hidden' && (
+ <MessageTemplate type="ai">
+ <div className="flex items-center gap-1">
+ <h4 className="m-0 text-sm grow">
+ {feedbackInputStatus === 'pending'
+ ? 'What disappointed you about the answer?'
+ : 'Thank you for your feedback!'}
+ </h4>
+ <LemonButton icon={<IconX />} type="tertiary" size="xsmall" onClick={closeFeedback} />
+ </div>
+ {feedbackInputStatus === 'pending' && (
+ <div className="flex w-full gap-1.5 items-center mt-1.5">
+ <LemonInput
+ placeholder="Help us improve PostHog AI…"
+ fullWidth
+ value={feedback}
+ onChange={(newValue) => setFeedback(newValue)}
+ onPressEnter={() => submitFeedback()}
+ autoFocus
+ />
+ <LemonButton
+ type="primary"
+ onClick={() => submitFeedback()}
+ disabledReason={!feedback ? 'Please type a few words!' : undefined}
+ >
+ Submit
+ </LemonButton>
+ </div>
+ )}
+ </MessageTemplate>
+ )}
+ </>
+ )
+}
diff --git a/frontend/src/scenes/max/messages/multiVisualizationInsights.ts b/frontend/src/scenes/max/messages/multiVisualizationInsights.ts
new file mode 100644
index 000000000000..7a39d35af7ff
--- /dev/null
+++ b/frontend/src/scenes/max/messages/multiVisualizationInsights.ts
@@ -0,0 +1,26 @@
+import { useMemo } from 'react'
+
+import { VisualizationItem } from '~/queries/schema/schema-assistant-messages'
+import { DataVisualizationNode, InsightVizNode } from '~/queries/schema/schema-general'
+
+import { visualizationTypeToQuery } from '../utils'
+
+export interface MultiVisualizationInsight {
+ query: InsightVizNode | DataVisualizationNode
+ title: string
+}
+
+export function useMultiVisualizationInsights(visualizations: VisualizationItem[]): MultiVisualizationInsight[] {
+ return useMemo(
+ () =>
+ visualizations.flatMap((visualization, index) => {
+ const query = visualizationTypeToQuery(visualization)
+ // Visualization items only ever carry insight or data-visualization queries.
+ const insightQuery = query as InsightVizNode | DataVisualizationNode | null
+ return insightQuery
+ ? [{ query: insightQuery, title: visualization.plan || `Insight #${index + 1}` }]
+ : []
+ }),
+ [visualizations]
+ )
+}
diff --git a/frontend/src/scenes/max/messages/planningSteps.ts b/frontend/src/scenes/max/messages/planningSteps.ts
new file mode 100644
index 000000000000..d2b2745c31c7
--- /dev/null
+++ b/frontend/src/scenes/max/messages/planningSteps.ts
@@ -0,0 +1,20 @@
+import { PlanningStep, PlanningStepStatus } from '~/queries/schema/schema-assistant-messages'
+
+import { EnhancedToolCall } from '../max-constants'
+
+export const PLAN_STEP_STATUS: Record<string, 'pending' | 'active' | 'done' | 'failed'> = {
+ completed: 'done',
+ in_progress: 'active',
+ failed: 'failed',
+}
+
+/** The steps of a `todo_write` call, whose `todos` arg holds `{ content, status, activeForm }` items. */
+export function parsePlanningSteps(toolCall: EnhancedToolCall): PlanningStep[] {
+ if (!Array.isArray(toolCall.args.todos)) {
+ return []
+ }
+ return (toolCall.args.todos as Array<{ content: string; status: string; activeForm: string }>).map((todo) => ({
+ description: todo.content,
+ status: todo.status as PlanningStepStatus,
+ }))
+}
diff --git a/frontend/src/scenes/max/messages/quill/QuillAssistantMessageForm.tsx b/frontend/src/scenes/max/messages/quill/QuillAssistantMessageForm.tsx
new file mode 100644
index 000000000000..50267a1cce65
--- /dev/null
+++ b/frontend/src/scenes/max/messages/quill/QuillAssistantMessageForm.tsx
@@ -0,0 +1,29 @@
+import { useActions } from 'kea'
+
+import { Button } from '@posthog/quill'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+
+import { maxThreadLogic } from '../../maxThreadLogic'
+import type { AssistantMessageFormProps } from '../AssistantMessageForm'
+
+export function QuillAssistantMessageForm({ form, linksOnly }: AssistantMessageFormProps): JSX.Element {
+ const { askMax } = useActions(maxThreadLogic)
+ const options = linksOnly ? form.options.filter((option) => option.href) : form.options
+
+ return (
+ <div className="flex flex-wrap gap-1.5">
+ {options.map((option) => (
+ <Button
+ key={option.value}
+ size="sm"
+ variant={option.variant === 'primary' ? 'primary' : 'outline'}
+ onClick={!option.href ? () => askMax(option.value) : undefined}
+ render={option.href ? <LinkPrimitive to={option.href} target="_blank" /> : undefined}
+ >
+ {option.value}
+ </Button>
+ ))}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/max/messages/quill/QuillMultiVisualizationAnswer.tsx b/frontend/src/scenes/max/messages/quill/QuillMultiVisualizationAnswer.tsx
new file mode 100644
index 000000000000..7e6e122a2c12
--- /dev/null
+++ b/frontend/src/scenes/max/messages/quill/QuillMultiVisualizationAnswer.tsx
@@ -0,0 +1,42 @@
+import { IconExpand } from '@posthog/icons'
+import { Button, Card, CardContent, CardHeader, CardTitle } from '@posthog/quill'
+
+import { cn } from 'lib/utils/css-classes'
+import { pluralize } from 'lib/utils/strings'
+
+import { NotQuill, QuillAssistantMarkdown, quillCardBorderClass } from 'products/posthog_ai/frontend/api/primitives'
+
+import type { MultiVisualizationAnswerProps } from '../MultiVisualizationAnswer'
+import { useMultiVisualizationInsights } from '../multiVisualizationInsights'
+import { openMultiVisualizationModal } from '../MultiVisualizationModal'
+import { MultiVisualizationMosaic } from '../MultiVisualizationMosaic'
+
+export function QuillMultiVisualizationAnswer({ message, className }: MultiVisualizationAnswerProps): JSX.Element {
+ const insights = useMultiVisualizationInsights(message.visualizations)
+ return (
+ <Card size="sm" className={cn('w-full max-w-full', quillCardBorderClass(), className)}>
+ <CardHeader className="flex flex-row items-center justify-between gap-2">
+ <CardTitle>{pluralize(message.visualizations.length, 'insight')} analyzed</CardTitle>
+ {message.visualizations.length > 1 && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => openMultiVisualizationModal(insights)}
+ tooltip="View all insights in detail"
+ >
+ <IconExpand />
+ Expand
+ </Button>
+ )}
+ </CardHeader>
+ <CardContent className="flex flex-col gap-2">
+ <NotQuill>
+ <MultiVisualizationMosaic insights={insights} />
+ </NotQuill>
+ {message.commentary && (
+ <QuillAssistantMarkdown content={message.commentary} id="multi-viz-commentary" />
+ )}
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/frontend/src/scenes/max/messages/quill/QuillPlanningAnswer.tsx b/frontend/src/scenes/max/messages/quill/QuillPlanningAnswer.tsx
new file mode 100644
index 000000000000..39710f81d032
--- /dev/null
+++ b/frontend/src/scenes/max/messages/quill/QuillPlanningAnswer.tsx
@@ -0,0 +1,35 @@
+import { IconNotebook } from '@posthog/icons'
+import { ChatTask } from '@posthog/quill'
+
+import { Activity } from 'products/posthog_ai/frontend/api/primitives'
+
+import type { PlanningAnswerProps } from '../PlanningAnswer'
+import { PLAN_STEP_STATUS, parsePlanningSteps } from '../planningSteps'
+
+/** The plan as the shared activity row, so it opens and closes like the tool calls around it. */
+export function QuillPlanningAnswer({ toolCall, isLastPlanningMessage = true }: PlanningAnswerProps): JSX.Element {
+ const steps = parsePlanningSteps(toolCall)
+ const completedCount = steps.filter((step) => step.status === 'completed').length
+
+ return (
+ <Activity
+ id={toolCall.id}
+ title="Planning"
+ subtitle={`${completedCount}/${steps.length}`}
+ status="completed"
+ defaultOpen={isLastPlanningMessage}
+ icon={<IconNotebook />}
+ details={
+ steps.length > 1 ? (
+ <ol className="quill-chat-task-list__items p-0">
+ {steps.map((step, index) => (
+ <ChatTask key={index} status={PLAN_STEP_STATUS[step.status] ?? 'pending'}>
+ {step.description}
+ </ChatTask>
+ ))}
+ </ol>
+ ) : null
+ }
+ />
+ )
+}
diff --git a/frontend/src/scenes/max/messages/quill/QuillSuccessActions.tsx b/frontend/src/scenes/max/messages/quill/QuillSuccessActions.tsx
new file mode 100644
index 000000000000..53012a2e20ae
--- /dev/null
+++ b/frontend/src/scenes/max/messages/quill/QuillSuccessActions.tsx
@@ -0,0 +1,110 @@
+import { useActions } from 'kea'
+
+import {
+ IconEye,
+ IconRefresh,
+ IconThumbsDown,
+ IconThumbsDownFilled,
+ IconThumbsUp,
+ IconThumbsUpFilled,
+ IconX,
+} from '@posthog/icons'
+import { Button, ChatMessageFooter, Input, Text } from '@posthog/quill'
+
+import { LinkPrimitive } from 'lib/lemon-ui/Link'
+
+import { stripMarkdown } from '~/lib/utils/markdown'
+
+import { QuillCopyButton, QuillFooterButton } from 'products/posthog_ai/frontend/api/primitives'
+
+import { maxThreadLogic } from '../../maxThreadLogic'
+import type { SuccessActionsProps } from '../SuccessActions'
+import { useAnswerRating } from '../useAnswerRating'
+
+/** The quill answer footer: the same affordances as the lemon row, drawn like a sandbox turn's footer. */
+export function QuillSuccessActions({ retriable, hideRatingAndRetry, content }: SuccessActionsProps): JSX.Element {
+ const { retryLastMessage } = useActions(maxThreadLogic)
+ const {
+ rating,
+ submitRating,
+ feedback,
+ setFeedback,
+ feedbackInputStatus,
+ closeFeedback,
+ submitFeedback,
+ traceUrl,
+ } = useAnswerRating()
+
+ return (
+ <div className="flex flex-col gap-2">
+ <ChatMessageFooter className="min-h-5 items-center gap-1 ps-0">
+ {content && <QuillCopyButton value={stripMarkdown(content)} label="Copy answer" />}
+ {!hideRatingAndRetry && rating !== 'bad' && (
+ <QuillFooterButton label="Good answer" onClick={() => submitRating('good')}>
+ {rating === 'good' ? <IconThumbsUpFilled /> : <IconThumbsUp />}
+ </QuillFooterButton>
+ )}
+ {!hideRatingAndRetry && rating !== 'good' && (
+ <QuillFooterButton label="Bad answer" onClick={() => submitRating('bad')}>
+ {rating === 'bad' ? <IconThumbsDownFilled /> : <IconThumbsDown />}
+ </QuillFooterButton>
+ )}
+ {!hideRatingAndRetry && retriable && (
+ <QuillFooterButton label="Try again" onClick={() => retryLastMessage()}>
+ <IconRefresh />
+ </QuillFooterButton>
+ )}
+ {traceUrl && (
+ <Button
+ variant="default"
+ size="icon-xs"
+ aria-label="View trace in AI observability"
+ tooltip="View trace in AI observability"
+ className="text-muted-foreground hover:text-foreground"
+ render={<LinkPrimitive to={traceUrl} />}
+ >
+ <IconEye />
+ </Button>
+ )}
+ </ChatMessageFooter>
+ {!hideRatingAndRetry && feedbackInputStatus !== 'hidden' && (
+ <div className="flex max-w-4/5 flex-col gap-2 rounded-lg border border-border p-3">
+ <div className="flex items-center gap-1">
+ <Text size="sm" weight="medium" className="grow">
+ {feedbackInputStatus === 'pending'
+ ? 'What disappointed you about the answer?'
+ : 'Thank you for your feedback!'}
+ </Text>
+ <QuillFooterButton label="Close" onClick={closeFeedback}>
+ <IconX />
+ </QuillFooterButton>
+ </div>
+ {feedbackInputStatus === 'pending' && (
+ <form
+ className="flex items-center gap-1.5"
+ onSubmit={(event) => {
+ event.preventDefault()
+ submitFeedback()
+ }}
+ >
+ <Input
+ aria-label="What disappointed you about the answer?"
+ placeholder="Help us improve PostHog AI…"
+ value={feedback}
+ onChange={(event) => setFeedback(event.target.value)}
+ autoFocus
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ disabledReason={!feedback ? 'Please type a few words!' : undefined}
+ >
+ Submit
+ </Button>
+ </form>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/max/messages/useAnswerRating.ts b/frontend/src/scenes/max/messages/useAnswerRating.ts
new file mode 100644
index 000000000000..06b340b34ac2
--- /dev/null
+++ b/frontend/src/scenes/max/messages/useAnswerRating.ts
@@ -0,0 +1,80 @@
+import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
+import { useState } from 'react'
+
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
+
+import { Region } from '~/types'
+
+import { type MessageRatingOrNull, messageRatingsLogic } from 'products/posthog_ai/frontend/api/logics'
+
+import { maxThreadLogic } from '../maxThreadLogic'
+import { useTraceId } from '../TraceIdContext'
+
+/**
+ * The rating and free-text feedback of one LangGraph answer, keyed by its trace. Both skins of
+ * `SuccessActions` read it, so the `$ai_metric` and `$ai_feedback` events stay the same whichever is on.
+ */
+export function useAnswerRating(): {
+ traceId: string | null
+ rating: MessageRatingOrNull
+ submitRating: (newRating: 'good' | 'bad') => void
+ feedback: string
+ setFeedback: (feedback: string) => void
+ feedbackInputStatus: 'hidden' | 'pending' | 'submitted'
+ closeFeedback: () => void
+ submitFeedback: () => void
+ traceUrl: string | null
+} {
+ const { traceId: logicTraceId } = useValues(maxThreadLogic)
+ const { ratingForKey } = useValues(messageRatingsLogic)
+ const { setRating } = useActions(messageRatingsLogic)
+ const { user } = useValues(userLogic)
+ const { isDev, preflight } = useValues(preflightLogic)
+ const contextTraceId = useTraceId()
+
+ // Use the context trace_id if available (for reloaded conversations), otherwise fall back to logic's traceId
+ const traceId = contextTraceId || logicTraceId
+
+ const rating = ratingForKey(traceId)
+ const [feedback, setFeedback] = useState<string>('')
+ const [feedbackInputStatus, setFeedbackInputStatus] = useState<'hidden' | 'pending' | 'submitted'>('hidden')
+
+ function submitRating(newRating: 'good' | 'bad'): void {
+ if (rating || !traceId) {
+ return // Already rated
+ }
+ setRating({ key: traceId, rating: newRating })
+ posthog.captureTraceMetric(traceId, 'quality', newRating)
+ if (newRating === 'bad') {
+ setFeedbackInputStatus('pending')
+ }
+ }
+
+ function submitFeedback(): void {
+ if (!feedback || !traceId) {
+ return // Input is empty
+ }
+ posthog.captureTraceFeedback(traceId, feedback)
+ setFeedbackInputStatus('submitted')
+ }
+
+ const traceUrl =
+ (user?.is_staff || isDev) && traceId
+ ? `${preflight?.region === Region.EU ? 'https://us.posthog.com/project/2' : ''}${urls.aiObservabilityTrace(traceId)}`
+ : null
+
+ return {
+ traceId,
+ rating,
+ submitRating,
+ feedback,
+ setFeedback,
+ feedbackInputStatus,
+ closeFeedback: () => setFeedbackInputStatus('hidden'),
+ submitFeedback,
+ traceUrl,
+ }
+}
diff --git a/frontend/src/scenes/project-homepage/ai-first/HomepageThread.tsx b/frontend/src/scenes/project-homepage/ai-first/HomepageThread.tsx
index 178fa5b78851..c8b5281db2ac 100644
--- a/frontend/src/scenes/project-homepage/ai-first/HomepageThread.tsx
+++ b/frontend/src/scenes/project-homepage/ai-first/HomepageThread.tsx
@@ -64,7 +64,7 @@ export function HomepageThread(): JSX.Element {
}
>
<ThreadAutoScroller>
- <Thread className="p-3" />
+ <Thread />
</ThreadAutoScroller>
</Suspense>
</ScrollableShadows>
diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.md
index 32027b081ee5..07a2ba66d97d 100644
--- a/products/posthog_ai/frontend/AGENTS.md
+++ b/products/posthog_ai/frontend/AGENTS.md
@@ -218,9 +218,12 @@ ingestion).
- **A shared presenter renders in both thread skins.** `ThreadView`'s `skin` prop (`'lemon' | 'quill'`) sets
`ThreadSkinContext`; `quill` is the PostHog Desktop chat layout, on behind the `phai-quill` flag (and `today-rail-nav`).
`Activity`, `ThreadRow` message and separator rows, `ThreadActivityGroup`, `RunAlertActivity`, `PullRequestCard`, `RunContext` and
- `TurnFeedbackActions` read `useQuillThread()` and dispatch to their `components/quill/` skin at the top of the
+ `TurnFeedbackActions` and `AssistantFailureMessage` read `useQuillThread()` and dispatch to their `components/quill/` skin at the top of the
component. Behavior both skins need (open state, group windowing, ratings) lives in a shared hook
(`useActivityDisclosure`, `useActivityGroup`, `useTurnRating`), never in one skin. Tool renderers never branch on skin.
+ A thread `ThreadView` does not render (Max's legacy thread) enters the skin through `QuillThreadSkin` and draws its
+ messages with the plain-prop `QuillHumanBubble` / `QuillAssistantBubble` (`api/primitives`). A story or test pins a
+ subtree's skin with `ThreadSkinOverrideContext`; product code lets the flags decide.
Grouping is the one rule that differs by skin, and `ThreadView` picks it.
The lemon thread folds every activity run (`groupThreadActivity`).
The quill thread folds only runs of two or more calls, like Desktop (`groupToolRuns`).
diff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.ts
index 292bf60c0c4e..2b1dd3720c80 100644
--- a/products/posthog_ai/frontend/api/logics.ts
+++ b/products/posthog_ai/frontend/api/logics.ts
@@ -16,6 +16,7 @@ export type { RunStreamLogicProps, RunSseStatus, RunStatus } from '../logics/run
// --- Interaction facade (follow-up / queue) ---
export { runInteractionLogic } from '../logics/runInteractionLogic'
export { messageRatingsLogic } from '../logics/messageRatingsLogic'
+export type { MessageRating, MessageRatingOrNull } from '../logics/messageRatingsLogic'
export type { RunInteractionLogicProps, QueuedMessage } from '../logics/runInteractionLogic'
// --- Thinking-message helpers ---
@@ -37,6 +38,11 @@ export { taskRunDefaultsLogic } from '../logics/taskRunDefaultsLogic'
export { tasksLogic } from '../logics/tasksLogic'
+// --- Chat skin ---
+// Here, not in ./primitives, because surfaces that load eagerly (the composer on the AI-first homepage) read it.
+export { useThreadSkin, ThreadSkinOverrideContext } from '../hooks/useThreadSkin'
+export type { ThreadSkin } from '../components/quill/quillThreadContext'
+
// --- Attached-context store + injection hook (headless) ---
// Global registry of on-screen context providers; `contextItems` is what the send paths wrap into the
// trusted/untrusted context blocks. `useAttachedContext` registers a provider for the lifetime of a mount.
diff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.ts
index bcc0afc6f65a..56fb789f638e 100644
--- a/products/posthog_ai/frontend/api/primitives.ts
+++ b/products/posthog_ai/frontend/api/primitives.ts
@@ -43,8 +43,24 @@ export { DEFAULT_SUGGESTIONS_DATA } from '../components/suggestions/suggestionsD
// atoms); `ThreadView` is the prepackaged virtualized presenter (also `Thread.Root`).
export { Thread } from '../components/Thread'
export { ThreadView } from '../components/ThreadView'
-export type { ThreadSkin } from '../components/quill/quillThreadContext'
-export { useThreadSkin } from '../hooks/useThreadSkin'
+export { useQuillThread } from '../components/quill/quillThreadContext'
+
+// The quill thread skin for a thread `ThreadView` does not render (the legacy chat behind `today-rail-nav`):
+// the skin provider, the message bubbles, and the footer affordances the bubbles share.
+export { QuillThreadSkin } from '../components/quill/QuillThreadSkin'
+export type { QuillThreadSkinProps } from '../components/quill/QuillThreadSkin'
+export {
+ QuillHumanBubble,
+ QuillAssistantBubble,
+ QuillAssistantMarkdown,
+ QUILL_ASSISTANT_PROSE_CLASS,
+} from '../components/quill/QuillMessages'
+export type { QuillHumanBubbleProps, QuillAssistantBubbleProps } from '../components/quill/QuillMessages'
+export { QuillFooterButton, QuillCopyButton } from '../components/quill/QuillFooterButton'
+export { QuillFooterTimestamp } from '../components/quill/QuillFooterTimestamp'
+export { quillCardBorderClass } from '../components/quill/quillCardBorder'
+export { MessageReveal } from '../components/MessageReveal'
+export { NotQuill } from '../components/quill/NotQuill'
export type { TurnTrailer } from '../utils/turnTrailers'
export { TurnTrailerActions } from '../components/TurnTrailerActions'
export { MessageTemplate } from '../messages/MessageTemplate'
diff --git a/products/posthog_ai/frontend/components/ActivityPrimitives.tsx b/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
index 8fff8ae975f5..63e6b62ed870 100644
--- a/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
+++ b/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
@@ -8,6 +8,7 @@ import { ActivityDisclosure } from './ActivityDisclosure'
import { ActivitySubsteps } from './ActivitySubsteps'
import type { ActivityProps, ActivityStatus } from './activityTypes'
import { QuillActivity } from './quill/QuillActivity'
+import { QuillActivityToggleSection } from './quill/QuillActivityToggleSection'
import { useQuillThread } from './quill/quillThreadContext'
import { useActivityDisclosure } from './useActivityDisclosure'
@@ -181,17 +182,18 @@ export function ActivityDetails({ children, hasIcon }: { children: React.ReactNo
)
}
-export function ActivityToggleSection({
- title,
- summary,
- tooltip,
- children,
-}: {
+export interface ActivityToggleSectionProps {
title: React.ReactNode
summary?: React.ReactNode
tooltip?: string
children: React.ReactNode
-}): JSX.Element {
+}
+
+export function ActivityToggleSection(props: ActivityToggleSectionProps): JSX.Element {
+ return useQuillThread() ? <QuillActivityToggleSection {...props} /> : <LemonActivityToggleSection {...props} />
+}
+
+function LemonActivityToggleSection({ title, summary, tooltip, children }: ActivityToggleSectionProps): JSX.Element {
const [isExpanded, setIsExpanded] = useState(false)
return (
@@ -238,11 +240,13 @@ function LemonActivity({
details = null,
children = null,
autoExpand = true,
+ defaultOpen,
onToggleDetails,
}: ActivityProps): JSX.Element {
const hasDetails = substeps.length > 0 || !!details
const { open: isDetailsExpanded, setOpen: setIsDetailsExpanded } = useActivityDisclosure({
autoExpand,
+ defaultOpen,
hasDetails,
status,
onToggleDetails,
diff --git a/products/posthog_ai/frontend/components/MessageReveal.tsx b/products/posthog_ai/frontend/components/MessageReveal.tsx
new file mode 100644
index 000000000000..0d83161bbe22
--- /dev/null
+++ b/products/posthog_ai/frontend/components/MessageReveal.tsx
@@ -0,0 +1,18 @@
+import { type ReactNode, useState } from 'react'
+
+import { TurnRevealContext } from './TurnRevealContext'
+
+/**
+ * Reveals a message's footer while the pointer is over that message. For a thread that does not group rows
+ * into turns; `ThreadView` reveals a whole turn through `TurnReveal` instead.
+ */
+export function MessageReveal({ children }: { children: ReactNode }): JSX.Element {
+ const [hovered, setHovered] = useState(false)
+ return (
+ <TurnRevealContext.Provider value={hovered}>
+ <div onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)}>
+ {children}
+ </div>
+ </TurnRevealContext.Provider>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/WidgetCard.tsx b/products/posthog_ai/frontend/components/WidgetCard.tsx
new file mode 100644
index 000000000000..33a4349a014c
--- /dev/null
+++ b/products/posthog_ai/frontend/components/WidgetCard.tsx
@@ -0,0 +1,36 @@
+import clsx from 'clsx'
+import type { ReactNode } from 'react'
+
+import { MessageTemplate } from '../messages/MessageTemplate'
+import { useQuillThread } from './quill/quillThreadContext'
+import { QuillWidgetCard } from './quill/QuillWidgetCard'
+
+export interface WidgetCardProps {
+ /** The scrolling body, e.g. a chart. Omit to show only the footer (a collapsed widget). */
+ body?: ReactNode
+ /** Height class for the body, e.g. `h-96`. The body scrolls past it. */
+ bodyHeightClassName?: string
+ footer: ReactNode
+ danger?: boolean
+}
+
+/** The frame a product widget sits in inside the thread. Each skin draws it; the widget stays skin-agnostic. */
+export function WidgetCard(props: WidgetCardProps): JSX.Element {
+ return useQuillThread() ? <QuillWidgetCard {...props} /> : <LemonWidgetCard {...props} />
+}
+
+function LemonWidgetCard({ body, bodyHeightClassName, footer, danger = false }: WidgetCardProps): JSX.Element {
+ return (
+ <MessageTemplate
+ type="ai"
+ className="w-full"
+ wrapperClassName="w-full"
+ boxClassName={clsx('flex flex-col w-full', danger && 'border-danger')}
+ >
+ <div className="flex flex-col w-full">
+ {body && <div className={clsx('flex flex-col overflow-auto', bodyHeightClassName)}>{body}</div>}
+ <div className={clsx('flex flex-col', body && 'mt-2')}>{footer}</div>
+ </div>
+ </MessageTemplate>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/activityTypes.ts b/products/posthog_ai/frontend/components/activityTypes.ts
index a56dcbd954ff..870a2d42ea3e 100644
--- a/products/posthog_ai/frontend/components/activityTypes.ts
+++ b/products/posthog_ai/frontend/components/activityTypes.ts
@@ -18,5 +18,10 @@ export interface ActivityProps {
details?: ReactNode
children?: ReactNode
autoExpand?: boolean
+ /**
+ * Opens the details by this rule instead of the status: they open while it is true and close when it turns
+ * false. A reader's toggle holds until it changes.
+ */
+ defaultOpen?: boolean
onToggleDetails?: (expanded: boolean) => void
}
diff --git a/products/posthog_ai/frontend/components/quill/NotQuill.tsx b/products/posthog_ai/frontend/components/quill/NotQuill.tsx
new file mode 100644
index 000000000000..fd5edae21078
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/NotQuill.tsx
@@ -0,0 +1,21 @@
+import type { ReactNode } from 'react'
+
+import { cn } from '@posthog/quill-primitives'
+
+import { useQuillThread } from './quillThreadContext'
+
+/**
+ * Fences a lemon component that has no quill skin yet, so PostHog's own colours survive inside the quill
+ * thread. Renders the children bare in the lemon thread.
+ */
+export function NotQuill({ children, className }: { children: ReactNode; className?: string }): JSX.Element {
+ const quill = useQuillThread()
+ if (!quill) {
+ return <>{children}</>
+ }
+ return (
+ <div data-not-quill className={cn('min-w-0 max-w-full', className)}>
+ {children}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillActivity.tsx b/products/posthog_ai/frontend/components/quill/QuillActivity.tsx
index 22522bbbec89..07fb05668a5d 100644
--- a/products/posthog_ai/frontend/components/quill/QuillActivity.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillActivity.tsx
@@ -19,10 +19,11 @@ export function QuillActivity({
details = null,
children = null,
autoExpand = true,
+ defaultOpen,
onToggleDetails,
}: ActivityProps): JSX.Element {
const hasDetails = substeps.length > 0 || !!details
- const { open, setOpen } = useActivityDisclosure({ autoExpand, hasDetails, status, onToggleDetails })
+ const { open, setOpen } = useActivityDisclosure({ autoExpand, defaultOpen, hasDetails, status, onToggleDetails })
const isRunning = status === 'in_progress'
const body = hasDetails ? (
@@ -52,12 +53,19 @@ export function QuillActivity({
wrapTitle && 'items-start [&>[data-slot=marker-icon]]:mt-[3px]'
)}
>
- <span className={cn('min-w-0 font-medium', wrapTitle ? 'whitespace-normal' : 'truncate')}>{title}</span>
+ <span
+ className={cn(
+ 'min-w-0 font-medium [&_.LemonMarkdown_p]:mb-0',
+ wrapTitle ? 'whitespace-normal' : 'truncate'
+ )}
+ >
+ {title}
+ </span>
{subtitle && <span className="min-w-0 truncate">{subtitle}</span>}
</ThreadMarker>
{/* Product widgets (charts, tables, diffs) keep PostHog's own colours inside the quill thread. */}
{children && (
- <div className="min-w-0 ps-5" data-not-quill>
+ <div className="my-2 min-w-0 ps-5" data-not-quill>
{children}
</div>
)}
diff --git a/products/posthog_ai/frontend/components/quill/QuillActivityToggleSection.tsx b/products/posthog_ai/frontend/components/quill/QuillActivityToggleSection.tsx
new file mode 100644
index 000000000000..562a3da07f78
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillActivityToggleSection.tsx
@@ -0,0 +1,31 @@
+import { useState } from 'react'
+
+import type { ActivityToggleSectionProps } from '../ActivityPrimitives'
+import { ThreadMarker } from './ThreadMarker'
+
+export function QuillActivityToggleSection({
+ title,
+ summary,
+ tooltip,
+ children,
+}: ActivityToggleSectionProps): JSX.Element {
+ const [open, setOpen] = useState(false)
+
+ return (
+ <ThreadMarker
+ shimmer={false}
+ open={open}
+ onOpenChange={setOpen}
+ body={
+ <div className="min-w-0" data-not-quill>
+ {children}
+ </div>
+ }
+ >
+ <span className="min-w-0 truncate font-medium" title={tooltip}>
+ {title}
+ </span>
+ {summary && <span className="min-w-0 truncate">{summary}</span>}
+ </ThreadMarker>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillCodeBlock.tsx b/products/posthog_ai/frontend/components/quill/QuillCodeBlock.tsx
new file mode 100644
index 000000000000..82760709c750
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillCodeBlock.tsx
@@ -0,0 +1,27 @@
+import { Card, ScrollArea, cn } from '@posthog/quill-primitives'
+
+import { CodeLine, type Language } from 'lib/components/CodeSnippet'
+
+import { quillCardBorderClass } from './quillCardBorder'
+import { QuillCopyButton } from './QuillFooterButton'
+
+export function QuillCodeBlock({ code, language }: { code: string; language: Language }): JSX.Element {
+ return (
+ <Card flush className={cn('py-0', quillCardBorderClass())}>
+ {/* The scroll runs to the card edges and shadows the cut side; the padding scrolls with the code. */}
+ <ScrollArea viewportClassName="py-2.5 pe-10 ps-3" data-not-quill>
+ <div className="w-max font-mono text-xs">
+ <CodeLine text={code} language={language} wrapLines={false} />
+ </div>
+ </ScrollArea>
+ <div className="absolute end-1.5 top-1.5 z-20">
+ <QuillCopyButton value={code} label="Copy code" />
+ </div>
+ </Card>
+ )
+}
+
+/** `LemonMarkdown`'s `renderCodeBlock` for the quill thread. Module-level, so markdown blocks stay memoized. */
+export function renderQuillCodeBlock(code: string, language: Language): JSX.Element {
+ return <QuillCodeBlock code={code} language={language} />
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillMessages.tsx b/products/posthog_ai/frontend/components/quill/QuillMessages.tsx
index ad8a6610bc40..6b1d39124299 100644
--- a/products/posthog_ai/frontend/components/quill/QuillMessages.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillMessages.tsx
@@ -1,3 +1,5 @@
+import './quillProse.scss'
+
import { memo, type ReactNode, useContext, useEffect, useRef, useState } from 'react'
import { IconChevronDown } from '@posthog/icons'
@@ -17,24 +19,11 @@ import { userMessageDisplayText } from '../../utils/userMessageDisplay'
import { HumanMessageText } from '../HumanMessageText'
import { ThreadAttachments } from '../ThreadAttachments'
import { TurnRevealContext } from '../TurnRevealContext'
-import { footerRevealClass } from './footerReveal'
+import { footerRevealProps } from './footerReveal'
+import { renderQuillCodeBlock } from './QuillCodeBlock'
import { QuillCopyButton } from './QuillFooterButton'
import { QuillFooterTimestamp } from './QuillFooterTimestamp'
-
-// A wide table scrolls sideways under a frozen first column. Cells keep a readable width and break between words.
-const ASSISTANT_TABLE_CLASS = cn(
- '[&_table]:block [&_table]:w-fit [&_table]:max-w-full [&_table]:overflow-x-auto',
- '[&_:is(th,td)]:min-w-32 [&_:is(th,td)]:[overflow-wrap:normal]',
- '[&_:is(th,td):first-child]:sticky [&_:is(th,td):first-child]:left-0 [&_:is(th,td):first-child]:z-1 [&_:is(th,td):first-child]:bg-(--background)'
-)
-
-// The copy button sits in a header bar above the code, so it never covers the first line.
-const ASSISTANT_CODE_CLASS = cn(
- '[&_.CodeSnippet_pre]:!pt-10',
- '[&_.CodeSnippet_pre]:![background:linear-gradient(var(--border),var(--border))_0_2rem/100%_1px_no-repeat,linear-gradient(var(--muted),var(--muted))_0_0/100%_2rem_no-repeat,var(--card)]',
- '[&_.CodeSnippet>div:first-child]:!top-1.5 [&_.CodeSnippet>div:first-child]:!right-1.5 [&_.CodeSnippet>div:first-child]:!bg-transparent',
- '[&_.CodeSnippet>div:first-child_svg]:!text-(--muted-foreground)'
-)
+import { QUILL_MARKDOWN_COMPONENTS } from './quillMarkdownComponents'
// A checklist starts at the text edge like a paragraph, and its read-only boxes draw at full strength. Inside quill the checkbox's lemon accent resolves to nothing, so a ticked box takes quill's primary colour.
const ASSISTANT_TASK_LIST_CLASS = cn(
@@ -42,6 +31,9 @@ const ASSISTANT_TASK_LIST_CLASS = cn(
'[&_.LemonCheckbox_label]:[--box-color:var(--primary)] [&_.LemonCheckbox_svg]:!opacity-100'
)
+/** The prose rules every assistant markdown block in the quill thread shares. */
+export const QUILL_ASSISTANT_PROSE_CLASS = cn('QuillProse', ASSISTANT_TASK_LIST_CLASS)
+
/**
* Clamps a user bubble to five lines with a Show more toggle. Overflow depends on wrapping width, so it
* is measured against the clamped height and re-measured on resize, and the toggle only appears when the
@@ -88,50 +80,108 @@ function ClampedContent({ children }: { children: ReactNode }): JSX.Element {
)
}
-export const QuillHumanMessage = memo(function QuillHumanMessage({ item }: { item: ThreadItem }): JSX.Element {
- const text = userMessageDisplayText(item.text ?? '')
+export interface QuillHumanBubbleProps {
+ /** Plain text the footer's copy button puts on the clipboard. Omit to hide the button. */
+ copyText?: string
+ /** When the message was sent, in milliseconds. */
+ startedAt?: number
+ /** Rendered above the bubble, right-aligned: attachments, a context summary. */
+ before?: ReactNode
+ className?: string
+ children: ReactNode
+}
+
+/**
+ * A user turn in the quill thread: a filled bubble on the end side with a hover footer (time, copy). Plain
+ * props, so a thread that is not fed by `runStreamLogic` renders the same bubble.
+ */
+export function QuillHumanBubble({
+ copyText,
+ startedAt,
+ before,
+ className,
+ children,
+}: QuillHumanBubbleProps): JSX.Element {
const revealed = useContext(TurnRevealContext)
- const screenshotNames = commentScreenshotNames(item.text ?? '')
return (
- <ChatMessage align="end" data-attr="posthog-ai-human-message">
+ <ChatMessage align="end" className={className} data-attr="posthog-ai-human-message">
<ChatMessageContent className="gap-1">
- {item.attachments && (
- <div className="self-end">
- <ThreadAttachments attachments={item.attachments} badgeNames={screenshotNames} />
- </div>
- )}
+ {before && <div className="self-end">{before}</div>}
<ChatBubble align="end" className="rounded-lg">
<ChatBubbleContent>
- <ClampedContent>
- <HumanMessageText text={item.text ?? ''} id={item.id} attachments={item.attachments} />
- </ClampedContent>
+ <ClampedContent>{children}</ClampedContent>
</ChatBubbleContent>
</ChatBubble>
- <ChatMessageFooter className={cn('min-h-5 items-center gap-1', footerRevealClass(revealed))}>
- {item.startedAt !== undefined && <QuillFooterTimestamp time={item.startedAt} />}
- {text && (
- <QuillCopyButton value={text} label="Copy message" dataAttr="posthog-ai-human-message-copy" />
- )}
- </ChatMessageFooter>
+ {(startedAt !== undefined || copyText) && (
+ <ChatMessageFooter {...footerRevealProps(revealed, 'items-center gap-1', { reserveSpace: true })}>
+ {startedAt !== undefined && <QuillFooterTimestamp time={startedAt} />}
+ {copyText && (
+ <QuillCopyButton
+ value={copyText}
+ label="Copy message"
+ dataAttr="posthog-ai-human-message-copy"
+ />
+ )}
+ </ChatMessageFooter>
+ )}
</ChatMessageContent>
</ChatMessage>
)
-})
+}
-export const QuillAssistantMessage = memo(function QuillAssistantMessage({ item }: { item: ThreadItem }): JSX.Element {
+export interface QuillAssistantBubbleProps {
+ className?: string
+ children: ReactNode
+}
+
+/** An assistant turn in the quill thread: ghost prose, full width, no frame. */
+export function QuillAssistantBubble({ className, children }: QuillAssistantBubbleProps): JSX.Element {
return (
- <ChatMessage align="start">
+ <ChatMessage align="start" className={className}>
<ChatMessageContent className="gap-1">
<ChatBubble variant="ghost">
- <ChatBubbleContent>
- <MarkdownMessage
- content={item.text ?? ''}
- id={item.id}
- className={cn(ASSISTANT_TABLE_CLASS, ASSISTANT_CODE_CLASS, ASSISTANT_TASK_LIST_CLASS)}
- />
- </ChatBubbleContent>
+ <ChatBubbleContent>{children}</ChatBubbleContent>
</ChatBubble>
</ChatMessageContent>
</ChatMessage>
)
+}
+
+// Sets the chat message text size itself, so it reads the same inside a 13px quill card as in a bubble.
+export function QuillAssistantMarkdown({ content, id }: { content: string; id: string }): JSX.Element {
+ return (
+ <MarkdownMessage
+ content={content}
+ id={id}
+ className={cn('text-[length:var(--text-sm,0.875rem)] leading-[1.625]', QUILL_ASSISTANT_PROSE_CLASS)}
+ components={QUILL_MARKDOWN_COMPONENTS}
+ renderCodeBlock={renderQuillCodeBlock}
+ />
+ )
+}
+
+export const QuillHumanMessage = memo(function QuillHumanMessage({ item }: { item: ThreadItem }): JSX.Element {
+ const text = userMessageDisplayText(item.text ?? '')
+ const screenshotNames = commentScreenshotNames(item.text ?? '')
+ return (
+ <QuillHumanBubble
+ copyText={text || undefined}
+ startedAt={item.startedAt}
+ before={
+ item.attachments ? (
+ <ThreadAttachments attachments={item.attachments} badgeNames={screenshotNames} />
+ ) : undefined
+ }
+ >
+ <HumanMessageText text={item.text ?? ''} id={item.id} attachments={item.attachments} />
+ </QuillHumanBubble>
+ )
+})
+
+export const QuillAssistantMessage = memo(function QuillAssistantMessage({ item }: { item: ThreadItem }): JSX.Element {
+ return (
+ <QuillAssistantBubble>
+ <QuillAssistantMarkdown content={item.text ?? ''} id={item.id} />
+ </QuillAssistantBubble>
+ )
})
diff --git a/products/posthog_ai/frontend/components/quill/QuillThreadSkin.tsx b/products/posthog_ai/frontend/components/quill/QuillThreadSkin.tsx
new file mode 100644
index 000000000000..2255322031e9
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillThreadSkin.tsx
@@ -0,0 +1,25 @@
+import type { ReactNode } from 'react'
+
+import { cn } from '@posthog/quill-primitives'
+
+import { ThreadSkinContext } from './quillThreadContext'
+
+export interface QuillThreadSkinProps {
+ className?: string
+ children: ReactNode
+}
+
+/**
+ * Puts a thread that `ThreadView` does not render into the quill skin: every shared presenter below
+ * (`Activity`, `ReasoningAnswer`, `AssistantFailureMessage`, `TurnFeedbackActions`) picks its quill half, and
+ * the `data-quill` wrapper scopes quill's tokens and sets the text color once, as `ThreadView` does.
+ */
+export function QuillThreadSkin({ className, children }: QuillThreadSkinProps): JSX.Element {
+ return (
+ <ThreadSkinContext.Provider value="quill">
+ <div data-quill className={cn('flex flex-col gap-4 text-[var(--foreground)]', className)}>
+ {children}
+ </div>
+ </ThreadSkinContext.Provider>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/QuillTurnFeedbackActions.tsx b/products/posthog_ai/frontend/components/quill/QuillTurnFeedbackActions.tsx
index 4fa0faf4491c..072b97611fcf 100644
--- a/products/posthog_ai/frontend/components/quill/QuillTurnFeedbackActions.tsx
+++ b/products/posthog_ai/frontend/components/quill/QuillTurnFeedbackActions.tsx
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { useContext, useId } from 'react'
import { IconThumbsDown, IconThumbsDownFilled, IconThumbsUp, IconThumbsUpFilled, IconX } from '@posthog/icons'
-import { Button, ChatMessageFooter, Input, Text, cn } from '@posthog/quill-primitives'
+import { Button, ChatMessageFooter, Input, Text } from '@posthog/quill-primitives'
import { stripMarkdown } from 'lib/utils/markdown'
@@ -11,7 +11,7 @@ import { todayShellLogic } from '~/layout/today/todayShellLogic'
import type { TurnFeedbackActionsProps } from '../turnFeedbackTypes'
import { TurnRevealContext } from '../TurnRevealContext'
import { useTurnRating } from '../useTurnRating'
-import { footerRevealClass } from './footerReveal'
+import { footerRevealProps } from './footerReveal'
import { QuillCopyButton, QuillFooterButton } from './QuillFooterButton'
import { QuillFooterTimestamp } from './QuillFooterTimestamp'
@@ -32,9 +32,9 @@ export function QuillTurnFeedbackActions({
return (
<div className="flex flex-col gap-2">
<ChatMessageFooter
- className={cn(
- 'min-h-5 items-center gap-1 ps-0',
- footerRevealClass(!!rating || turnHovered || (todayRailEnabled && phoneLayout))
+ {...footerRevealProps(
+ !!rating || turnHovered || (todayRailEnabled && phoneLayout),
+ 'items-center gap-1 ps-0'
)}
>
{timestamp !== undefined && <QuillFooterTimestamp time={timestamp} />}
diff --git a/products/posthog_ai/frontend/components/quill/QuillWidgetCard.tsx b/products/posthog_ai/frontend/components/quill/QuillWidgetCard.tsx
new file mode 100644
index 000000000000..52ac51e31c70
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/QuillWidgetCard.tsx
@@ -0,0 +1,23 @@
+import { Card, CardContent, CardFooter, ScrollArea, cn } from '@posthog/quill-primitives'
+
+import type { WidgetCardProps } from '../WidgetCard'
+import { quillCardBorderClass } from './quillCardBorder'
+
+export function QuillWidgetCard({ body, bodyHeightClassName, footer, danger = false }: WidgetCardProps): JSX.Element {
+ return (
+ <Card size="sm" flush className={cn('py-0', quillCardBorderClass(danger))}>
+ {body && (
+ // Product widgets keep PostHog's own colours inside the quill thread.
+ <CardContent data-not-quill>
+ {/* The viewport inherits a `max-h-*` cap from the root, or it outgrows the root and scrolls nothing. */}
+ <ScrollArea className={bodyHeightClassName} viewportClassName="max-h-[inherit]">
+ {body}
+ </ScrollArea>
+ </CardContent>
+ )}
+ <CardFooter data-not-quill className={cn('flex-col items-stretch gap-2 py-2', !body && 'border-t-0')}>
+ {footer}
+ </CardFooter>
+ </Card>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/footerReveal.scss b/products/posthog_ai/frontend/components/quill/footerReveal.scss
new file mode 100644
index 000000000000..7178ee639e48
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/footerReveal.scss
@@ -0,0 +1,30 @@
+// A message footer that fades in on hover. It takes no space while hidden, unless it has `data-reserve-space`. It takes pointer input only once
+// the fade ends, so a pointer that passes over it on the way in does not open the timestamp popover early.
+.QuillFooterReveal {
+ --footer-fade: 150ms;
+
+ min-height: 1.25rem;
+ transition:
+ opacity var(--footer-fade),
+ pointer-events 0s var(--footer-fade) allow-discrete;
+
+ // Only a device that can hover can reveal it, so only there does it hide.
+ @media (hover: hover) {
+ &:not([data-revealed], :focus-within) {
+ pointer-events: none;
+ opacity: 0;
+ transition: opacity var(--footer-fade);
+
+ &:not([data-reserve-space]) {
+ height: 0;
+ min-height: 0;
+ overflow: hidden;
+ }
+ }
+ }
+
+ // Always shown on a touch screen, so it needs room before the next message.
+ @media (hover: none) {
+ margin-bottom: 0.75rem;
+ }
+}
diff --git a/products/posthog_ai/frontend/components/quill/footerReveal.ts b/products/posthog_ai/frontend/components/quill/footerReveal.ts
index b2456d67ecda..dfa6ed73154c 100644
--- a/products/posthog_ai/frontend/components/quill/footerReveal.ts
+++ b/products/posthog_ai/frontend/components/quill/footerReveal.ts
@@ -1,9 +1,16 @@
-/**
- * Classes for a message footer that fades in on hover. The footer takes pointer input only once the fade
- * ends, so a pointer that passes over it on the way in does not open the timestamp popover early.
- */
-export function footerRevealClass(revealed: boolean): string {
- return revealed
- ? '[--footer-fade:150ms] opacity-100 [transition:opacity_var(--footer-fade),pointer-events_0s_var(--footer-fade)_allow-discrete]'
- : '[--footer-fade:150ms] pointer-events-none opacity-0 [transition:opacity_var(--footer-fade)] focus-within:pointer-events-auto focus-within:opacity-100'
+import './footerReveal.scss'
+
+import { cn } from '@posthog/quill-primitives'
+
+/** Props for a message footer that shows while its turn is hovered (see `footerReveal.scss`). */
+export function footerRevealProps(
+ revealed: boolean,
+ className?: string,
+ { reserveSpace = false }: { reserveSpace?: boolean } = {}
+): { className: string; 'data-revealed'?: true; 'data-reserve-space'?: true } {
+ return {
+ className: cn('QuillFooterReveal', className),
+ 'data-revealed': revealed || undefined,
+ 'data-reserve-space': reserveSpace || undefined,
+ }
}
diff --git a/products/posthog_ai/frontend/components/quill/quillCardBorder.ts b/products/posthog_ai/frontend/components/quill/quillCardBorder.ts
new file mode 100644
index 000000000000..cf1fb38ace64
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/quillCardBorder.ts
@@ -0,0 +1,15 @@
+import { cn } from '@posthog/quill-primitives'
+
+/**
+ * Classes that draw a quill card's border as an inset ring on an overlay above its content. The card's own
+ * outer ring is clipped by the chat bubble's overflow, and positioned content such as a chart paints over it.
+ */
+export function quillCardBorderClass(danger = false): string {
+ return cn(
+ 'relative shadow-none',
+ 'after:pointer-events-none after:absolute after:inset-0 after:z-10 after:rounded-[inherit]',
+ danger
+ ? 'after:shadow-[inset_0_0_0_1px_var(--destructive-foreground)]'
+ : 'after:shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--foreground)_10%,transparent)]'
+ )
+}
diff --git a/products/posthog_ai/frontend/components/quill/quillMarkdownComponents.tsx b/products/posthog_ai/frontend/components/quill/quillMarkdownComponents.tsx
new file mode 100644
index 000000000000..4272beb4fba5
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/quillMarkdownComponents.tsx
@@ -0,0 +1,39 @@
+import {
+ Card,
+ CardContent,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ cn,
+} from '@posthog/quill-primitives'
+
+import type { LemonMarkdownComponents } from 'lib/lemon-ui/LemonMarkdown'
+
+import { quillCardBorderClass } from './quillCardBorder'
+
+type CellAlign = 'left' | 'center' | 'right'
+
+// GFM writes a column's alignment onto each cell; quill takes it as a prop instead of an inline style.
+function cellAlign(node: unknown): CellAlign | undefined {
+ const align = (node as { properties?: { align?: unknown } } | undefined)?.properties?.align
+ return align === 'left' || align === 'center' || align === 'right' ? align : undefined
+}
+
+export const QUILL_MARKDOWN_COMPONENTS: LemonMarkdownComponents = {
+ table: ({ node: _node, children }) => (
+ // No header, so no header gap on top.
+ <Card size="sm" flush className={cn('pt-0', quillCardBorderClass())}>
+ <CardContent>
+ <Table size="sm">{children}</Table>
+ </CardContent>
+ </Card>
+ ),
+ thead: ({ node: _node, children }) => <TableHeader>{children}</TableHeader>,
+ tbody: ({ node: _node, children }) => <TableBody>{children}</TableBody>,
+ tr: ({ node: _node, children }) => <TableRow>{children}</TableRow>,
+ th: ({ node, children }) => <TableHead align={cellAlign(node)}>{children}</TableHead>,
+ td: ({ node, children }) => <TableCell align={cellAlign(node)}>{children}</TableCell>,
+}
diff --git a/products/posthog_ai/frontend/components/quill/quillProse.scss b/products/posthog_ai/frontend/components/quill/quillProse.scss
new file mode 100644
index 000000000000..0b1701f8aee3
--- /dev/null
+++ b/products/posthog_ai/frontend/components/quill/quillProse.scss
@@ -0,0 +1,41 @@
+// Vertical rhythm for assistant markdown in the quill thread. Each block sets only its top margin, so the
+// space between two blocks comes from one rule and does not depend on collapsing margins.
+// `.LemonMarkdown.QuillProse` outranks the base `.LemonMarkdown` margins without `!important`.
+.LemonMarkdown.QuillProse {
+ --quill-prose-block: 0.75rem;
+ --quill-prose-section: 1.5rem;
+ --quill-prose-card: 1rem;
+ --quill-prose-tight: 0.5rem;
+
+ > * {
+ margin: 0;
+ }
+
+ > * + * {
+ margin-top: var(--quill-prose-block);
+ }
+
+ // A card has a visible edge, so it needs more room than a line of text to read as a separate block.
+ // `:where` keeps these rules below the heading rules, so a heading still binds to the card under it.
+ > :where([data-slot='card']) + *,
+ > * + :where([data-slot='card']) {
+ margin-top: var(--quill-prose-card);
+ }
+
+ // A heading opens a section: wide space above it, and tight space below so it stays with its content.
+ > * + :is(h1, h2, h3, h4, h5, h6) {
+ margin-top: var(--quill-prose-section);
+ }
+
+ > :is(h1, h2, h3, h4, h5, h6) + * {
+ margin-top: var(--quill-prose-tight);
+ }
+
+ > hr {
+ margin-block: var(--quill-prose-section);
+ }
+
+ li + li {
+ margin-top: 0.25rem;
+ }
+}
diff --git a/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.test.tsx b/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.test.tsx
index e854ac2ff019..5b4c3c4a3b1e 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.test.tsx
+++ b/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.test.tsx
@@ -53,7 +53,7 @@ describe('VisualizationWidget', () => {
}
render(
<Provider>
- <VisualizationWidget content={content} isCollapsed embedded />
+ <VisualizationWidget content={content} isCollapsed />
</Provider>
)
expect(detail).not.toHaveBeenCalled()
diff --git a/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsx
index 0656795fd946..22158cfa4e62 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsx
+++ b/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsx
@@ -1,4 +1,3 @@
-import clsx from 'clsx'
import { useActions } from 'kea'
import React, { useMemo, useState } from 'react'
@@ -26,8 +25,8 @@ import { QueryContext } from '~/queries/types'
import { isFunnelsQuery, isHogQLQuery, isInsightVizNode } from '~/queries/utils'
import { InsightShortId } from '~/types'
-import { MessageTemplate } from '../../../messages/MessageTemplate'
import { visualizationTypeToQuery } from '../../../utils/visualizationQuery'
+import { WidgetCard } from '../../WidgetCard'
const QUERY_CONTEXT_POSTHOG_AI: QueryContext = { limitContext: 'posthog_ai' } as const
@@ -42,8 +41,6 @@ export interface VisualizationWidgetProps {
onCollapsedChange?: (isCollapsed: boolean) => void
/** Extra buttons rendered in the actions row before the CTA. */
extraActions?: React.ReactNode
- /** Render only the widget body, for use inside an existing activity/message shell. */
- embedded?: boolean
}
/** Fallback CTA for ephemeral visualizations: open the rendered query as a new unsaved insight. */
@@ -77,7 +74,6 @@ export const VisualizationWidget = React.memo(function VisualizationWidget({
isCollapsed: controlledCollapsed,
onCollapsedChange,
extraActions,
- embedded = false,
}: VisualizationWidgetProps): JSX.Element {
const { loadCohortsByIds } = useActions(cohortsModel)
const [isSummaryShown, setIsSummaryShown] = useState(false)
@@ -96,19 +92,19 @@ export const VisualizationWidget = React.memo(function VisualizationWidget({
// Get the raw query for height calculation
const rawQuery = content.query
- const renderedContent = !query ? (
+ const chart =
+ query && !isCollapsed ? <Query query={query} readOnly embedded context={QUERY_CONTEXT_POSTHOG_AI} /> : null
+ // A funnel sizes itself, so it only gets a cap; a chart drawn on a canvas needs a fixed height.
+ const chartHeightClassName = isFunnelsQuery(rawQuery) ? 'max-h-[580px]' : 'h-96'
+
+ const footer = !query ? (
<div className="flex items-center gap-1.5">
<IconWarning className="text-xl text-danger" />
<span>Failed to load visualization</span>
</div>
) : (
- <div className="flex flex-col w-full">
- {!isCollapsed && (
- <div className={clsx('flex flex-col overflow-auto', isFunnelsQuery(rawQuery) ? 'h-[580px]' : 'h-96')}>
- <Query query={query} readOnly embedded context={QUERY_CONTEXT_POSTHOG_AI} />
- </div>
- )}
- <div className={clsx('flex items-center justify-between', !isCollapsed && 'mt-2')}>
+ <>
+ <div className="flex items-center justify-between">
{isInsightVizNode(query) ? (
<div className="flex items-center gap-1.5">
<LemonButton
@@ -164,29 +160,8 @@ export const VisualizationWidget = React.memo(function VisualizationWidget({
)}
</>
)}
- </div>
+ </>
)
- if (embedded) {
- return renderedContent
- }
-
- if (!query) {
- return (
- <MessageTemplate
- type="ai"
- className="w-full"
- wrapperClassName="w-full"
- boxClassName="flex flex-col w-full border-danger"
- >
- {renderedContent}
- </MessageTemplate>
- )
- }
-
- return (
- <MessageTemplate type="ai" className="w-full" wrapperClassName="w-full" boxClassName="flex flex-col w-full">
- {renderedContent}
- </MessageTemplate>
- )
+ return <WidgetCard body={chart} bodyHeightClassName={chartHeightClassName} footer={footer} danger={!query} />
})
diff --git a/products/posthog_ai/frontend/components/useActivityDisclosure.ts b/products/posthog_ai/frontend/components/useActivityDisclosure.ts
index 8d1936c122e4..8d5f3d466e62 100644
--- a/products/posthog_ai/frontend/components/useActivityDisclosure.ts
+++ b/products/posthog_ai/frontend/components/useActivityDisclosure.ts
@@ -4,20 +4,23 @@ import type { ActivityStatus } from './activityTypes'
/**
* Open state for an activity's details, shared by every skin. With `autoExpand`, details open while the
- * step runs and close once it settles; a reader's toggle holds until the status changes that rule.
+ * step runs and close once it settles; `defaultOpen` replaces that rule. A reader's toggle holds until the
+ * rule's result changes.
*/
export function useActivityDisclosure({
autoExpand,
+ defaultOpen,
hasDetails,
status,
onToggleDetails,
}: {
autoExpand: boolean
+ defaultOpen?: boolean
hasDetails: boolean
status: ActivityStatus
onToggleDetails?: (expanded: boolean) => void
}): { open: boolean; setOpen: (open: boolean) => void } {
- const shouldExpand = autoExpand && hasDetails && status !== 'completed' && status !== 'failed'
+ const shouldExpand = hasDetails && (defaultOpen ?? (autoExpand && status !== 'completed' && status !== 'failed'))
const [open, setOpenState] = useState(shouldExpand)
useLayoutEffect(() => {
setOpenState(shouldExpand)
diff --git a/products/posthog_ai/frontend/hooks/useThreadSkin.ts b/products/posthog_ai/frontend/hooks/useThreadSkin.ts
index 862c9b43d8a0..cdec8c63d0ac 100644
--- a/products/posthog_ai/frontend/hooks/useThreadSkin.ts
+++ b/products/posthog_ai/frontend/hooks/useThreadSkin.ts
@@ -1,13 +1,25 @@
+import { createContext, useContext } from 'react'
+
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import type { ThreadSkin } from '../components/quill/quillThreadContext'
+/**
+ * Pins the skin for a subtree, whatever the flags say. A story or a test renders the lemon and the quill
+ * chat side by side with it; product code leaves it unset and lets the flags decide.
+ */
+export const ThreadSkinOverrideContext = createContext<ThreadSkin | null>(null)
+
/**
* The skin for every PostHog AI chat surface: the thread, the run composer and its pickers. The quill chat
* is part of the quill web redesign, so `today-rail-nav` turns it on as well.
*/
export function useThreadSkin(): ThreadSkin {
+ const override = useContext(ThreadSkinOverrideContext)
const phaiQuill = useFeatureFlag('PHAI_QUILL')
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
+ if (override) {
+ return override
+ }
return phaiQuill || todayRailNav ? 'quill' : 'lemon'
}
diff --git a/products/posthog_ai/frontend/messages/AssistantFailureMessage.test.tsx b/products/posthog_ai/frontend/messages/AssistantFailureMessage.test.tsx
index 3f29289fcd59..e718efc2679a 100644
--- a/products/posthog_ai/frontend/messages/AssistantFailureMessage.test.tsx
+++ b/products/posthog_ai/frontend/messages/AssistantFailureMessage.test.tsx
@@ -1,26 +1,32 @@
import '@testing-library/jest-dom'
import { cleanup, render, screen } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ThreadSkinContext } from '../components/quill/quillThreadContext'
import { AssistantFailureMessage } from './AssistantFailureMessage'
-describe('AssistantFailureMessage', () => {
+// The failure bubble has a skin per thread, and both must keep the message and the action visible.
+describe.each([
+ ['lemon', (ui: ReactElement) => ui],
+ ['quill', (ui: ReactElement) => <ThreadSkinContext.Provider value="quill">{ui}</ThreadSkinContext.Provider>],
+])('AssistantFailureMessage (%s)', (_skin, wrap) => {
afterEach(cleanup)
it('renders the supplied failure message', () => {
- render(<AssistantFailureMessage id="failure-1" content="Internal error: Failed to authenticate" />)
+ render(wrap(<AssistantFailureMessage id="failure-1" content="Internal error: Failed to authenticate" />))
expect(screen.getByText('Internal error: Failed to authenticate')).toBeInTheDocument()
})
it('falls back when no failure message is supplied', () => {
- render(<AssistantFailureMessage id="failure-1" content={null} />)
+ render(wrap(<AssistantFailureMessage id="failure-1" content={null} />))
expect(screen.getByText('*PostHog AI has failed to generate an answer. Please try again.*')).toBeInTheDocument()
})
it('renders an optional action', () => {
- render(<AssistantFailureMessage id="failure-1" content="Failed" action={<button>Try again</button>} />)
+ render(wrap(<AssistantFailureMessage id="failure-1" content="Failed" action={<button>Try again</button>} />))
expect(screen.getByText('Try again')).toBeInTheDocument()
})
diff --git a/products/posthog_ai/frontend/messages/AssistantFailureMessage.tsx b/products/posthog_ai/frontend/messages/AssistantFailureMessage.tsx
index 0dace8304297..1343eb4eb8c4 100644
--- a/products/posthog_ai/frontend/messages/AssistantFailureMessage.tsx
+++ b/products/posthog_ai/frontend/messages/AssistantFailureMessage.tsx
@@ -1,5 +1,10 @@
import React from 'react'
+import { IconWarning } from '@posthog/icons'
+import { ChatBubble, ChatBubbleContent, ChatMessage, ChatMessageContent } from '@posthog/quill-primitives'
+
+import { QuillAssistantMarkdown } from '../components/quill/QuillMessages'
+import { useQuillThread } from '../components/quill/quillThreadContext'
import { MarkdownMessage } from './MarkdownMessage'
import { MessageTemplate } from './MessageTemplate'
@@ -13,6 +18,22 @@ export interface AssistantFailureMessageProps {
export const AssistantFailureMessage = React.forwardRef<HTMLDivElement, AssistantFailureMessageProps>(
function AssistantFailureMessage({ id, content, action }, ref) {
+ const quill = useQuillThread()
+ if (quill) {
+ return (
+ <ChatMessage align="start" ref={ref} data-message-type="ai">
+ <ChatMessageContent className="gap-1">
+ <ChatBubble variant="destructive">
+ <ChatBubbleContent className="flex items-start gap-2">
+ <IconWarning className="mt-1 size-4 shrink-0" />
+ <QuillAssistantMarkdown content={content || DEFAULT_FAILURE_MESSAGE} id={id} />
+ </ChatBubbleContent>
+ </ChatBubble>
+ {action}
+ </ChatMessageContent>
+ </ChatMessage>
+ )
+ }
return (
<MessageTemplate type="ai" boxClassName="border-danger" ref={ref} action={action}>
<MarkdownMessage content={content || DEFAULT_FAILURE_MESSAGE} id={id} />
diff --git a/products/posthog_ai/frontend/messages/MarkdownMessage.tsx b/products/posthog_ai/frontend/messages/MarkdownMessage.tsx
index bdcae0052c81..8de25768e207 100644
--- a/products/posthog_ai/frontend/messages/MarkdownMessage.tsx
+++ b/products/posthog_ai/frontend/messages/MarkdownMessage.tsx
@@ -2,7 +2,7 @@ import { marked } from 'marked'
import { memo, useMemo } from 'react'
import { rewriteAgentObjectTags } from 'lib/components/AgentObjectTags/rewriteAgentObjectTags'
-import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+import { LemonMarkdown, type LemonMarkdownComponents, type LemonMarkdownProps } from 'lib/lemon-ui/LemonMarkdown'
import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'
import { urls } from 'scenes/urls'
@@ -28,10 +28,16 @@ export const MarkdownMessage = memo(function MarkdownMessage({
content,
id,
className,
+ components,
+ renderCodeBlock,
}: {
content: string
id: string
className?: string
+ /** Element renderers that replace LemonMarkdown's own. Pass a stable (module-level) object. */
+ components?: LemonMarkdownComponents
+ /** Renderer for fenced code blocks. Pass a stable (module-level) function. */
+ renderCodeBlock?: LemonMarkdownProps['renderCodeBlock']
}): JSX.Element {
// The team id is a memo dependency so a project switch re-points existing links.
const teamId = getCurrentTeamIdOrNone()
@@ -39,7 +45,13 @@ export const MarkdownMessage = memo(function MarkdownMessage({
return (
<LemonMarkdown.Container className={className}>
{blocks.map((block, index) => (
- <LemonMarkdown.Renderer key={`${id}-block_${index}`}>{block}</LemonMarkdown.Renderer>
+ <LemonMarkdown.Renderer
+ key={`${id}-block_${index}`}
+ components={components}
+ renderCodeBlock={renderCodeBlock}
+ >
+ {block}
+ </LemonMarkdown.Renderer>
))}
</LemonMarkdown.Container>
)
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
index 407270f5b944..12cb970cf8b5 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
@@ -7,11 +7,11 @@ import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentP
import { urls } from 'scenes/urls'
import { Composer } from 'products/posthog_ai/frontend/api/composer'
+import { useThreadSkin } from 'products/posthog_ai/frontend/api/logics'
import {
DEFAULT_SUGGESTIONS_DATA,
type SuggestionItem,
Suggestions,
- useThreadSkin,
Welcome,
} from 'products/posthog_ai/frontend/api/primitives'
import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
index d26a930165c6..78aa77c4e369 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
@@ -11,8 +11,12 @@ import { userLogic } from 'scenes/userLogic'
import { todayShellLogic } from '~/layout/today/todayShellLogic'
import { Composer } from 'products/posthog_ai/frontend/api/composer'
-import { runInteractionLogic, type RunInteractionLogicProps } from 'products/posthog_ai/frontend/api/logics'
-import { QueuedMessageList, useThreadSkin } from 'products/posthog_ai/frontend/api/primitives'
+import {
+ runInteractionLogic,
+ type RunInteractionLogicProps,
+ useThreadSkin,
+} from 'products/posthog_ai/frontend/api/logics'
+import { QueuedMessageList } from 'products/posthog_ai/frontend/api/primitives'
import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'
import { runSlashCommandsLogic } from 'products/posthog_ai/frontend/logics/runSlashCommandsLogic'
import { taskRunDefaultsLogic } from 'products/posthog_ai/frontend/logics/taskRunDefaultsLogic'