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(ai): combine chat and task navigation (#98581)

Chris Volzer215b72dc4b5e
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index fe4cfc14018b..30b5a8f66128 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -113,6 +113,12 @@ The handoff removes `ask` from the current browser history entry while preservin
Changing the panel state or remounting the view therefore does not submit the prompt again.
Without organization-level AI data-processing consent, the prompt only prefills the composer.
+## Task navigation
+
+Task links in shared AI history open `/ai?task=<task-id>` and render the task runner, regardless of the saved chat view preference.
+The task stays selected on reload and when navigating back or forward.
+Existing `/tasks/<task-id>` links still open the standalone runner.
+
## Fine-grained access tokens
Every sandboxed agent gets a scoped OAuth access token that controls what PostHog resources it can access.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d768a2b441d6..d09dd5a1e04c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9860,66 +9860,74 @@ snapshots:
hash: v1.k794b7964.1234ce11c2b03ff3e0a4a41eda4da0c033361aaa0a4ae31d00f2ee966a216270.6jMMIFd43bSq7kmGgVrwQOlvv2XXBE4ciOdoBFUjqSM
scenes-app-surveys-surveyresponsekeysreference--webhook--light:
hash: v1.k794b7964.c2676130771cba15a3b1cd5b9c511f42fce4d3345f761a1c112e8f12ca1dfcc0.N4q5DAtNnKGEGrtCJv-vQYe5KOhn7D9Ocu6IRBkp9yE
+ scenes-app-tasks--ai-task-selected--dark:
+ hash: v1.k794b7964.d4169f92563f1a61588ba823f6be7392267558bfbb86124b6e53ec9b18056418.iKEx9vQEw72HqX58dUDsyxmsH-qtEXIeb6MqQMByB8Y
+ scenes-app-tasks--ai-task-selected--light:
+ hash: v1.k794b7964.e0a6374da2da7262d08d1992bea3898259837679f5676f4330400d27559ac5d2.68EwF3z0RoO2K9aUGYr1XiQ_dRiNa6XtreqmKjXsfVg
+ scenes-app-tasks--composer--dark:
+ hash: v1.k794b7964.7eef9b267cd20f210bf5f20c395acbd04f412df23a4e5591fb5513ffd82334e8.IPg6Br9tL3KbGN-SdYcgmmoT8ftICA72iN4UafDeT_8
+ scenes-app-tasks--composer--light:
+ hash: v1.k794b7964.d38ed6e0fe09c3d165585b63808152234f78ce9eb93460b3f7a2a7ab7dfaf918.5bFTaA6wI2Yyb7NxkwOrzmnvzlONa0kan4caNEiXejI
scenes-app-tasks--empty--dark:
- hash: v1.k794b7964.d112f05471a711379792d3010c0c6471fe0c24765510d4b9f00ebd1f858e4016.6JBRci6NsHBPP7tehgmjAOGfr8AMPqfwMs8Mc8DWWzA
+ hash: v1.k794b7964.d4169f92563f1a61588ba823f6be7392267558bfbb86124b6e53ec9b18056418.IhcjWqVnjpPpoEiXclkDX1Llo8JrdqTdGLLTp4oHL8w
scenes-app-tasks--empty--light:
- hash: v1.k794b7964.316e58fe1fff68b296e39a2cbbb421c2b31390f3f37fec1076dc0495b33337aa.OS9VZZebl4dW3lbGSc_kQ5V4_6czCfxWl5ds7nvB6vI
+ hash: v1.k794b7964.e0a6374da2da7262d08d1992bea3898259837679f5676f4330400d27559ac5d2.TQVEDnDzgXco7d3Qk1T8xxhEqIWEK0pe1L9cX8tYL9U
scenes-app-tasks--list-load-error--dark:
- hash: v1.k794b7964.d53b40f13aeb3c390918ccf1fd2e4767bba43a856661a7201e9a4ab6a1855599.KPJeYWi038_pPOYak6FYunfOe_YpjSUL0t0nHchQco0
+ hash: v1.k794b7964.d4169f92563f1a61588ba823f6be7392267558bfbb86124b6e53ec9b18056418.IHrn0ouFkC-2WCWNZyLjoh-Nmi_o_m7tRLIGDB3dmqE
scenes-app-tasks--list-load-error--light:
- hash: v1.k794b7964.8fb5c1cbd8f30dfa93a15f1cf4ad157c01724b826c706e229392392d85fb6c0c.KGfwyP6m-yBY1OmmeOYg8pRM6FFwwcRGa1Ob3kcvZNM
- scenes-app-tasks--list-with-composer--dark:
- hash: v1.k794b7964.756e28a70d187a93123016bc701180742ca8ce8e38c27137551d1ad1a11136b4.XbeEUBERng61PLYJm1KKvkdNSEh9kxMrW6RO1hJQjn8
- scenes-app-tasks--list-with-composer--light:
- hash: v1.k794b7964.9379caf3dc17b02b7ec3dd691de01481c897795c53d7e17246ee63e7354e81a6.1b8SeLm6Vf2O8Ydf9273V_wiRhVDhloCNtzQNf6HNUQ
+ hash: v1.k794b7964.e0a6374da2da7262d08d1992bea3898259837679f5676f4330400d27559ac5d2.GRHjeB6ePzk1dNIg2SAuNO68t5GV_ApXRJacbk7hWQM
scenes-app-tasks--loading--dark:
- hash: v1.k794b7964.dc58d14e704883628e5a2e448973c2bf40f998192dfc729e4936b4d2d2b71d67.KAxOfjwJ1dhSBLCnt3UeX7TX_cXo2mqGgTmWWtS13_c
+ hash: v1.k794b7964.d4169f92563f1a61588ba823f6be7392267558bfbb86124b6e53ec9b18056418.J8P4wJp8rxM3vNinzY8gfyZ2J4nqdQvQTBd_RgQ8IOw
scenes-app-tasks--loading--light:
- hash: v1.k794b7964.906dd83775961d29051f8e9aedf7a15aa92a3c4a47cb09c307e2853fbb302301.qihWUdFX63dpuA0oy-aFgIhM8i_ALfOxtv6aLTWXGV8
- scenes-app-tasks--mobile-list--dark:
- hash: v1.k794b7964.aa12d9283f2d371e340c367e042cc94b3368451aae7648d72a75604e50c32612.JvoQ6Mf3LGKxdkiERXq65fWkNggXdufEyGvsagLl5WE
- scenes-app-tasks--mobile-list--light:
- hash: v1.k794b7964.9fd49300ca0d02ce3fe8cf6ea7eb850af2f42332d19a821ac73a6108f33fd651.aHbvQ9EqCKA43njPMkK_xgXEq4rToiJ0U8zAsxjwEWA
+ hash: v1.k794b7964.e0a6374da2da7262d08d1992bea3898259837679f5676f4330400d27559ac5d2.0twUlIpBhVsx7O1A3O-B2m1cy4xax5db9u75koBjBco
+ scenes-app-tasks--mobile-composer--dark:
+ hash: v1.k794b7964.0d46e6ad501f2ee733d8196af20d0f88b6ae8d50353bff30695067958c519a13.AGVyuD22c_wa1UCJpXlN2XBYFkp38d7zhyUwqoh-aiA
+ scenes-app-tasks--mobile-composer--light:
+ hash: v1.k794b7964.4e46fc238eaa36f61f17bb56c33d2f2e1dfc2c097b08da0cf5a4acd7a331b8f9.J2sJCuTxb8s7EbQZzfVdZyFUtsQlPIvd7495R3QlsR0
scenes-app-tasks--mobile-new-task--dark:
- hash: v1.k794b7964.769ea87b534e9349dce86bd8288578fdc367515923f19715c8547d77afbb401b.sppYSyaZvxn8yw2wisc1oDBq5cQpXG2xZktdkQc2OBU
+ hash: v1.k794b7964.0d46e6ad501f2ee733d8196af20d0f88b6ae8d50353bff30695067958c519a13.gh2enhX5PvDbT7xD-wd9iHQnAqnQ-ztlcbW0DlZmJgo
scenes-app-tasks--mobile-new-task--light:
- hash: v1.k794b7964.ff1d06e8ac15222e5e15ef40f8498e1f1bbf1cfdd40cb09c6955ee302bc74927.K0Knbgd_yAx-hUhip40iw-gEWVhY7vkTMQUoGeycXIE
+ hash: v1.k794b7964.4e46fc238eaa36f61f17bb56c33d2f2e1dfc2c097b08da0cf5a4acd7a331b8f9.BwgsVP8F0KpL4GnPbv3hnGxEi8al2XBdoAByGydlOnI
scenes-app-tasks--mobile-task-selected--dark:
- hash: v1.k794b7964.db0156b3fd83b5c3494116788236075e0bc2c5ace019e4c1d9947d2b21fa70fb.4HfTdy-PBBkgEn0HFlUkrJm0D6GCiujf_ljrGGrLrsc
+ hash: v1.k794b7964.d62477cbcb9408400e76d3cb0071deb3d03faff4ac520b2d4ecdab6258a1a7ad.crUdc0PsNoOFZ91X7UTIgYXgUxCHJRxLiUt67SP-ZIk
scenes-app-tasks--mobile-task-selected--light:
- hash: v1.k794b7964.8de299235efc98c794efccb4501e490a0f77ee19c901ceaf672266cec2b5ada3.rce6dJ7kA184L-8c5CwwlsEO140N_TEYcHSO-_10d18
+ hash: v1.k794b7964.b65826b2b012393f45046c4ed288096a85f6aca78b4910c0c3007a271767ffaa.HVnEcnGs6oiFe-3r24AafcbzANt_xRt5Zwb1FNk-fRA
scenes-app-tasks--new-task--dark:
- hash: v1.k794b7964.756e28a70d187a93123016bc701180742ca8ce8e38c27137551d1ad1a11136b4.BJtOcYnQfGJ95pWUG9mb_4uPk-UUGwuXKZYER0z_pTY
+ hash: v1.k794b7964.7eef9b267cd20f210bf5f20c395acbd04f412df23a4e5591fb5513ffd82334e8.igtYZYdMAjdMTWuPyiI8UjcKM2v2atwlbdF2GcbufqU
scenes-app-tasks--new-task--light:
- hash: v1.k794b7964.9379caf3dc17b02b7ec3dd691de01481c897795c53d7e17246ee63e7354e81a6.dm0yw0i6qVGswZMSVV1fDRWcSxZ44LiJ9fjTgOXASvo
+ hash: v1.k794b7964.318e9c80dc685a794981c4718212c0ff1529a62113f0fe53b1babb86e990ab6e.lc7xztqxXpgNPLRIPef1RY3WwIquiwVm64iyEciqcUg
scenes-app-tasks--new-task-with-repository--dark:
- hash: v1.k794b7964.e6bd8d80073256a5ccfdd64bd55b5cfb12c44bba71739fdb50f9dc9e0a7054ee.dZCBGIl2eygiUiUSVDfxMJNG0-KCjMs-YTQwN4ZqQO8
+ hash: v1.k794b7964.183b80968dd176e810833f6237d50559eb2b45905a12715d7615b79dd3987304.glKUf15z01yE2oekRT1Y_QLcT87dpxpWCTxnUOh4a-M
scenes-app-tasks--new-task-with-repository--light:
- hash: v1.k794b7964.08a38b4245a1174f7ce20c5c2c506bbbd12bdb1ad34e9684eee26a56a191aeba.kxjvT-TynVb5pDWDLFAvUStnHtr6FhNiLEtkWgPlgzU
+ hash: v1.k794b7964.9e3733a4b644973157675b87f9d5c93279803c83b236223008a7f0275906127a.TLun3X19lpf5HQJhm-68oFXFf_l-39SBlQP779lf8XE
scenes-app-tasks--task-detail-loading--dark:
- hash: v1.k794b7964.bb72909ac17aa66d816aad41006c66a4322781db3d4ab8fd60a82bbac50cee69.ETcygpHfNWRT-7UqS-FfnZLdrhpmdtIEAFc4C2ekROE
+ hash: v1.k794b7964.941ec3a5b05523b0ee00f5671c58aa19fbbf4d54785c9bc49387a9a51d65121d.ln3p7-YC5TFzCDXOJI0C8a-F4AA36fHS0TarfQmdXGc
scenes-app-tasks--task-detail-loading--light:
- hash: v1.k794b7964.044a3c854192cb2e06ae22f4e6a7f703831a59652936d0b06cfabe59813dd76e.AJ9MtVC0Iu1uQx902cLr2-a1tRSwSqWKjAG4mpQxZW8
+ hash: v1.k794b7964.cf66aaef1d8b5d59017acd2a91dbf148fb87fb3e19eda70583e318127a5b52b6.F3PWVbTXInzfojH4Uv6o2d_8Gfkc1bN-nwBULgEtN8I
scenes-app-tasks--task-load-error--dark:
- hash: v1.k794b7964.7073a94dd71871f0b538f05a3a970c73dedd510b6f3dd2ad0ba562ba30a51eec.K9Lrpg3-yUcBrWV_5JKp9c1L3ZwEra0eDHmee7LuS40
+ hash: v1.k794b7964.8c160753039593f051efc147d69f447a861f14a8281d97f8f612b1b2279bb241.wB8WL7fVnS3sNEHJtbST0gUGVoyv2V2TwcnemxoSeBw
scenes-app-tasks--task-load-error--light:
- hash: v1.k794b7964.18a026a996664cec797ad80a508ab89c3028f783efcb9161a0adf140b972ee08.l1xXnSHksgq98dfn_LT-UhmAdUeOPMYapzPlOpLp3ww
+ hash: v1.k794b7964.c46594d69a1c79ef1ff5e151185446bd8132250943cbfaebc069c2e37210eef3.QXFvdCyeprBPyV0HDJmBIEb6HsQ2lc_E5xkUiSJiCHU
scenes-app-tasks--task-not-found--dark:
- hash: v1.k794b7964.cc71899ce25c4eadeba2910a0b52dbc4e1fb497f35b10b2d1ab796ec3c1bd57d.Pj7MmRHJnfyORmf0W_scRECZL1H1RdsHt9HElLbFY9U
+ hash: v1.k794b7964.f1f31f93ac3975b02cab5780747b02f23060ad1adb06c401c11c7bf75d888c99.S4e5VoeP1sHpOuSixuIeeJS7E0Jzt0NfOgV8IJB9Fg8
scenes-app-tasks--task-not-found--light:
- hash: v1.k794b7964.ceeda3871d908806cc8f334391c43defc4ac2e20e6c3a4ec2fc95ddebe358476.zXBV_Ndgjb4vW5DcgehQRN_BDLHN0TQtRbNtndBbWU4
+ hash: v1.k794b7964.ba0258d71a153077d78895c251518dd05810884eda29937720025fdc09f1dee4.kfd78wcAqNuCyYxFGp9oQ6JxKtwA7nizg1RDwox3DR8
scenes-app-tasks--task-run-not-found--dark:
- hash: v1.k794b7964.948bc51a74c839dff0ffd9a75167d8304fd519567263b6eedbc7106aba37ed93.rnJ5mu8tV3kNf1lgz1doTiN9q0Q4R00p-0YpvsHOo-o
+ hash: v1.k794b7964.c05e9ecd2cf29ddab2e5033c8de0a57e2813c536a2f659abcba351ae7d024d17.AHHcGww408YFyBdUPBTR7IUK_QuEhA8I2_BxvSZjXkY
scenes-app-tasks--task-run-not-found--light:
- hash: v1.k794b7964.370216a7a9f2b3ba19e2f6bf2243a0e6d67e43935d8f2e54afb2fac55e54b93e.2duqwV6WqEvrJmpWtDgvQDWDWm01FPb-kZiInr0XB-k
+ hash: v1.k794b7964.89fe5064ecd6c305c839fbd7bcac35b60d6bb23e5dd3716f80271d031628535e.1cdWwFSH8nG-Mz-lQSKzNs0k1TbzwPs3Pob0nZNaLcw
scenes-app-tasks--task-runs-load-error--dark:
- hash: v1.k794b7964.616445e8a1b657493e511f3db82c2d9a7d1092c33db2e15d292f290f6a5bed87.d6DELVtYFsbeY2FAa0mVU0T1xxGKAgU7pOf81PjLX6I
+ hash: v1.k794b7964.4e2bbc04b75c49d35589d8c275c777034d6afab28507d68aababcfd19232a45c.R0mnkM8UCMjCJAV5DqeOrYtwnF-gxWpE6Rle55jAoaY
scenes-app-tasks--task-runs-load-error--light:
- hash: v1.k794b7964.1444d6ec719d41d213411748a5d662866f5b8d376781319a7a187b44adac561c.baHxFicxkxo1sTQYd0DXUEbre2hXm584V4SSZsHjCSo
+ hash: v1.k794b7964.fdf3f8bb967ff9b5741fd10c49b4ce2b7e3cd13c3060ea81a4ffa4c81e209c7b.GoOApSFkzjBf_rJn7J2qTtiPSwlrtlpfSNOx37mlrKw
scenes-app-tasks--task-selected--dark:
- hash: v1.k794b7964.a3564e4ea464f6d12fa3814ae4bfd912e0d25bf347e5821e7777f43566691aff.63OMH4BdMlykEi9JHdi0JM9h_q2bQI_6MKvDbic9uOM
+ hash: v1.k794b7964.5022d3dde1540f86819fccfc1d7c0a337569b2213ccdf1a730d3b7fdf16d57ed.2713dyfaJHLc5PWhqZEWOjuyotRUNPgOuqaEdJUaI9k
scenes-app-tasks--task-selected--light:
- hash: v1.k794b7964.168f661b01add428d664291d16c520116553700d9506b449d95f19b702c161d5.ulbWsFps-CsJY5OwIAweZ-ft0Xe3NeUIAujNiC9usjg
+ hash: v1.k794b7964.a3c996704d86f0854bc4aaaa07cbf709a25391cd776e54a9ba054241d364099d.6L6U3eW3Nxye1C7mVa1g2p0le8gClLpYZE8kZ5UkqX4
+ scenes-app-tasks--unified-navigation--dark:
+ hash: v1.k794b7964.d4169f92563f1a61588ba823f6be7392267558bfbb86124b6e53ec9b18056418.acrrts8TAMCVepFdVIC0S1wZjdtoI-atFC1n-9B9Qwk
+ scenes-app-tasks--unified-navigation--light:
+ hash: v1.k794b7964.e0a6374da2da7262d08d1992bea3898259837679f5676f4330400d27559ac5d2.0GaInhE5K4q2-DGSz6KrZX6vsXX_WN_S8oNY3a1_ZzQ
scenes-app-user-interviews-invite-preview-modal--emailable--dark:
hash: v1.k794b7964.72aefcbed7109d9a1e05f4240c269ce0fa8c6d744f174720aa6fb3cc09d6f624.uCLx-0pStvTD_U6yriY685FeR9zupKQb1RVQL1xcExA
scenes-app-user-interviews-invite-preview-modal--emailable--light:
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.test.ts b/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.test.ts
index ca578481c59c..a51ec28f81a8 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.test.ts
+++ b/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.test.ts
@@ -2,7 +2,9 @@ import { MOCK_DEFAULT_BASIC_USER } from 'lib/api.mock'
import { Conversation, ConversationStatus, ConversationType } from '~/types'
-import { groupConversations } from './NavTabChat'
+import type { Task } from 'products/posthog_ai/frontend/api/types'
+
+import { groupAiHistory, groupConversations } from './NavTabChat'
const conversation: Conversation = {
id: 'conversation-id',
@@ -25,3 +27,67 @@ describe('groupConversations', () => {
expect(groups.flatMap((group) => group.items)).toEqual([conversation])
})
})
+
+const baseTask: Task = {
+ id: 'task-id',
+ task_number: 1,
+ slug: 'TASK-1',
+ title: 'Fix the checkout funnel',
+ description: 'Find the largest conversion drop.',
+ origin_product: 'user_created' as Task['origin_product'],
+ runtime: 'acp' as Task['runtime'],
+ repository: null,
+ github_integration: null,
+ signal_report: null,
+ json_schema: null,
+ internal: false,
+ latest_run: null,
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ created_by: null,
+}
+
+describe('groupAiHistory', () => {
+ it('combines chats and tasks in updated order', () => {
+ const olderConversation = {
+ ...conversation,
+ updated_at: new Date(Date.now() - 2_000).toISOString(),
+ }
+ const task: Task = {
+ ...baseTask,
+ created_at: new Date(Date.now() - 1_000).toISOString(),
+ updated_at: new Date(Date.now() - 1_000).toISOString(),
+ }
+
+ const items = groupAiHistory([olderConversation], [task]).flatMap((group) => group.items)
+
+ expect(items.map((item) => item.key)).toEqual(['task:task-id', 'conversation:conversation-id'])
+ expect(items[0].searchableText).toContain('largest conversion drop')
+ // The list is filtered client-side against this text, so a titled task still has to carry
+ // the slug the server matches a `TASK-1`-shaped query by.
+ expect(items[0].searchableText).toContain('TASK-1')
+ })
+
+ // A task row is rarely edited after creation, so `updated_at` stays near its creation time
+ // however long its agent runs. Ordering on it buries a task that was active moments ago.
+ // `last_activity_at` is nullable for rows written outside the ORM, hence the fallback row.
+ it.each([
+ ['activity time', new Date(Date.now() - 600_000).toISOString(), new Date(Date.now() - 1_000).toISOString()],
+ ['row edit time when there is no activity time', new Date(Date.now() - 1_000).toISOString(), null],
+ ])('orders a task by its %s', (_label, updatedAt, lastActivityAt) => {
+ const recentConversation = {
+ ...conversation,
+ updated_at: new Date(Date.now() - 2_000).toISOString(),
+ }
+ const task: Task = {
+ ...baseTask,
+ created_at: updatedAt,
+ updated_at: updatedAt,
+ last_activity_at: lastActivityAt,
+ }
+
+ const items = groupAiHistory([recentConversation], [task]).flatMap((group) => group.items)
+
+ expect(items.map((item) => item.key)).toEqual(['task:task-id', 'conversation:conversation-id'])
+ })
+})
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.tsx b/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.tsx
index 6811583b4e12..8c6c657f59ba 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.tsx
+++ b/frontend/src/layout/panel-layout/navbar/tabs/NavTabChat.tsx
@@ -1,21 +1,28 @@
import { Combobox } from '@base-ui/react/combobox'
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
-import { useId, useMemo, useState } from 'react'
+import { memo, useId, useMemo, useState } from 'react'
import { IconPlusSmall, IconSearch, IconX } from '@posthog/icons'
import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { Link } from 'lib/lemon-ui/Link'
+import { Spinner } from 'lib/lemon-ui/Spinner'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { Collapsible } from 'lib/ui/Collapsible/Collapsible'
import { cn } from 'lib/utils/css-classes'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { AiChatListItem } from 'scenes/max/components/List/AiChatListItem'
import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
import { urls } from 'scenes/urls'
-import { Conversation } from '~/types'
+import type { Conversation } from '~/types'
+
+import { tasksLogic } from 'products/posthog_ai/frontend/api/logics'
+import { TaskAssigneeFilterMenu, TaskListItem } from 'products/posthog_ai/frontend/api/primitives'
+import type { Task } from 'products/posthog_ai/frontend/api/types'
const DATE_GROUP_ORDER = ['Today', 'Yesterday', 'Last 7 days', 'Last 30 days', 'Older'] as const
@@ -46,29 +53,201 @@ function getDateGroupLabel(dateString: string | null): string {
return 'Older'
}
-export interface ConversationGroup {
+export type AiHistoryItem =
+ | {
+ kind: 'conversation'
+ key: string
+ title: string
+ searchableText: string
+ updatedAt: string | null
+ conversation: Conversation
+ }
+ | {
+ kind: 'task'
+ key: string
+ title: string
+ searchableText: string
+ updatedAt: string
+ task: Task
+ }
+
+export interface AiHistoryGroup {
value: string
- items: Conversation[]
+ items: AiHistoryItem[]
}
-export function groupConversations(conversationHistory: Conversation[]): ConversationGroup[] {
- const grouped: Record<string, Conversation[]> = {}
+export function groupAiHistory(conversationHistory: Conversation[], tasks: Task[]): AiHistoryGroup[] {
+ const items: AiHistoryItem[] = []
+
for (const conversation of conversationHistory) {
if (!conversation) {
continue
}
- const label = getDateGroupLabel(conversation.updated_at)
+ const title = conversation.title || 'Untitled conversation'
+ items.push({
+ kind: 'conversation',
+ key: `conversation:${conversation.id}`,
+ title,
+ searchableText: title,
+ updatedAt: conversation.updated_at,
+ conversation,
+ })
+ }
+
+ for (const task of tasks) {
+ const title = task.title || task.slug
+ items.push({
+ kind: 'task',
+ key: `task:${task.id}`,
+ title,
+ // The slug rather than `title`, which only falls back to it for untitled tasks. The server
+ // also matches a task by its number, through a slug-shaped query like `TASK-42`, and the
+ // run header shows that slug for people to type back. Leaving it out of this filter hides
+ // a titled row the server did return.
+ searchableText: `${task.title} ${task.slug} ${task.description}`,
+ // A task's row is often never edited after creation, so `updated_at` would bucket a
+ // task that ran an hour ago by how long ago it was created.
+ updatedAt: task.last_activity_at ?? task.updated_at,
+ task,
+ })
+ }
+
+ items.sort((left, right) => (Date.parse(right.updatedAt ?? '') || 0) - (Date.parse(left.updatedAt ?? '') || 0))
+
+ const grouped: Record<string, AiHistoryItem[]> = {}
+ for (const item of items) {
+ const label = getDateGroupLabel(item.updatedAt)
if (!grouped[label]) {
grouped[label] = []
}
- grouped[label].push(conversation)
+ grouped[label].push(item)
}
return DATE_GROUP_ORDER.filter((label) => grouped[label]?.length > 0).map(
- (label): ConversationGroup => ({ value: label, items: grouped[label] })
+ (label): AiHistoryGroup => ({ value: label, items: grouped[label] })
+ )
+}
+
+export interface ConversationGroup {
+ value: string
+ items: Conversation[]
+}
+
+export function groupConversations(conversationHistory: Conversation[]): ConversationGroup[] {
+ return groupAiHistory(conversationHistory, []).map((group) => ({
+ value: group.value,
+ items: group.items.flatMap((item) => (item.kind === 'conversation' ? [item.conversation] : [])),
+ }))
+}
+
+function LoadTasksError({ onRetry }: { onRetry: () => void }): JSX.Element {
+ return (
+ <div className="mx-2 mt-2 flex items-center justify-between gap-2 rounded border border-danger bg-danger-highlight px-2 py-1.5 text-xs">
+ <span>Tasks couldn't load.</span>
+ <ButtonPrimitive size="xs" onClick={onRetry}>
+ Retry
+ </ButtonPrimitive>
+ </div>
)
}
+// Every loaded row renders inside the collapsible groups, with no virtualizer, and a search opens
+// every group. Memoized so a keystroke or a status poll re-renders only the rows whose item or
+// selection changed, rather than every page the user has loaded.
+const ConversationRow = memo(function ConversationRow({
+ item,
+ active,
+ onItemClick,
+}: {
+ item: Extract<AiHistoryItem, { kind: 'conversation' }>
+ active: boolean
+ onItemClick?: () => void
+}): JSX.Element {
+ const href = AiChatListItem.getHref(item.conversation.id)
+ return (
+ <AiChatListItem.Root>
+ <AiChatListItem.Group>
+ <Combobox.Item
+ value={item}
+ render={(props) => (
+ <Tooltip title={item.title} placement="right">
+ <Link
+ {...props}
+ to={href}
+ data-attr="nav-chat-history-conversation"
+ buttonProps={{
+ active,
+ fullWidth: true,
+ className: 'pr-0',
+ menuItem: true,
+ }}
+ onClick={(e) => {
+ e.preventDefault()
+ router.actions.push(href)
+ onItemClick?.()
+ }}
+ >
+ <AiChatListItem.Content
+ title={item.conversation.title}
+ status={item.conversation.status}
+ updatedAt={item.conversation.updated_at}
+ />
+ </Link>
+ </Tooltip>
+ )}
+ />
+ <AiChatListItem.Trigger />
+ </AiChatListItem.Group>
+ <AiChatListItem.Actions conversationId={item.conversation.id} />
+ </AiChatListItem.Root>
+ )
+})
+
+const TaskRow = memo(function TaskRow({
+ item,
+ active,
+ onItemClick,
+}: {
+ item: Extract<AiHistoryItem, { kind: 'task' }>
+ active: boolean
+ onItemClick?: () => void
+}): JSX.Element {
+ const href = TaskListItem.getHref(item.task.id)
+ return (
+ <TaskListItem.Root>
+ <TaskListItem.Group>
+ <Combobox.Item
+ value={item}
+ render={(props) => (
+ <Tooltip title={item.title} placement="right">
+ <Link
+ {...props}
+ to={href}
+ data-attr="nav-chat-history-task"
+ buttonProps={{
+ active,
+ fullWidth: true,
+ className: 'pr-0',
+ menuItem: true,
+ }}
+ onClick={(e) => {
+ e.preventDefault()
+ router.actions.push(href)
+ onItemClick?.()
+ }}
+ >
+ <TaskListItem.Content task={item.task} />
+ </Link>
+ </Tooltip>
+ )}
+ />
+ <TaskListItem.Trigger />
+ </TaskListItem.Group>
+ <TaskListItem.Actions taskId={item.task.id} />
+ </TaskListItem.Root>
+ )
+})
+
export function NavTabChat({
inPanel = false,
onItemClick,
@@ -79,17 +258,56 @@ export function NavTabChat({
// The chat surface can be mounted twice at once (nav tab, kept mounted, plus the side panel),
// so the search input's id must be per-instance to keep label/htmlFor pairing valid.
const searchInputId = useId()
- const { conversationHistory, conversationHistoryLoading, currentConversationId } = useValues(maxGlobalLogic)
- const [inputValue, setInputValue] = useState('')
+ const {
+ conversationHistory,
+ conversationHistoryLoading,
+ currentConversationId,
+ isPhaiSandboxFlagOn,
+ effectivePhaiView,
+ } = useValues(maxGlobalLogic)
+ const {
+ tasks,
+ tasksLoading,
+ tasksError,
+ tasksNext,
+ tasksLoadingMore,
+ tasksSearchPending,
+ searchQuery,
+ taskListParams,
+ } = useValues(tasksLogic)
+ const { loadTasks, loadMoreTasks, setSearchQuery } = useActions(tasksLogic)
+ const { location, searchParams } = useValues(router)
+ const tasksEnabled = useFeatureFlag('TASKS') || isPhaiSandboxFlagOn
+ const [chatSearch, setChatSearch] = useState('')
+ const inputValue = tasksEnabled ? searchQuery : chatSearch
+ const selectedTaskId =
+ removeProjectIdIfPresent(location.pathname) === urls.ai() && typeof searchParams.task === 'string'
+ ? searchParams.task
+ : (location.pathname.match(/\/tasks\/([^/]+)/)?.[1] ?? null)
- const conversationGroups = useMemo(() => groupConversations(conversationHistory), [conversationHistory])
+ const historyGroups = useMemo(
+ () => groupAiHistory(conversationHistory, tasksEnabled ? tasks : []),
+ [conversationHistory, tasks, tasksEnabled]
+ )
+ const initialLoading = historyGroups.length === 0 && (conversationHistoryLoading || (tasksEnabled && tasksLoading))
+ // Typing moves the client-side filter at once, but the matching tasks are a debounce plus a round
+ // trip behind it. Until they land, an empty filtered list means "still loading", not "none found".
+ const taskResultsPending = tasksEnabled && (tasksSearchPending || tasksLoading)
+
+ const setInputValue = (value: string): void => {
+ if (tasksEnabled) {
+ setSearchQuery(value)
+ } else {
+ setChatSearch(value)
+ }
+ }
return (
<div className="flex flex-col flex-1 overflow-hidden">
<Combobox.Root
- items={conversationGroups}
- itemToStringLabel={(item: Conversation) => item?.title ?? ''}
- itemToStringValue={(item: Conversation) => item?.title ?? ''}
+ items={historyGroups}
+ itemToStringLabel={(item: AiHistoryItem) => item.searchableText}
+ itemToStringValue={(item: AiHistoryItem) => item.searchableText}
open
autoHighlight
inline
@@ -108,8 +326,8 @@ export function NavTabChat({
<IconSearch className="size-4 text-tertiary group-focus-within:text-primary w-4 shrink-0" />
<Combobox.Input
id={searchInputId}
- placeholder="Chat history"
- aria-label="Chat history"
+ placeholder={tasksEnabled ? 'Search all' : 'Chat history'}
+ aria-label={tasksEnabled ? 'Search chats and tasks' : 'Chat history'}
className="w-full text-sm bg-transparent border-none focus:outline-none focus:ring-0 transition-[width] duration-100 h-[30px]"
autoFocus={inPanel}
/>
@@ -124,11 +342,14 @@ export function NavTabChat({
</ButtonPrimitive>
)}
</label>
+ {tasksEnabled && <TaskAssigneeFilterMenu />}
<Link
to={urls.ai()}
data-attr="nav-chat-new"
buttonProps={{ iconOnly: true, variant: 'outline', className: 'text-ai' }}
- tooltip="New chat"
+ // Only the new PostHog AI view puts the task composer behind this link; every
+ // other cohort lands on the legacy chat, which can only start a conversation.
+ tooltip={effectivePhaiView === 'new' ? 'New chat or task' : 'New chat'}
>
<IconPlusSmall className="size-4" />
</Link>
@@ -140,7 +361,7 @@ export function NavTabChat({
innerClassName="flex flex-col px-1 pb-4 -mx-1 scroll-pt-8 focus-visible:outline-accent -outline-offset-2"
styledScrollbars
>
- {conversationHistoryLoading && conversationHistory.length === 0 ? (
+ {initialLoading ? (
<div className="flex flex-col gap-1 px-1">
<LemonSkeleton className="h-8" />
<LemonSkeleton className="h-8 opacity-60" />
@@ -149,13 +370,11 @@ export function NavTabChat({
) : (
<>
<Combobox.List className="flex flex-col">
- {(group: ConversationGroup) => (
+ {(group: AiHistoryGroup) => (
<Collapsible
key={`${group.value}-${!!inputValue}`}
defaultOpen={
- !!inputValue ||
- group.value === 'Today' ||
- conversationGroups.length === 1
+ !!inputValue || group.value === 'Today' || historyGroups.length === 1
}
>
<Combobox.Group items={group.items}>
@@ -168,62 +387,26 @@ export function NavTabChat({
</Combobox.GroupLabel>
<Collapsible.Panel className="p-1 pl-3">
<Combobox.Collection>
- {(conversation: Conversation) => (
- <AiChatListItem.Root>
- <AiChatListItem.Group>
- <Combobox.Item
- key={conversation.id}
- value={conversation}
- render={(props) => (
- <Tooltip
- title={
- conversation.title ||
- 'view conversation'
- }
- placement="right"
- >
- <Link
- {...props}
- to={AiChatListItem.getHref(
- conversation.id
- )}
- data-attr="nav-chat-history-conversation"
- buttonProps={{
- active:
- conversation.id ===
- currentConversationId,
- fullWidth: true,
- className: 'pr-0',
- menuItem: true,
- }}
- onClick={(e) => {
- e.preventDefault()
- router.actions.push(
- AiChatListItem.getHref(
- conversation.id
- )
- )
- onItemClick?.()
- }}
- >
- <AiChatListItem.Content
- title={conversation.title}
- status={conversation.status}
- updatedAt={
- conversation.updated_at
- }
- />
- </Link>
- </Tooltip>
- )}
- />
- <AiChatListItem.Trigger />
- </AiChatListItem.Group>
- <AiChatListItem.Actions
- conversationId={conversation.id}
+ {(item: AiHistoryItem) =>
+ item.kind === 'conversation' ? (
+ <ConversationRow
+ key={item.key}
+ item={item}
+ active={
+ !selectedTaskId &&
+ item.conversation.id === currentConversationId
+ }
+ onItemClick={onItemClick}
/>
- </AiChatListItem.Root>
- )}
+ ) : (
+ <TaskRow
+ key={item.key}
+ item={item}
+ active={item.task.id === selectedTaskId}
+ onItemClick={onItemClick}
+ />
+ )
+ }
</Combobox.Collection>
</Collapsible.Panel>
</Combobox.Group>
@@ -233,12 +416,49 @@ export function NavTabChat({
<div className="p-2 empty:hidden">
<Combobox.Empty className="empty:hidden">
<div className="flex flex-col items-center justify-center text-center py-8 text-muted border border-dashed rounded-md">
- <p className="text-xs mb-0">No chats found</p>
+ {taskResultsPending ? (
+ <span className="flex items-center gap-2 text-xs">
+ <Spinner className="size-3" />
+ Loading tasks…
+ </span>
+ ) : (
+ <p className="text-xs mb-0">
+ {tasksEnabled ? 'No chats or tasks found' : 'No chats found'}
+ </p>
+ )}
</div>
</Combobox.Empty>
</div>
</>
)}
+ {/* Deliberately not gated on an empty list. A failed load keeps the previous page,
+ so that gate would leave the user reading the old filter's rows with no error
+ and no retry. Nothing else reports this failure: there is no toast for it. */}
+ {tasksEnabled && tasksError && !tasksLoading && (
+ <LoadTasksError onRetry={() => loadTasks(taskListParams)} />
+ )}
+ {tasksEnabled && tasksLoading && tasks.length === 0 && historyGroups.length > 0 && (
+ <div className="flex items-center gap-2 px-3 py-2 text-xs text-muted">
+ <Spinner className="size-3" />
+ Loading tasks…
+ </div>
+ )}
+ {tasksEnabled && tasksNext && (
+ <div className="px-2 pt-2">
+ <ButtonPrimitive
+ fullWidth
+ size="sm"
+ disabled={tasksLoadingMore}
+ onClick={() => loadMoreTasks()}
+ >
+ {tasksLoadingMore && <Spinner className="size-3" />}
+ {/* Wrapped so the label is not a bare text node beside the conditional
+ spinner. A page translator swaps that node for a `<font>` element, and
+ React then inserts the spinner against a node the DOM no longer holds. */}
+ <span>Load more tasks</span>
+ </ButtonPrimitive>
+ </div>
+ )}
</ScrollableShadows>
</div>
</Combobox.Root>
diff --git a/frontend/src/lib/api.test.ts b/frontend/src/lib/api.test.ts
index 9d4b3dc243db..05112a8f483c 100644
--- a/frontend/src/lib/api.test.ts
+++ b/frontend/src/lib/api.test.ts
@@ -501,4 +501,17 @@ describe('API helper', () => {
)
})
})
+
+ describe('tasks', () => {
+ it.each([
+ ['task/id', 'projects/2/tasks/task%2Fid'],
+ ['../other', 'projects/2/tasks/..%2Fother'],
+ ])('keeps task ID %s inside the task path', (taskId, expectedPath) => {
+ expect(new ApiRequest().task(taskId).assembleEndpointUrl()).toEqual(expectedPath)
+ })
+
+ it.each(['.', '..'])('rejects task ID dot segment %s', (taskId) => {
+ expect(() => new ApiRequest().task(taskId)).toThrow('Invalid task ID')
+ })
+ })
})
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 924f3f15c6a6..7bbd4d521c8c 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -1264,7 +1264,11 @@ export class ApiRequest {
}
public task(id: Task['id'], teamId?: TeamType['id']): ApiRequest {
- return this.tasks(teamId).addPathComponent(id)
+ if (id === '.' || id === '..') {
+ throw new Error('Invalid task ID')
+ }
+
+ return this.tasks(teamId).addEncodedPathComponent(id)
}
public taskRuns(taskId: Task['id'], teamId?: TeamType['id']): ApiRequest {
diff --git a/frontend/src/scenes/max/Max.tsx b/frontend/src/scenes/max/Max.tsx
index 62587c529b74..21a08aa6b94d 100644
--- a/frontend/src/scenes/max/Max.tsx
+++ b/frontend/src/scenes/max/Max.tsx
@@ -1,4 +1,5 @@
import { BindLogic, useActions, useValues } from 'kea'
+import { router } from 'kea-router'
import React, { Suspense } from 'react'
import {
@@ -16,6 +17,7 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { cn } from 'lib/utils/css-classes'
+import { isUUIDLike } from 'lib/utils/guards'
import { lazyWithRetry } from 'lib/utils/retryImport'
import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
import { SceneExport } from 'scenes/sceneTypes'
@@ -55,17 +57,54 @@ const ReportAiPanel = lazyWithRetry(() =>
}))
)
-export const scene: SceneExport = {
+interface MaxProps {
+ tabId?: string
+ /**
+ * The scene logic's prop only. The rendered component never receives it, because the app spreads
+ * just the route's path params into the element, so `Max` reads the task from the router instead.
+ */
+ taskId?: string
+}
+
+/**
+ * The task `/ai?task=` selects, or `undefined` when the URL names none.
+ *
+ * `isUUIDLike` rejects a path-shaped value, because this id is interpolated into API paths.
+ */
+function selectedTaskId(searchParams: Record<string, any>): string | undefined {
+ const taskId = searchParams.task
+
+ return typeof taskId === 'string' && isUUIDLike(taskId) ? taskId : undefined
+}
+
+/**
+ * The legacy conversation `/ai?chat=` selects, or `undefined` when the URL names none. Legacy Max
+ * reads the same param to open the conversation (see `maxLogic`); this copy only picks the surface.
+ */
+function selectedChatId(searchParams: Record<string, any>): string | undefined {
+ const chatId = searchParams.chat
+
+ return typeof chatId === 'string' && chatId ? chatId : undefined
+}
+
+export const scene: SceneExport<MaxProps> = {
component: Max,
logic: maxLogic,
+ paramsToProps: ({ searchParams }) => ({ taskId: selectedTaskId(searchParams) }),
}
-export function Max({ tabId }: { tabId?: string }): JSX.Element {
+export function Max({ tabId }: MaxProps): JSX.Element {
+ // `paramsToProps` builds the scene logic's props, and the app spreads only the route's path
+ // params into the component. `/ai` declares none and carries the task in its query string, so
+ // the selected task has to come from the router here or every task link opens the composer.
+ const { searchParams } = useValues(router)
+ const taskId = selectedTaskId(searchParams)
+ const chatId = selectedChatId(searchParams)
const { sidePanelOpen, selectedTab } = useValues(sidePanelLogic)
const { closeSidePanel } = useActions(sidePanelLogic)
const { conversationId: tabConversationId } = useValues(maxLogic({ panelId: tabId }))
const { conversationId: sidepanelConversationId } = useValues(maxLogic({ panelId: SIDE_PANEL_PANEL_ID }))
- if (sidePanelOpen && selectedTab === SidePanelTab.Max && sidepanelConversationId === tabConversationId) {
+ if (!taskId && sidePanelOpen && selectedTab === SidePanelTab.Max && sidepanelConversationId === tabConversationId) {
return (
<SceneContent className="px-4 py-4 min-h-[calc(100vh-var(--scene-layout-header-height)-120px)]">
<SceneTitleSection name={null} resourceType={{ type: 'chat' }} />
@@ -86,7 +125,7 @@ export function Max({ tabId }: { tabId?: string }): JSX.Element {
)
}
- return <AiFirstMaxInstance tabId={tabId ?? ''} />
+ return <AiFirstMaxInstance tabId={tabId ?? ''} taskId={taskId} chatId={chatId} />
}
export interface MaxInstanceProps {
diff --git a/frontend/src/scenes/max/aiSceneView.test.ts b/frontend/src/scenes/max/aiSceneView.test.ts
new file mode 100644
index 000000000000..84de3c951a32
--- /dev/null
+++ b/frontend/src/scenes/max/aiSceneView.test.ts
@@ -0,0 +1,17 @@
+import { AiSceneViewInput, aiSceneView } from './aiSceneView'
+
+describe('aiSceneView', () => {
+ const cases: [string, AiSceneViewInput, 'runner' | 'chat'][] = [
+ ['a bare /ai with the new view saved', { effectivePhaiView: 'new' }, 'runner'],
+ ['a bare /ai with the legacy view saved', { effectivePhaiView: 'legacy' }, 'chat'],
+ ['a task link with the legacy view saved', { taskId: 'task-1', effectivePhaiView: 'legacy' }, 'runner'],
+ ['a chat link with the new view saved', { chatId: 'chat-1', effectivePhaiView: 'new' }, 'chat'],
+ ['a chat link with the legacy view saved', { chatId: 'chat-1', effectivePhaiView: 'legacy' }, 'chat'],
+ // Legacy Max writes `?chat=` itself once a conversation starts; a task added to that URL wins.
+ ['a task and a chat in one URL', { taskId: 'task-1', chatId: 'chat-1', effectivePhaiView: 'new' }, 'runner'],
+ ]
+
+ it.each(cases)('%s', (_name, input, expected) => {
+ expect(aiSceneView(input)).toBe(expected)
+ })
+})
diff --git a/frontend/src/scenes/max/aiSceneView.ts b/frontend/src/scenes/max/aiSceneView.ts
new file mode 100644
index 000000000000..565b2fcce283
--- /dev/null
+++ b/frontend/src/scenes/max/aiSceneView.ts
@@ -0,0 +1,25 @@
+import type { PhaiViewMode } from './maxGlobalLogic'
+
+export interface AiSceneViewInput {
+ /** The task `/ai?task=` selects, if any. */
+ taskId?: string
+ /** The legacy conversation `/ai?chat=` selects, if any. */
+ chatId?: string
+ /** The view the person saved, collapsed to legacy when the sandbox flag is off. */
+ effectivePhaiView: PhaiViewMode
+}
+
+/**
+ * Which surface the `/ai` scene renders. A task only exists in the new runner and a conversation only
+ * exists in the legacy chat, so a link to either has to open that surface whatever view the person
+ * saved: both kinds of link are shared and opened cold. A bare `/ai` follows the saved view.
+ */
+export function aiSceneView({ taskId, chatId, effectivePhaiView }: AiSceneViewInput): 'runner' | 'chat' {
+ if (taskId) {
+ return 'runner'
+ }
+ if (chatId) {
+ return 'chat'
+ }
+ return effectivePhaiView === 'new' ? 'runner' : 'chat'
+}
diff --git a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
index 3ef92e10f82e..a4f7ba10adf3 100644
--- a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
+++ b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
@@ -1,4 +1,5 @@
import { BindLogic, useActions, useValues } from 'kea'
+import { router } from 'kea-router'
import { IconOpenSidebar, IconShare } from '@posthog/icons'
import { LemonBanner } from '@posthog/lemon-ui'
@@ -13,8 +14,9 @@ import { SceneName } from '~/layout/scenes/components/SceneTitleSection'
import { DebugLogsMenu } from 'products/posthog_ai/frontend/api/primitives'
import { EmbeddedRunner } from 'products/posthog_ai/frontend/api/runner'
+import { aiSceneView } from '../aiSceneView'
import { Intro } from '../Intro'
-import { maxGlobalLogic } from '../maxGlobalLogic'
+import { PhaiViewMode, maxGlobalLogic } from '../maxGlobalLogic'
import { maxLogic } from '../maxLogic'
import { MaxThreadLogicProps, maxThreadLogic } from '../maxThreadLogic'
import { phaiAiComposerSeedLogic } from '../phaiAiComposerSeedLogic'
@@ -31,6 +33,8 @@ export function ChatHeader({
children,
hideBorder,
isSandboxRuntime,
+ hideViewToggle,
+ onViewChange,
}: {
conversationId: string | null
tabId?: string
@@ -38,6 +42,9 @@ export function ChatHeader({
hideBorder?: boolean
/** Debug rows only exist on the sandbox runtime, so the staff menu that reveals them is hidden elsewhere. */
isSandboxRuntime?: boolean
+ /** For a surface the URL pinned, where the saved view the toggle reads does not match what is shown. */
+ hideViewToggle?: boolean
+ onViewChange?: (mode: PhaiViewMode) => void
}): JSX.Element {
const { openSidePanelMax } = useActions(maxGlobalLogic)
const { chatTitle } = useValues(maxLogic)
@@ -62,7 +69,7 @@ export function ChatHeader({
</div>
<div className="flex items-center gap-2">
{isSandboxRuntime && <DebugLogsMenu variant="lemon" />}
- <PhaiViewToggle variant="lemon" />
+ {!hideViewToggle && <PhaiViewToggle variant="lemon" onChange={onViewChange} />}
{conversationId ? (
<LemonButton
size="small"
@@ -97,26 +104,27 @@ export function ChatHeader({
interface AiFirstMaxInstanceProps {
tabId: string
+ taskId?: string
+ /** The legacy conversation the URL names. It pins the legacy chat, as `taskId` pins the runner. */
+ chatId?: string
}
-export function AiFirstMaxInstance({ tabId }: AiFirstMaxInstanceProps): JSX.Element {
+export function AiFirstMaxInstance({ tabId, taskId, chatId }: AiFirstMaxInstanceProps): JSX.Element {
const { threadVisible, threadLogicKey, conversation, conversationId } = useValues(maxLogic({ panelId: tabId }))
const { startNewConversation } = useActions(maxLogic({ panelId: tabId }))
const { isMaxAvailable, effectivePhaiView } = useValues(maxGlobalLogic)
- // On `/ai` the new view is the full TaskTracker product (tasks list + composer + run detail); a thin
- // bar keeps the toggle reachable so the user can drop back to the legacy chat.
- if (effectivePhaiView === 'new') {
+ if (aiSceneView({ taskId, chatId, effectivePhaiView }) === 'runner') {
return (
<div className="flex flex-col grow overflow-hidden h-full">
<div className="flex w-full items-center justify-end gap-2 py-2 px-2 border-b border-primary">
{/* The new view is the runner, which is always the sandbox runtime — no runtime check needed. */}
<DebugLogsMenu variant="lemon" />
- <PhaiViewToggle variant="lemon" />
+ {!taskId && <PhaiViewToggle variant="lemon" />}
</div>
<div className="flex flex-col flex-1 min-h-0">
<BindLogic logic={phaiAiComposerSeedLogic} props={{}}>
- <EmbeddedRunner />
+ <EmbeddedRunner taskId={taskId} />
</BindLogic>
</div>
</div>
@@ -138,6 +146,16 @@ export function AiFirstMaxInstance({ tabId }: AiFirstMaxInstanceProps): JSX.Elem
conversationId={conversationId}
tabId={tabId}
isSandboxRuntime={conversation?.agent_runtime === 'sandbox'}
+ // A chat link opened the legacy chat over the saved new view: the toggle would
+ // offer "legacy" for what is already shown. "New chat" leads back to the runner.
+ hideViewToggle={!!chatId && effectivePhaiView === 'new'}
+ // Legacy Max keeps `?chat=` in the URL once a conversation starts, and that param
+ // pins this chat, so switching to the new view has to leave the conversation too.
+ onViewChange={(mode) => {
+ if (mode === 'new' && chatId) {
+ router.actions.push(urls.ai())
+ }
+ }}
/>
{isMaxAvailable ? (
<ChatArea
diff --git a/frontend/src/scenes/max/components/PhaiViewToggle.tsx b/frontend/src/scenes/max/components/PhaiViewToggle.tsx
index 28ae079a42fc..63d717a42bc3 100644
--- a/frontend/src/scenes/max/components/PhaiViewToggle.tsx
+++ b/frontend/src/scenes/max/components/PhaiViewToggle.tsx
@@ -5,7 +5,7 @@ import { LemonButton } from '@posthog/lemon-ui'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
-import { maxGlobalLogic } from '../maxGlobalLogic'
+import { PhaiViewMode, maxGlobalLogic } from '../maxGlobalLogic'
/**
* Switches the Max scene between the new posthog_ai/frontend surface and the legacy Max chat. Only
@@ -14,7 +14,14 @@ import { maxGlobalLogic } from '../maxGlobalLogic'
* `lemon` matches the small secondary buttons in the main `/ai` header; `primitive` matches the
* icon-only chrome around "Open as main focus" in the side-panel header.
*/
-export function PhaiViewToggle({ variant = 'lemon' }: { variant?: 'lemon' | 'primitive' }): JSX.Element | null {
+export function PhaiViewToggle({
+ variant = 'lemon',
+ onChange,
+}: {
+ variant?: 'lemon' | 'primitive'
+ /** Runs after the saved view changes, for a host that has to follow the switch (e.g. leave a pinned chat). */
+ onChange?: (mode: PhaiViewMode) => void
+}): JSX.Element | null {
const { isPhaiSandboxFlagOn, effectivePhaiView } = useValues(maxGlobalLogic)
const { setPhaiViewMode } = useActions(maxGlobalLogic)
@@ -25,7 +32,11 @@ export function PhaiViewToggle({ variant = 'lemon' }: { variant?: 'lemon' | 'pri
const switchingToLegacy = effectivePhaiView === 'new'
const tooltip = switchingToLegacy ? 'Switch to legacy PostHog AI' : 'Switch to new PostHog AI'
const Icon = switchingToLegacy ? IconRevert : IconSparkles
- const onClick = (): void => setPhaiViewMode(switchingToLegacy ? 'legacy' : 'new')
+ const onClick = (): void => {
+ const mode: PhaiViewMode = switchingToLegacy ? 'legacy' : 'new'
+ setPhaiViewMode(mode)
+ onChange?.(mode)
+ }
if (variant === 'primitive') {
return (
diff --git a/frontend/src/scenes/max/mainFocusUrl.test.ts b/frontend/src/scenes/max/mainFocusUrl.test.ts
index 1e92a4b06f5b..3ab1856500b6 100644
--- a/frontend/src/scenes/max/mainFocusUrl.test.ts
+++ b/frontend/src/scenes/max/mainFocusUrl.test.ts
@@ -9,12 +9,12 @@ describe('mainFocusUrl', () => {
activeCreation: { streamKey: 'run-1', taskId: 'task-1', runId: 'run-1' },
conversationId: null,
},
- '/tasks/task-1?runId=run-1',
+ '/ai?task=task-1&runId=run-1',
],
[
'new view with a run that never started',
{ isNewView: true, activeCreation: { streamKey: 'run-1', taskId: 'task-1' }, conversationId: null },
- '/tasks/task-1',
+ '/ai?task=task-1',
],
[
'new view with a task still being created',
diff --git a/frontend/src/scenes/max/mainFocusUrl.ts b/frontend/src/scenes/max/mainFocusUrl.ts
index d9efe1a0e067..d5504086c5fd 100644
--- a/frontend/src/scenes/max/mainFocusUrl.ts
+++ b/frontend/src/scenes/max/mainFocusUrl.ts
@@ -31,5 +31,5 @@ export function mainFocusUrl({ isNewView, activeCreation, conversationId }: Main
return null
}
// The panel keeps streaming the run it opened, while the task page otherwise defaults to the newest.
- return combineUrl(urls.taskDetail(activeCreation.taskId), { runId: activeCreation.runId }).url
+ return combineUrl(urls.aiTask(activeCreation.taskId), { runId: activeCreation.runId }).url
}
diff --git a/frontend/src/scenes/max/maxLogic.test.ts b/frontend/src/scenes/max/maxLogic.test.ts
index 107d6b410e9c..0d73077a0618 100644
--- a/frontend/src/scenes/max/maxLogic.test.ts
+++ b/frontend/src/scenes/max/maxLogic.test.ts
@@ -15,6 +15,7 @@ import { ConversationDetail, SidePanelTab } from '~/types'
import { REPORT_AI_PANEL } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'
+import { maxGlobalLogic } from './maxGlobalLogic'
import {
PENDING_MAX_CONTEXT_KEY,
QUESTION_SUGGESTIONS_DATA,
@@ -136,6 +137,40 @@ describe('maxLogic', () => {
featureFlagLogic.unmount()
})
+ it('keeps the selected task URL when navigating from a legacy chat', async () => {
+ logic = maxLogic({ panelId: 'scene' })
+ logic.mount()
+ logic.actions.openConversation(MOCK_CONVERSATION_ID)
+ await expectLogic(logic).toFinishAllListeners()
+ router.actions.push(urls.aiTask('task-1'))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.location.pathname).toBe(urls.currentProject(urls.ai()))
+ expect(router.values.searchParams).toEqual({ task: 'task-1' })
+ })
+
+ // Regression coverage: the `/ai` handler deliberately leaves the previous chat in this logic
+ // while a task is open, and `maxGlobalLogic` clears that chat from every mounted logic when it
+ // is deleted. Mapping `startNewConversation` to a bare `/ai` then dropped `?task=` and closed
+ // the task the user was reading, without the user navigating at all.
+ it('keeps the selected task URL when the retained chat is deleted', async () => {
+ useMocks({ ...maxMocks, delete: { '/api/environments/:team_id/conversations/:id': [200, {}] } })
+ logic = maxLogic({ panelId: 'scene' })
+ logic.mount()
+ logic.actions.openConversation(MOCK_CONVERSATION_ID)
+ await expectLogic(logic).toFinishAllListeners()
+ router.actions.push(urls.aiTask('task-1'))
+ await expectLogic(logic).toFinishAllListeners()
+
+ maxGlobalLogic.actions.deleteConversation(MOCK_CONVERSATION_ID)
+ await expectLogic(maxGlobalLogic).toFinishAllListeners()
+
+ // The stale chat is still released, it just must not take the route with it.
+ expect(logic.values.conversationId).toBeNull()
+ expect(router.values.location.pathname).toBe(urls.currentProject(urls.ai()))
+ expect(router.values.searchParams).toEqual({ task: 'task-1' })
+ })
+
// The /ai?ask= deep link (e.g. "Start with AI") must not silently vanish when the org hasn't
// granted AI data-processing consent: askMax no-ops in that case, so the handler has to fall back
// to prefilling the composer. With consent it auto-sends via askMax instead.
diff --git a/frontend/src/scenes/max/maxLogic.tsx b/frontend/src/scenes/max/maxLogic.tsx
index f310a7bcdd9f..9d8c4b4e8813 100644
--- a/frontend/src/scenes/max/maxLogic.tsx
+++ b/frontend/src/scenes/max/maxLogic.tsx
@@ -9,6 +9,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'
import { inStorybook, inStorybookTestRunner, uuid } from 'lib/utils/dom'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { objectsEqual } from 'lib/utils/objects'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -959,6 +960,9 @@ export const maxLogic = kea<maxLogicType>([
}
},
[urls.ai()]: (_, search) => {
+ if (search.task) {
+ return
+ }
if (search.ask && !search.chat && !values.question) {
// Clear any existing conversation so the tab title updates
if (values.conversationId && values.activeStreamingThreads === 0) {
@@ -1036,6 +1040,16 @@ export const maxLogic = kea<maxLogicType>([
return [urls.ai(), {}, router.values.location.hash]
},
startNewConversation: () => {
+ // A task open at `/ai?task=` keeps its previous chat in this logic, because the
+ // `urlToAction` handler above skips the cleanup while a task is selected. Deleting
+ // that chat then releases it here without the user navigating, so a bare `/ai`
+ // would drop the task parameter and close the task they are reading.
+ if (
+ removeProjectIdIfPresent(router.values.location.pathname) === urls.ai() &&
+ router.values.searchParams.task
+ ) {
+ return undefined
+ }
return [urls.ai(), {}, router.values.location.hash]
},
openConversation: ({ conversationId }) => {
diff --git a/frontend/src/scenes/max/maxScene.test.tsx b/frontend/src/scenes/max/maxScene.test.tsx
new file mode 100644
index 000000000000..886c347a9c91
--- /dev/null
+++ b/frontend/src/scenes/max/maxScene.test.tsx
@@ -0,0 +1,59 @@
+import { cleanup, render } from '@testing-library/react'
+import { router } from 'kea-router'
+
+import { urls } from 'scenes/urls'
+
+import { initKeaTests } from '~/test/init'
+
+import { Max, scene } from './Max'
+
+// The heavy runner is irrelevant here; record what the scene hands it.
+const renderedSelections: { taskId?: string; chatId?: string }[] = []
+jest.mock('./components/AiFirstMaxInstance', () => ({
+ AiFirstMaxInstance: ({ taskId, chatId }: { taskId?: string; chatId?: string }) => {
+ renderedSelections.push({ taskId, chatId })
+ return null
+ },
+}))
+
+describe('Max scene parameters', () => {
+ const validTaskId = '0199ed4a-5c03-0000-3220-df21df612e95'
+
+ beforeEach(() => {
+ renderedSelections.length = 0
+ initKeaTests()
+ })
+
+ afterEach(cleanup)
+
+ it('accepts a UUID task ID', () => {
+ expect(scene.paramsToProps?.({ params: {}, searchParams: { task: validTaskId }, hashParams: {} })).toEqual({
+ taskId: validTaskId,
+ })
+ })
+
+ it.each(['.', '..', '../../99', 'task-1'])('rejects invalid task ID %s', (taskId) => {
+ expect(scene.paramsToProps?.({ params: {}, searchParams: { task: taskId }, hashParams: {} })).toEqual({
+ taskId: undefined,
+ })
+ })
+
+ // Regression coverage: `paramsToProps` feeds the scene logic, and the app spreads only the
+ // route's path params into the component. `/ai` declares none, so a component that trusted a
+ // `taskId` prop saw `undefined` on every task link and opened the composer instead. Asserting
+ // `paramsToProps` in isolation cannot catch that, because it stays correct while unused.
+ it.each([
+ ['selects the task named by the URL', urls.aiTask(validTaskId), { taskId: validTaskId, chatId: undefined }],
+ ['selects no task for a non-UUID task param', '/ai?task=task-1', { taskId: undefined, chatId: undefined }],
+ ['selects nothing when the URL names nothing', urls.ai(), { taskId: undefined, chatId: undefined }],
+ // A chat link must reach the component too, or it opens the runner over the saved new view.
+ ['selects the chat named by the URL', urls.ai('chat-1'), { taskId: undefined, chatId: 'chat-1' }],
+ ['selects no chat for an empty chat param', '/ai?chat=', { taskId: undefined, chatId: undefined }],
+ ])('%s', (_name, url, expected) => {
+ router.actions.push(url)
+
+ render(<Max />)
+
+ expect(renderedSelections).toEqual([expected])
+ })
+})
diff --git a/frontend/src/scenes/max/phaiAiComposerSeedLogic.test.ts b/frontend/src/scenes/max/phaiAiComposerSeedLogic.test.ts
index 6d27f6af6c3b..e97a3d7dbe73 100644
--- a/frontend/src/scenes/max/phaiAiComposerSeedLogic.test.ts
+++ b/frontend/src/scenes/max/phaiAiComposerSeedLogic.test.ts
@@ -55,6 +55,11 @@ describe('phaiAiComposerSeedLogic', () => {
router.actions.push(urls.ai(undefined, 'Explain this dashboard'))
expect(seedLogic.values.seed).toEqual({ prompt: 'Explain this dashboard', autoSubmit })
+
+ seedLogic.actions.consumeSeed()
+ router.actions.push(urls.aiTask('task-1'), { ask: 'Explain this dashboard' })
+ expect(seedLogic.values.seed).toBeNull()
+ expect(router.values.searchParams).toEqual({ task: 'task-1', ask: 'Explain this dashboard' })
}
)
})
diff --git a/frontend/src/scenes/max/phaiAiComposerSeedLogic.ts b/frontend/src/scenes/max/phaiAiComposerSeedLogic.ts
index dce2f01c9efe..1a94807f3138 100644
--- a/frontend/src/scenes/max/phaiAiComposerSeedLogic.ts
+++ b/frontend/src/scenes/max/phaiAiComposerSeedLogic.ts
@@ -36,7 +36,7 @@ export const phaiAiComposerSeedLogic = kea<phaiAiComposerSeedLogicType>([
urlToAction(({ actions, values }) => ({
[urls.ai()]: (_, search, hash) => {
- if (search.ask && !search.chat) {
+ if (search.ask && !search.chat && !search.task) {
const { ask, ...remainingSearch } = search
// Hash changes also run this handler. Remove the prompt before handing it off so they
// cannot submit it again.
diff --git a/frontend/src/scenes/sceneSmoke.test.tsx b/frontend/src/scenes/sceneSmoke.test.tsx
index cd4d1ffe6455..3c5ad26fffd0 100644
--- a/frontend/src/scenes/sceneSmoke.test.tsx
+++ b/frontend/src/scenes/sceneSmoke.test.tsx
@@ -47,6 +47,7 @@ const ERROR_SCENES: string[] = [
const HIGH_TRAFFIC_SCENES: [name: string, path: string][] = [
['home', '/home'],
['max (/ai)', '/ai'],
+ ['max task (/ai?task=0199ed4a-5c03-0000-3220-df21df612e95)', '/ai?task=0199ed4a-5c03-0000-3220-df21df612e95'],
['insights', '/insights'],
['insight (new)', '/insights/new'],
['dashboards', '/dashboard'],
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index 77e85f6644ec..392f88cb1f5d 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -166,6 +166,7 @@ export const urls = {
projectRoot: (): string => '/',
projectHomepage: (): string => '/home',
ai: (chat?: string, ask?: string): string => combineUrl('/ai', { ask, chat }).url,
+ aiTask: (taskId: string): string => combineUrl('/ai', { task: taskId }).url,
aiHistory: (): string => '/ai/history',
settings: (section: SettingSectionId | SettingLevelId = 'project', setting?: SettingId): string =>
combineUrl(`/settings/${section}`, undefined, setting).url,
diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.md
index d962328777d0..222987af7a00 100644
--- a/products/posthog_ai/frontend/AGENTS.md
+++ b/products/posthog_ai/frontend/AGENTS.md
@@ -57,11 +57,13 @@ The headline exports per module:
it only from an already route-split scene (the `/tasks` runner) or another lazily-loaded layout module — a
light bundle that should stay split uses `api/readableRun` instead.
- **`api/runner`** — **`EmbeddedRunner`** (`<EmbeddedRunner taskId? />`), the lazy, code-split TaskTracker
- product (tasks list + composer + agent-run detail) for hosts that render the whole `/tasks` experience
+ workspace (composer + agent-run detail) for hosts that render the `/tasks` experience
inline (the Max scene surfaces it behind the sandbox view toggle). The heavy scene chunk loads only via
- `EmbeddedRunner`'s dynamic `import()`, so importing this module never statically pulls the scene. Task
- selection/creation still routes through the scene's own `/tasks/:id` URLs — it's the standalone product
- embedded, not a route-decoupled widget.
+ `EmbeddedRunner`'s dynamic `import()`, so importing this module never statically pulls the scene. An
+ embedded host passes `taskId` to select a task, and the AI scene reads it from `/ai?task=<id>`. Never
+ route an embedded selection to `/tasks/:id`, because that moves the user out of the host. The standalone
+ `/tasks` scene keeps its own `/tasks/:id` URLs. Shared AI navigation owns task history, so this remains
+ the standalone workspace embedded in another host, not a route-decoupled widget.
- **`api/primitives`** — **`Thread`** (Radix-style compound: `Thread.Root` is the virtualized presenter, the
atoms `Thread.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall` are the building blocks for
bespoke threads), **`Composer`** (logic-free compound input — the caller owns
diff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.md
index 5921789f29bd..b0518ccc61f4 100644
--- a/products/posthog_ai/frontend/README.md
+++ b/products/posthog_ai/frontend/README.md
@@ -34,12 +34,12 @@ re-introduce the exact bundling problem the split solves. Always import an `api/
Pick the **lowest tier** that does the job.
-| Tier | Module | What's in it | Use when |
-| ------------------------------ | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| **1 — Prepackaged surfaces** | `api/readableRun` + `api/runSurface` + `api/runner` | `ReadonlyRunSurface` (lazy, code-split read-only embed); the `RunSurface` compound (`Root` + slots, eager) for custom layouts; `EmbeddedRunner` (lazy TaskTracker product for inline hosts) | "Just show a run" → `ReadonlyRunSurface` (inbox embeds). "Drive a run / custom layout" → `RunSurface` (tasks). "Embed the whole `/tasks` product" → `EmbeddedRunner` (Max). |
-| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms (`.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall`), `ThreadView`, `Composer.*`, `AttachedContextBar`, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces | Custom layout, or a bespoke/compact thread. |
-| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status helpers (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers, context injection (`attachedContextLogic`, `useAttachedContext`, `contextPickerLogic`), tool-stream subscriptions (`toolStreamEventsLogic`, `useToolStreamListener`); folded-thread + tool types, `AttachedContextItem`, `ToolStreamEvent` | Status badge, automation, context injection, tool-event listeners — no presenters, no registry. |
-| **4 — Extension seam** | `api/tools` | `toolRegistry`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers | Your product renders tool cards (insights, dashboards…). Declare them in your product list and include it in the central manifest. |
+| Tier | Module | What's in it | Use when |
+| ------------------------------ | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **1 — Prepackaged surfaces** | `api/readableRun` + `api/runSurface` + `api/runner` | `ReadonlyRunSurface` (lazy, code-split read-only embed); the `RunSurface` compound (`Root` + slots, eager) for custom layouts; `EmbeddedRunner` (lazy TaskTracker workspace for inline hosts) | "Just show a run" → `ReadonlyRunSurface` (inbox embeds). "Drive a run / custom layout" → `RunSurface` (tasks). "Embed the `/tasks` workspace" → `EmbeddedRunner` (Max). |
+| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms (`.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall`), `ThreadView`, `Composer.*`, `AttachedContextBar`, task navigation items and filters, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces | Custom layout, shared navigation, or a bespoke/compact thread. |
+| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, `tasksLogic`, status helpers (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers, context injection (`attachedContextLogic`, `useAttachedContext`, `contextPickerLogic`), tool-stream subscriptions (`toolStreamEventsLogic`, `useToolStreamListener`); folded-thread, task, and tool types | Status badge, automation, context injection, task navigation, tool-event listeners — no presenters or registry. |
+| **4 — Extension seam** | `api/tools` | `toolRegistry`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers | Your product renders tool cards (insights, dashboards…). Declare them in your product list and include it in the central manifest. |
The Tier 1 surfaces are built on `api/primitives` (Tier 2), which consumes the headless
`api/logics`/`api/types` (Tier 3). Going down a tier trades convenience for control and a smaller chunk.
@@ -336,3 +336,9 @@ Max/LangGraph/conversation. Anything the LangGraph path owns that the surface do
/ the tool registry / `streamKey` — lifted to a generic seam here, never special-cased. The four-tier
contract above is unchanged whichever side of the switch is active. See
[`AGENTS.md`](./AGENTS.md#6-replacement-readiness) for the contributor-side detail.
+
+### Task selection in embedded hosts
+
+Pass `taskId` to `EmbeddedRunner` to render an existing task.
+The AI scene reads it from `/ai?task=<id>`, so shared history links and reloads select the same task.
+Tasks created from `/ai` stay under that route; the standalone `/tasks` scene keeps its existing routes.
diff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.ts
index 2ba7156574d7..ce35a813e58c 100644
--- a/products/posthog_ai/frontend/api/logics.ts
+++ b/products/posthog_ai/frontend/api/logics.ts
@@ -24,6 +24,8 @@ export { getThinkingMessageFromResponse, getRandomThinkingMessage, THINKING_MESS
export { resolveEffortForModel, DEFAULT_COMPOSER_MODEL, DEFAULT_COMPOSER_EFFORT } from '../utils/composerModels'
export { modelCatalogueLogic } from '../logics/modelCatalogueLogic'
+export { tasksLogic } from '../logics/tasksLogic'
+
// --- 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 eaa50fcb2ba1..fb7641e3a62d 100644
--- a/products/posthog_ai/frontend/api/primitives.ts
+++ b/products/posthog_ai/frontend/api/primitives.ts
@@ -77,6 +77,8 @@ export { RunAlertActivity } from '../components/RunAlertActivity'
export { TaskRunStatusDot } from '../components/TaskRunStatusDot'
export { TaskRunLivenessDot } from '../components/TaskRunLivenessDot'
+export { TaskListItem } from '../components/navigation/TaskListItem'
+export { TaskAssigneeFilterMenu } from '../components/navigation/TaskAssigneeFilterMenu'
// Debug-logs overflow menu for hosts with no scene chrome (the PostHog AI scene and side panel).
export { DebugLogsMenu } from '../components/DebugLogsMenu'
diff --git a/products/posthog_ai/frontend/api/runner.ts b/products/posthog_ai/frontend/api/runner.ts
index c61225f3ae2a..df1b468146b7 100644
--- a/products/posthog_ai/frontend/api/runner.ts
+++ b/products/posthog_ai/frontend/api/runner.ts
@@ -1,10 +1,10 @@
// Tier 1 — the embeddable runner scene. `EmbeddedRunner` (`<EmbeddedRunner taskId? />`) is the lazy,
-// code-split TaskTracker product (tasks list + composer + agent-run detail) for hosts that want to render
-// the whole `/tasks` experience inline — e.g. the Max scene surfacing it behind the sandbox view toggle.
+// code-split TaskTracker product (composer + agent-run detail) for hosts that want to render
+// the `/tasks` workspace inline — e.g. the Max scene surfacing it behind the sandbox view toggle.
//
// LIGHT boundary: the heavy TaskTracker scene chunk is reached only through `EmbeddedRunner`'s dynamic
-// `import()`, so importing this module never statically pulls the scene/list/run-surface into the host
-// bundle. Task selection/creation still routes through the scene's own `/tasks/:id` URLs.
+// `import()`, so importing this module never statically pulls the scene/run-surface into the host
+// bundle. The host passes `taskId` for selection; creation stays under `/ai` when hosted there.
//
// Part of the `products/posthog_ai/frontend/api/<module>` public surface — import from here, not from
// deep `../scenes/*` paths. See ../README.md for the tier model and ../AGENTS.md for the coupling rule.
@@ -12,8 +12,8 @@
export { EmbeddedRunner, type TaskTrackerProps } from '../components/EmbeddedRunner'
// `SidePanelRunner` (`<SidePanelRunner panelId />`) is the lazy, code-split compact task-run surface
-// (composer -> pending thread -> live run, no list/detail chrome) for narrow hosts that render a single
-// in-place run rather than the whole `/tasks` list/detail experience — e.g. Max's side panel behind the
+// (composer -> pending thread -> live run, no detail chrome) for narrow hosts that render a single
+// in-place run rather than the whole `/tasks` workspace — e.g. Max's side panel behind the
// posthog_ai view toggle. Same LIGHT boundary as `EmbeddedRunner`: the heavy chunk is reached only through
// its dynamic `import()`. `panelId` keys an embedded `taskTrackerSceneLogic` instance independent of the
// `/tasks` scene's own singleton — submitting a task here never navigates the host.
diff --git a/products/posthog_ai/frontend/api/types.ts b/products/posthog_ai/frontend/api/types.ts
index f9ad1f5f2493..6e7ba006537e 100644
--- a/products/posthog_ai/frontend/api/types.ts
+++ b/products/posthog_ai/frontend/api/types.ts
@@ -8,6 +8,7 @@ export type {
} from '../types/streamTypes'
export type { ToolCallMessage } from '../types/toolTypes'
export type { AttachedContextItem } from '../types/contextTypes'
+export type { Task, TaskAssigneeFilter, TaskListParams } from '../types/taskTypes'
export type {
ToolStreamEvent,
ToolStreamPhase,
diff --git a/products/posthog_ai/frontend/components/EmbeddedRunner.tsx b/products/posthog_ai/frontend/components/EmbeddedRunner.tsx
index 1ed17da83fd1..5165de33bcdb 100644
--- a/products/posthog_ai/frontend/components/EmbeddedRunner.tsx
+++ b/products/posthog_ai/frontend/components/EmbeddedRunner.tsx
@@ -7,16 +7,11 @@ import type { TaskTrackerProps } from '../scenes/TaskTracker/TaskTracker'
export type { TaskTrackerProps } from '../scenes/TaskTracker/TaskTracker'
-// The TaskTracker scene (master/detail list + composer + run detail) is the heavy runner UI. It's loaded on
+// The TaskTracker scene (composer + run detail) is the heavy runner UI. It's loaded on
// demand so a consumer that only links to it — e.g. the Max scene rendering it behind the sandbox view
// toggle — doesn't statically pull it into its own chunk. Only `react` + a lightweight spinner load eagerly.
const Lazy = lazyWithRetry(() => import('../scenes/TaskTracker/TaskTracker').then((m) => ({ default: m.TaskTracker })))
-/**
- * Embeddable, code-split TaskTracker runner. Renders the standalone `/tasks` product (tasks list + composer
- * + agent-run detail) inside any host. Pass `taskId` to preselect a task; omit it for the list + composer.
- * Note the scene routes task selection/creation through its own `/tasks/:id` URLs.
- */
export function EmbeddedRunner(props: TaskTrackerProps): JSX.Element {
return (
<Suspense
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskAssigneeFilterMenu.tsx b/products/posthog_ai/frontend/components/navigation/TaskAssigneeFilterMenu.tsx
similarity index 84%
rename from products/posthog_ai/frontend/scenes/TaskTracker/components/TaskAssigneeFilterMenu.tsx
rename to products/posthog_ai/frontend/components/navigation/TaskAssigneeFilterMenu.tsx
index 326267871384..cbca8a3e3031 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskAssigneeFilterMenu.tsx
+++ b/products/posthog_ai/frontend/components/navigation/TaskAssigneeFilterMenu.tsx
@@ -11,8 +11,8 @@ import {
MenuLabel,
} from '@posthog/quill-primitives'
-import { tasksLogic } from '../../../logics/tasksLogic'
-import { TaskAssigneeFilter } from '../../../types/taskTypes'
+import { tasksLogic } from '../../logics/tasksLogic'
+import type { TaskAssigneeFilter } from '../../types/taskTypes'
export function TaskAssigneeFilterMenu(): JSX.Element {
const { assigneeFilter, isStaffUser } = useValues(tasksLogic)
@@ -22,13 +22,13 @@ export function TaskAssigneeFilterMenu(): JSX.Element {
<DropdownMenu>
<DropdownMenuTrigger
render={
- <Button type="button" size="icon-lg" aria-label="Filter tasks">
+ <Button type="button" size="icon-sm" aria-label="Filter tasks">
<IconFilter />
</Button>
}
/>
<DropdownMenuContent align="start" side="bottom" sideOffset={6} className="min-w-fit">
- <MenuLabel>Show</MenuLabel>
+ <MenuLabel>Show tasks</MenuLabel>
<DropdownMenuRadioGroup
value={assigneeFilter}
onValueChange={(value) => setAssigneeFilter(value as TaskAssigneeFilter)}
@@ -37,7 +37,7 @@ export function TaskAssigneeFilterMenu(): JSX.Element {
<DropdownMenuRadioItem value="my_scouts">My scouts</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="team_scouts">Team scouts</DropdownMenuRadioItem>
{isStaffUser && (
- <DropdownMenuRadioItem value="all_team">All team tasks (staff)</DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="all_team">Everything you can see</DropdownMenuRadioItem>
)}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
diff --git a/products/posthog_ai/frontend/components/navigation/TaskListItem.tsx b/products/posthog_ai/frontend/components/navigation/TaskListItem.tsx
new file mode 100644
index 000000000000..471f306ddddd
--- /dev/null
+++ b/products/posthog_ai/frontend/components/navigation/TaskListItem.tsx
@@ -0,0 +1,94 @@
+import { useActions } from 'kea'
+
+import { IconArchive, IconCloud, IconLaptop, IconListCheck } from '@posthog/icons'
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
+import { DropdownMenuGroup, DropdownMenuItem } from 'lib/ui/DropdownMenu/DropdownMenu'
+import { LinkListItem } from 'lib/ui/LinkListItem/LinkListItem'
+import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { urls } from 'scenes/urls'
+
+import { tasksLogic } from '../../logics/tasksLogic'
+import { TaskRunEnvironment } from '../../types/taskTypes'
+import type { Task } from '../../types/taskTypes'
+import { TaskRunLivenessDot } from '../TaskRunLivenessDot'
+
+function compactTimeAgo(iso: string): string {
+ const seconds = dayjs().diff(dayjs(iso), 'second')
+ if (seconds < 60) {
+ return 'now'
+ }
+ return humanFriendlyDuration(seconds, { maxUnits: 1 })
+}
+
+function getHref(taskId: string): string {
+ return urls.aiTask(taskId)
+}
+
+function TaskTypeIcon({ task }: { task: Task }): JSX.Element {
+ const environment = task.latest_run?.environment
+ const label = environment === TaskRunEnvironment.CLOUD ? 'Cloud task' : 'Local task'
+
+ return (
+ <Tooltip title={environment ? label : 'Task'} placement="right">
+ <span className="flex size-4 text-secondary opacity-50 group-hover:opacity-100 transition-all duration-50">
+ {environment === TaskRunEnvironment.CLOUD ? (
+ <IconCloud />
+ ) : environment === TaskRunEnvironment.LOCAL ? (
+ <IconLaptop />
+ ) : (
+ <IconListCheck />
+ )}
+ </span>
+ </Tooltip>
+ )
+}
+
+function Content({ task }: { task: Task }): JSX.Element {
+ const displayTitle = task.title || task.slug
+
+ return (
+ <>
+ <TaskTypeIcon task={task} />
+ <span className="flex-1 line-clamp-1 text-primary">{displayTitle}</span>
+ {task.latest_run && <TaskRunLivenessDot status={task.latest_run.status} />}
+ <span
+ className={cn(
+ 'opacity-30 text-xs pr-1.5 transition-opacity duration-100',
+ 'group-hover:opacity-0 group-has-[[data-state=open]]:opacity-0 group-has-focus-within:opacity-0'
+ )}
+ >
+ {compactTimeAgo(task.last_activity_at ?? task.updated_at)}
+ </span>
+ </>
+ )
+}
+
+function Actions({ taskId }: { taskId: string }): JSX.Element {
+ const { deleteTask } = useActions(tasksLogic)
+
+ return (
+ <LinkListItem.Actions>
+ <DropdownMenuGroup>
+ <DropdownMenuItem asChild>
+ <ButtonPrimitive menuItem variant="danger" onClick={() => deleteTask({ taskId })}>
+ <IconArchive className="size-4 text-danger" />
+ <span className="text-danger">Archive task</span>
+ </ButtonPrimitive>
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ </LinkListItem.Actions>
+ )
+}
+
+export const TaskListItem = {
+ Root: LinkListItem.Root,
+ Group: LinkListItem.Group,
+ Content,
+ Trigger: LinkListItem.Trigger,
+ Actions,
+ getHref,
+}
diff --git a/products/posthog_ai/frontend/logics/taskHistoryLogic.ts b/products/posthog_ai/frontend/logics/taskHistoryLogic.ts
index 951bfb135db2..de07b134ed1a 100644
--- a/products/posthog_ai/frontend/logics/taskHistoryLogic.ts
+++ b/products/posthog_ai/frontend/logics/taskHistoryLogic.ts
@@ -72,8 +72,8 @@ export const taskHistoryLogic = kea<taskHistoryLogicType>([
reducers({
history: {
- // The full-list surface archives via `tasksLogic.deleteTask` and dispatches this to keep
- // this independent list in sync without re-fetching.
+ // `tasksLogic` dispatches this after any surface archives a task, so this independent
+ // list stays in sync without re-fetching.
taskArchived: (state, { taskId }) => state.filter((task) => task.id !== taskId),
},
historyError: [
diff --git a/products/posthog_ai/frontend/logics/taskLogic.test.ts b/products/posthog_ai/frontend/logics/taskLogic.test.ts
index 1c2bd7a5b1e2..220febb1cf64 100644
--- a/products/posthog_ai/frontend/logics/taskLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/taskLogic.test.ts
@@ -1,10 +1,13 @@
import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import { lemonToast } from '@posthog/lemon-ui'
import api, { ApiError } from 'lib/api'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { initKeaTests } from '~/test/init'
@@ -152,6 +155,32 @@ describe('taskLogic', () => {
})
})
+ describe('deleteTask', () => {
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ // The shared AI navigation opens a task inside `/ai`, so a fixed push to the task list dropped
+ // the user out of the workspace they archived from.
+ it.each([
+ ['the AI workspace', urls.aiTask('task-123'), urls.ai()],
+ ['the task page', urls.taskDetail('task-123'), urls.taskTracker()],
+ ])('returns to the list of %s after archiving', async (_name, openedAt, expectedUrl) => {
+ jest.spyOn(api.tasks, 'delete').mockResolvedValue(undefined)
+ router.actions.push(openedAt)
+
+ logic = taskLogic({ taskId: 'task-123' })
+ logic.mount()
+
+ logic.actions.deleteTask()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(removeProjectIdIfPresent(router.values.location.pathname) + router.values.location.search).toBe(
+ expectedUrl
+ )
+ })
+ })
+
describe('runTaskSuccess', () => {
it('updates tasksLogic with task including new run', async () => {
const tasksLogicInstance = tasksLogic()
diff --git a/products/posthog_ai/frontend/logics/taskLogic.ts b/products/posthog_ai/frontend/logics/taskLogic.ts
index 43b6d94350d4..ed7eb403947b 100644
--- a/products/posthog_ai/frontend/logics/taskLogic.ts
+++ b/products/posthog_ai/frontend/logics/taskLogic.ts
@@ -6,6 +6,8 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { urls } from 'scenes/urls'
import { TaskExecutionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
@@ -138,7 +140,14 @@ export const taskLogic = kea<taskLogicType>([
// defaults to `{}`, which drops "For you"'s scout exclusion (and any other
// filter) and shows the whole visible set until the next filter/search change.
tasksLogic.findAllMounted().forEach((logic) => logic.actions.loadTasks(logic.values.taskListParams))
- router.actions.push('/tasks')
+ // The archived task has no page left, so send the user to the list of the host they
+ // are already in: the task page came from `/tasks`, but the shared AI workspace
+ // renders the same detail under `/ai` and must not eject them to another product.
+ router.actions.push(
+ removeProjectIdIfPresent(router.values.location.pathname) === urls.ai()
+ ? urls.ai()
+ : urls.taskTracker()
+ )
return null
},
updateTask: async ({ data }: { data: TaskUpsertProps }) => {
diff --git a/products/posthog_ai/frontend/logics/tasksLogic.test.ts b/products/posthog_ai/frontend/logics/tasksLogic.test.ts
index 0cb6ba087517..9e75be468cf2 100644
--- a/products/posthog_ai/frontend/logics/tasksLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/tasksLogic.test.ts
@@ -2,6 +2,8 @@ import { MOCK_DEFAULT_USER, api } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { userLogic } from 'scenes/userLogic'
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
@@ -11,6 +13,7 @@ import { initKeaTests } from '~/test/init'
import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
import { OriginProduct, Task } from '../types/taskTypes'
+import { taskHistoryLogic } from './taskHistoryLogic'
import { tasksLogic } from './tasksLogic'
const createMockTask = (id: string): Task => ({
@@ -57,6 +60,9 @@ describe('tasksLogic', () => {
})
afterEach(() => {
+ // `featureFlags` is a persisted reducer, so a flag set in one test survives the next
+ // `initKeaTests` and would make its mount fire an unexpected list load.
+ featureFlagLogic.findMounted()?.actions.setFeatureFlags([], {})
logic.unmount()
})
@@ -102,7 +108,12 @@ describe('tasksLogic', () => {
])('maps the %s filter to its query params', (assigneeFilter, expected) => {
logic.actions.setAssigneeFilter(assigneeFilter)
- expect(logic.values.taskListParams).toEqual({ search: undefined, ...expected })
+ // The nav presents recent activity, so every filter must ask the server for it.
+ expect(logic.values.taskListParams).toEqual({
+ search: undefined,
+ ordering: '-last_activity_at',
+ ...expected,
+ })
})
it('composes the search term with the active assignee filter', () => {
@@ -110,6 +121,7 @@ describe('tasksLogic', () => {
expect(logic.values.taskListParams).toEqual({
search: 'checkout bug',
+ ordering: '-last_activity_at',
created_by: userLogic.values.user?.id,
exclude_origin_product: OriginProduct.SIGNALS_SCOUT,
})
@@ -128,6 +140,91 @@ describe('tasksLogic', () => {
expect(listRequestUrls[0].searchParams.get('exclude_origin_product')).toBe(OriginProduct.SIGNALS_SCOUT)
expect(listRequestUrls[0].searchParams.get('created_by')).toBe(String(MOCK_DEFAULT_USER.id))
})
+
+ // Regression coverage: the app renders once the feature-flag request times out, so this
+ // singleton can mount with the flag still off and `afterMount` never runs again. Without a
+ // load on the late flag the nav sits on an empty list and reports "no tasks".
+ it('loads once when the task flag arrives after mount', async () => {
+ expect(listRequestUrls).toHaveLength(0)
+
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TASKS], { [FEATURE_FLAGS.TASKS]: true })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(listRequestUrls).toHaveLength(1)
+
+ // `onFeatureFlags` fires again on any later flag refresh; that must not re-request.
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TASKS], { [FEATURE_FLAGS.TASKS]: true })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(listRequestUrls).toHaveLength(1)
+ })
+
+ // Regression coverage: the loader reached `breakpoint` only after a resolved response, so a
+ // superseded request that rejected still dispatched `loadTasksFailure`. `tasksError` only
+ // clears on a new `loadTasks`, so the nav kept its error banner above the newer run's
+ // correct list until the user searched, refiltered, retried, or reloaded.
+ it.each([
+ ['before', true],
+ ['after', false],
+ ])('discards a superseded failure that lands %s the newer page', async (_order, failFirst) => {
+ // Deliberate loader failure — kea-loaders would log it
+ silenceKeaLoadersErrors()
+ let rejectStale: (error: Error) => void = () => {}
+ let resolveCurrent: (value: unknown) => void = () => {}
+ jest.spyOn(api, 'get')
+ .mockImplementationOnce(() => new Promise((_resolve, reject) => (rejectStale = reject)))
+ .mockImplementationOnce(() => new Promise((resolve) => (resolveCurrent = resolve)))
+
+ logic.actions.loadTasks({ search: 'stale' })
+ logic.actions.loadTasks({ search: 'current' })
+
+ const page = { results: [createMockTask('current-task')], next: null }
+ if (failFirst) {
+ rejectStale(new Error('gateway timeout'))
+ resolveCurrent(page)
+ } else {
+ resolveCurrent(page)
+ rejectStale(new Error('gateway timeout'))
+ }
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.tasks.map((task) => task.id)).toEqual(['current-task'])
+ expect(logic.values.tasksError).toBeNull()
+ })
+ })
+
+ describe('setSearchQuery', () => {
+ // Regression coverage: the request sits behind a 300ms debounce, so `tasksLoading` is still
+ // false while a consumer filters the cached rows against the new query. Without a pending
+ // flag the nav reports "nothing found" for a search whose matches are still on the server.
+ it('stays pending across the debounce until the matching page lands', async () => {
+ logic.actions.loadTasksSuccess([createMockTask('task-1')])
+
+ logic.actions.setSearchQuery('checkout bug')
+
+ expect(logic.values.tasksSearchPending).toBe(true)
+ expect(logic.values.tasksLoading).toBe(false)
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.tasksSearchPending).toBe(false)
+ })
+
+ // Regression coverage: a load already in flight when the user types answers the previous
+ // query. Ending the wait when that response lands reopens the "nothing found" flash for the
+ // rest of the debounce, which is the flash the pending flag exists to prevent.
+ it('stays pending when a load for the previous query lands during the debounce', async () => {
+ logic.actions.loadTasks(logic.values.taskListParams)
+ logic.actions.setSearchQuery('checkout bug')
+
+ await expectLogic(logic).toDispatchActions(['loadTasks', 'loadTasksSuccess'])
+
+ expect(logic.values.tasksSearchPending).toBe(true)
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.tasksSearchPending).toBe(false)
+ })
})
describe('loadMoreTasks', () => {
@@ -154,10 +251,11 @@ describe('tasksLogic', () => {
expect(logic.values.tasksNext).toBeNull()
})
- // Regression coverage: without clearing `tasksNext` on failure, `hasMore` stays true forever
- // and the infinite-scroll spinner never goes away after a failed page load.
- it('clears tasksNext on failure so the list stops reporting more pages', async () => {
- logic.actions.setTasksNext('/api/projects/1/tasks/?cursor=page-2')
+ // Regression coverage: the cursor is what renders the manual "Load more" control, so dropping
+ // it on a transient failure would remove the only retry for the rest of the session.
+ it('keeps tasksNext on failure so the page can be retried', async () => {
+ const cursor = '/api/projects/1/tasks/?cursor=page-2'
+ logic.actions.setTasksNext(cursor)
// Deliberate loader failure — kea-loaders would log it
silenceKeaLoadersErrors()
jest.spyOn(api, 'get').mockRejectedValueOnce(new Error('network error'))
@@ -165,8 +263,54 @@ describe('tasksLogic', () => {
logic.actions.loadMoreTasks()
await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.tasksNext).toBeNull()
+ expect(logic.values.tasksNext).toBe(cursor)
expect(logic.values.tasksLoadingMore).toBe(false)
+
+ // The retry reuses the same cursor and succeeds.
+ resumeKeaLoadersErrors()
+ jest.spyOn(api, 'get').mockResolvedValueOnce({ results: [createMockTask('task-2')], next: null })
+
+ logic.actions.loadMoreTasks()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.tasks.map((t) => t.id)).toEqual(['task-2'])
+ expect(logic.values.tasksNext).toBeNull()
+ })
+
+ // Regression coverage: the list pages by offset over an activity order, so a task that gains
+ // activity between two page requests can come back on the second page as well.
+ it('drops rows the list already holds when a page repeats them', async () => {
+ logic.actions.loadTasksSuccess([createMockTask('task-1'), createMockTask('task-2')])
+ logic.actions.setTasksNext('/api/projects/1/tasks/?offset=2')
+ jest.spyOn(api, 'get').mockResolvedValueOnce({
+ results: [createMockTask('task-2'), createMockTask('task-3')],
+ next: null,
+ })
+
+ logic.actions.loadMoreTasks()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.tasks.map((t) => t.id)).toEqual(['task-1', 'task-2', 'task-3'])
+ })
+ })
+
+ describe('deleteTask', () => {
+ // Regression coverage: archiving from the shared navigation used to leave the row on the
+ // panel history, which loads its own list and never hears about the delete.
+ it('drops the task from a mounted panel history', async () => {
+ jest.spyOn(api, 'delete').mockResolvedValueOnce({})
+ const historyLogic = taskHistoryLogic()
+ historyLogic.mount()
+ // Let the mount-time load land first, or it overwrites the seeded history.
+ await expectLogic(historyLogic).toDispatchActions(['loadHistorySuccess'])
+ const task = createMockTask('task-1')
+ historyLogic.actions.loadHistorySuccess([task, createMockTask('task-2')])
+
+ logic.actions.deleteTask({ taskId: task.id })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(historyLogic.values.history.map((t) => t.id)).toEqual(['task-2'])
+ historyLogic.unmount()
})
})
})
diff --git a/products/posthog_ai/frontend/logics/tasksLogic.ts b/products/posthog_ai/frontend/logics/tasksLogic.ts
index 947336284a33..5d13b1344147 100644
--- a/products/posthog_ai/frontend/logics/tasksLogic.ts
+++ b/products/posthog_ai/frontend/logics/tasksLogic.ts
@@ -1,24 +1,37 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
import api, { PaginatedResponse } from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { addProductIntent } from 'lib/utils/product-intents'
import { userLogic } from 'scenes/userLogic'
import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
+import { TasksListOrdering } from 'products/tasks/frontend/generated/api.schemas'
+
import type { UserType } from '../../../../frontend/src/types'
import { loadErrorMessage } from '../lib/load-error'
import { OriginProduct, Task, TaskAssigneeFilter, TaskListParams, TaskUpsertProps } from '../types/taskTypes'
+import { taskHistoryLogic } from './taskHistoryLogic'
+
+function hasTasksFlag(featureFlags: FeatureFlagsSet): boolean {
+ return !!(featureFlags[FEATURE_FLAGS.TASKS] || featureFlags[FEATURE_FLAGS.PHAI_SANDBOX_MODE])
+}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tasksLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
user: UserType | null // userLogic
assigneeFilter: TaskAssigneeFilter
+ hasRequestedTasks: boolean
isStaffUser: boolean
+ pendingSearchQuery: string | null
repositories: string[]
repositoriesLoading: boolean
searchQuery: string
@@ -28,10 +41,18 @@ export interface tasksLogicValues {
tasksLoading: boolean
tasksLoadingMore: boolean
tasksNext: string | null
+ tasksSearchPending: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tasksLogicActions {
+ setFeatureFlags: (
+ flags: string[],
+ variants: Record<string, boolean | string>
+ ) => {
+ flags: string[]
+ variants: Record<string, boolean | string>
+ } // featureFlagLogic
createTask: ({ data }: { data: TaskUpsertProps }) => {
data: TaskUpsertProps
}
@@ -140,6 +161,7 @@ export interface tasksLogicActions {
export interface tasksLogicMeta {
__keaTypeGenInternalSelectorTypes: {
isStaffUser: (user: UserType | null) => boolean
+ tasksSearchPending: (pendingSearchQuery: string | null) => boolean
taskListParams: (
searchQuery: string,
assigneeFilter: TaskAssigneeFilter,
@@ -154,7 +176,8 @@ export const tasksLogic = kea<tasksLogicType>([
path(['products', 'posthog_ai', 'frontend', 'logics', 'tasksLogic']),
connect(() => ({
- values: [userLogic, ['user']],
+ values: [userLogic, ['user'], featureFlagLogic, ['featureFlags']],
+ actions: [featureFlagLogic, ['setFeatureFlags']],
})),
actions({
@@ -176,7 +199,18 @@ export const tasksLogic = kea<tasksLogicType>([
// it is showing, and `{}` there would swap the active filter for the whole visible set.
// The default is evaluated per call, so it picks up the filter active at refresh time.
loadTasks: async (params: TaskListParams = values.taskListParams, breakpoint) => {
- const response = await api.tasks.list(params)
+ let response: PaginatedResponse<Task>
+ try {
+ response = await api.tasks.list(params)
+ } catch (error) {
+ // A superseded run must not settle the loader on the error path either. Its
+ // failure would raise the navigation's error banner over the results a newer
+ // run has already delivered, and only another `loadTasks` clears that value.
+ // `breakpoint` throws for a superseded run and does nothing for the newest
+ // one, whose failure does need to surface.
+ breakpoint()
+ throw error
+ }
breakpoint()
actions.setTasksNext(response.next ?? null)
return response.results
@@ -201,7 +235,11 @@ export const tasksLogic = kea<tasksLogicType>([
return values.tasks
}
actions.setTasksNext(response.next ?? null)
- return [...values.tasks, ...response.results]
+ // The server pages by offset over an activity order that streaming runs keep
+ // moving, so a row already loaded can come back on the next page. Keep the first
+ // copy: a repeated row would collide with its own key in the list.
+ const loadedIds = new Set(values.tasks.map((task) => task.id))
+ return [...values.tasks, ...response.results.filter((task) => !loadedIds.has(task.id))]
},
createTask: async ({ data }: { data: TaskUpsertProps }) => {
const newTask = await api.tasks.create(data)
@@ -247,6 +285,28 @@ export const tasksLogic = kea<tasksLogicType>([
setAssigneeFilter: (_, { assigneeFilter }) => assigneeFilter,
},
],
+ // Whether the first list request has been dispatched, so a feature-flag payload arriving
+ // after mount doesn't fire a second one (`onFeatureFlags` can fire repeatedly).
+ hasRequestedTasks: [
+ false,
+ {
+ loadTasks: () => true,
+ },
+ ],
+ // The search the loaded rows don't answer yet, null once they do. `tasksLoading` misses the
+ // 300ms debounce in front of the request, and that gap is when a consumer filtering the
+ // cached rows would report "nothing found" for a search whose matches are still on the
+ // server. A load that was already in flight when the user typed answers the previous query,
+ // so only a response carrying this term ends the wait. A failure carries no term, and
+ // holding the wait open on one would leave a spinner over the error instead.
+ pendingSearchQuery: [
+ null as string | null,
+ {
+ setSearchQuery: (_, { search }) => search,
+ loadTasksSuccess: (state, { payload }) => ((payload?.search ?? '') === (state ?? '') ? null : state),
+ loadTasksFailure: () => null,
+ },
+ ],
tasksError: [
null as string | null,
{
@@ -261,9 +321,9 @@ export const tasksLogic = kea<tasksLogicType>([
{
loadTasks: () => null,
setTasksNext: (_, { next }) => next,
- // Clear the cursor on failure too, otherwise `hasMore` stays true forever and the
- // infinite-scroll spinner keeps spinning with no feedback that the request failed.
- loadMoreTasksFailure: () => null,
+ // Deliberately survives `loadMoreTasksFailure`: the cursor is what renders the manual
+ // "Load more" control, so dropping it on a transient failure would take the retry away
+ // for the rest of the session. The failure listener raises a toast instead.
},
],
// Distinct from `tasksLoading` (which also flips for `loadMoreTasks`) so the infinite-scroll
@@ -281,13 +341,19 @@ export const tasksLogic = kea<tasksLogicType>([
selectors({
// The "all team" filter is staff-only; expose it so the menu can conditionally show it.
isStaffUser: [(s) => [s.user], (user: null | import('~/types').UserType): boolean => !!user?.is_staff],
+ // Whether the visible rows still lag the typed search (see `pendingSearchQuery`).
+ tasksSearchPending: [
+ (s) => [s.pendingSearchQuery],
+ (pendingSearchQuery: string | null): boolean => pendingSearchQuery !== null,
+ ],
// Combined list filters: search term + the assignee toggle. A scout run is created by the user
// the scout executes as, so "for you" and "my scouts" are the two halves of that user's
// `created_by` rows: those runs are what clutters their list, so they are what the split has to
// move. Keying "my scouts" on scout ownership (`LLMSkillOwner`) instead would hide the runs from
// the person actually seeing them, since the executing identity and the owner can differ.
- // "Team scouts" is every scout task on the team; "all team" (staff only) lists every task,
- // letting the server bypass the per-user visibility filter.
+ // "Team scouts" is every scout task on the team. "All team" drops the `created_by` pin, so the
+ // list widens to every task the user can read. It is not a team-wide read: the server bypasses
+ // the visibility filter in local development only (see `all_team_tasks` in `TaskListParams`).
taskListParams: [
(s) => [s.searchQuery, s.assigneeFilter, s.user],
(
@@ -295,9 +361,15 @@ export const tasksLogic = kea<tasksLogicType>([
assigneeFilter: TaskAssigneeFilter,
user: null | import('~/types').UserType
): TaskListParams => {
- const base: TaskListParams = { search: searchQuery || undefined }
- // Guard here too: a non-staff user must never send `all_team_tasks` (the server ignores
- // it, but this keeps the request honest and falls back to their own tasks).
+ // Activity order, not the server's `-created_at` default: this list is presented as
+ // recent activity, and a task can stream for hours without its row being edited.
+ const base: TaskListParams = {
+ search: searchQuery || undefined,
+ ordering: TasksListOrdering.LastActivityAt,
+ }
+ // Guard here too: only the staff-gated menu item may send `all_team_tasks`, so a
+ // non-staff caller falls back to their own tasks instead of sending a parameter the
+ // server would discard.
if (assigneeFilter === 'all_team' && user?.is_staff) {
return { ...base, all_team_tasks: true }
}
@@ -328,5 +400,29 @@ export const tasksLogic = kea<tasksLogicType>([
loadMoreTasksFailure: ({ error, errorObject }) => {
lemonToast.error(`Couldn't load more tasks: ${loadErrorMessage(error, errorObject)}`)
},
+ // Every surface that archives goes through this loader, so sync the independent panel
+ // history here instead of asking each one to remember. Only when it's already mounted:
+ // building it would fetch a list nobody is showing, and a later mount loads it fresh.
+ deleteTaskSuccess: ({ payload }) => {
+ if (payload) {
+ taskHistoryLogic.findMounted()?.actions.taskArchived(payload.taskId)
+ }
+ },
+ // The app renders once the feature-flag request times out (3s), so this logic can mount
+ // before the flags land — and it's an unkeyed singleton, so `afterMount` never runs again.
+ // Without this the nav would sit on an empty list, showing "no tasks" rather than loading.
+ setFeatureFlags: () => {
+ if (!values.hasRequestedTasks && hasTasksFlag(values.featureFlags)) {
+ actions.loadTasks(values.taskListParams)
+ }
+ },
+ })),
+
+ events(({ actions, values }) => ({
+ afterMount: () => {
+ if (hasTasksFlag(values.featureFlags)) {
+ actions.loadTasks(values.taskListParams)
+ }
+ },
})),
])
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx
index 2e37803c9083..34687fc70574 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx
@@ -1,9 +1,14 @@
import { Meta, StoryObj } from '@storybook/react'
+import { useActions } from 'kea'
import { delay, HttpResponse } from 'msw'
+import { useEffect } from 'react'
import { FEATURE_FLAGS } from 'lib/constants'
import { App } from 'scenes/App'
+import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
+import { urls } from 'scenes/urls'
+import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
import { mswDecorator } from '~/mocks/browser'
import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
@@ -23,14 +28,20 @@ const CREATED_BY: Task['created_by'] = {
}
-function mockRun(taskId: string, status: TaskRunStatus, createdAt: string, completedAt: string | null): TaskRun {
+function mockRun(
+ taskId: string,
+ status: TaskRunStatus,
+ createdAt: string,
+ completedAt: string | null,
+ environment: TaskRunEnvironment = TaskRunEnvironment.CLOUD
+): TaskRun {
return {
id: `run-${taskId}`,
task: taskId,
stage: null,
branch: status === TaskRunStatus.COMPLETED ? 'posthog/task-branch' : null,
status,
- environment: TaskRunEnvironment.CLOUD,
+ environment,
runtime_adapter: null,
model: null,
reasoning_effort: null,
@@ -77,7 +88,13 @@ const TASKS: Task[] = [
signal_report: null,
json_schema: null,
internal: false,
- latest_run: mockRun('task-2', TaskRunStatus.COMPLETED, '2024-01-15T11:40:00Z', '2024-01-15T11:52:00Z'),
+ latest_run: mockRun(
+ 'task-2',
+ TaskRunStatus.COMPLETED,
+ '2024-01-15T11:40:00Z',
+ '2024-01-15T11:52:00Z',
+ TaskRunEnvironment.LOCAL
+ ),
created_at: '2024-01-15T11:38:00Z',
updated_at: '2024-01-15T11:40:00Z',
created_by: CREATED_BY,
@@ -119,6 +136,42 @@ const GITHUB_INTEGRATION = {
created_at: '2024-01-01T00:00:00Z',
}
+const CONVERSATIONS = {
+ count: 2,
+ next: null,
+ previous: null,
+ results: [
+ {
+ id: 'conversation-1',
+ status: 'idle',
+ title: 'Summarize weekly signups',
+ created_at: '2024-01-15T10:00:00Z',
+ updated_at: '2024-01-15T10:15:00Z',
+ user: CREATED_BY,
+ },
+ {
+ id: 'conversation-2',
+ status: 'idle',
+ title: 'Compare conversion by channel',
+ created_at: '2024-01-14T14:00:00Z',
+ updated_at: '2024-01-14T14:20:00Z',
+ user: CREATED_BY,
+ },
+ ],
+}
+
+function UnifiedNavigationStory({ viewMode = 'new' }: { viewMode?: 'new' | 'legacy' }): JSX.Element {
+ const { setNavExperimentTab } = useActions(panelLayoutLogic)
+ const { setPhaiViewMode } = useActions(maxGlobalLogic)
+
+ useEffect(() => {
+ setNavExperimentTab('chat')
+ setPhaiViewMode(viewMode)
+ }, [setNavExperimentTab, setPhaiViewMode, viewMode])
+
+ return <App />
+}
+
const meta: Meta = {
component: App,
title: 'Scenes-App/Tasks',
@@ -128,6 +181,8 @@ const meta: Meta = {
'/api/code/invites/check-access/': { has_access: true, has_loops_access: false },
'/api/projects/:team_id/tasks/': listResponse(TASKS),
'/api/projects/:team_id/tasks/repositories/': { repositories: ['PostHog/posthog'] },
+ // nosemgrep: no-environments-api-urls-frontend -- Storybook mock for the shared AI navigation.
+ '/api/environments/:team_id/conversations/': CONVERSATIONS,
// Exact ids (not `:id`) so they never shadow the `repositories` action route.
'/api/projects/:team_id/tasks/task-3/': TASKS[2],
'/api/projects/:team_id/tasks/task-3/runs/': { count: 0, next: null, previous: null, results: [] },
@@ -147,10 +202,23 @@ export default meta
type Story = StoryObj<typeof meta>
-// Two-column layout: list on the left, the new-task composer on the right.
-export const ListWithComposer: Story = {}
+export const Composer: Story = {}
+
+export const UnifiedNavigation: Story = {
+ render: () => <UnifiedNavigationStory />,
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.TASKS, FEATURE_FLAGS.PHAI_SANDBOX_MODE],
+ pageUrl: urls.ai(),
+ },
+}
+
+export const AiTaskSelected: Story = {
+ render: () => <UnifiedNavigationStory viewMode="legacy" />,
+ parameters: {
+ pageUrl: urls.aiTask('task-3'),
+ },
+}
-// New-task route — same two columns, composer is the focused right pane.
export const NewTask: Story = {
parameters: {
pageUrl: taskNewUrl(),
@@ -184,15 +252,14 @@ export const NewTaskWithRepository: Story = {
],
}
-// A task is selected: the row is highlighted and its detail fills the right column.
export const TaskSelected: Story = {
parameters: {
pageUrl: taskDetailUrl('task-3'),
},
}
-// The tasks request never resolves, so the list column shows its loading skeletons.
export const Loading: Story = {
+ render: () => <UnifiedNavigationStory />,
parameters: {
testOptions: { waitForLoadersToDisappear: false },
},
@@ -210,8 +277,8 @@ export const Loading: Story = {
],
}
-// The tasks list endpoint fails with no cached tasks — the column shows an error + retry, not "No tasks yet".
export const ListLoadError: Story = {
+ render: () => <UnifiedNavigationStory />,
decorators: [
mswDecorator({
get: {
@@ -312,8 +379,8 @@ export const TaskRunNotFound: Story = {
],
}
-// No tasks yet — the list shows its empty state alongside the composer.
export const Empty: Story = {
+ render: () => <UnifiedNavigationStory />,
decorators: [
mswDecorator({
get: {
@@ -334,8 +401,7 @@ const MOBILE_PARAMETERS = {
testOptions: { viewport: MOBILE_VIEWPORT },
}
-// Mobile: the list fills the screen in its own scroll container, with a floating "New task" button.
-export const MobileList: Story = {
+export const MobileComposer: Story = {
parameters: MOBILE_PARAMETERS,
}
@@ -347,7 +413,6 @@ export const MobileNewTask: Story = {
},
}
-// Mobile: a selected task's detail fills the screen (its back button returns to the list).
export const MobileTaskSelected: Story = {
parameters: {
...MOBILE_PARAMETERS,
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.tsx
index 44c7fb765256..f8be539db52a 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.tsx
@@ -2,19 +2,14 @@ import { useValues } from 'kea'
import { AllowTrainingCallout } from 'lib/components/AllowTrainingCallout/AllowTrainingCallout'
import { useWindowSize } from 'lib/hooks/useWindowSize'
-import { sceneConfigurations } from 'scenes/scenes'
-import { Scene, SceneExport } from 'scenes/sceneTypes'
-import { urls } from 'scenes/urls'
+import { SceneExport } from 'scenes/sceneTypes'
-import { SceneBreadcrumbBackButton } from '~/layout/scenes/components/SceneBreadcrumbs'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
import { TaskComposer } from './components/TaskComposer'
import { TaskCreateThread } from './components/TaskCreateThread'
import { TaskDetailPage } from './components/TaskDetailPage'
-import { TasksListColumn } from './components/TasksListColumn'
import { taskTrackerSceneLogic } from './taskTrackerSceneLogic'
export interface TaskTrackerProps {
@@ -36,81 +31,26 @@ export function TaskTracker({ taskId }: TaskTrackerProps): JSX.Element {
const selectedTaskId = taskId && taskId !== 'new' ? taskId : null
- // While an optimistic create is in flight (and no task is selected), the thread opens immediately in place
- // of the composer — see `taskTrackerSceneLogic.submit`.
- const composerPane = activeCreation ? (
- <TaskCreateThread streamKey={activeCreation.streamKey} isMobile={isMobile} />
- ) : (
- <TaskComposer />
- )
- const rightPane = selectedTaskId ? <TaskDetailPage taskId={selectedTaskId} isMobile={false} /> : composerPane
-
- if (isMobile) {
- // Single column: detail, composer, or the list (with a "Create a new task" row).
- if (selectedTaskId) {
- return (
- <div className="flex flex-col h-full min-h-0">
- <AllowTrainingCallout featureName="PostHog Desktop" />
- <div className="flex flex-1 min-h-0 flex-col overflow-hidden">
- <TaskDetailPage taskId={selectedTaskId} isMobile />
- </div>
- </div>
- )
- }
- if (taskId === 'new') {
- // Optimistic create renders the same scene shell as the detail page (which carries its own
- // SceneContent + back button), so wrap it like the detail branch — not the composer's
- // SceneContent — to keep the create → detail handoff seamless and avoid nesting SceneContent.
- if (activeCreation) {
- return (
- <div className="flex flex-col h-full min-h-0">
- <AllowTrainingCallout featureName="Tasks" />
- <div className="flex flex-1 min-h-0 flex-col overflow-hidden">
- <TaskCreateThread streamKey={activeCreation.streamKey} isMobile />
- </div>
- </div>
- )
- }
- return (
- <SceneContent className="h-full">
- <SceneBreadcrumbBackButton
- forceBackTo={{
- key: 'tasks',
- name: 'Tasks',
- path: urls.taskTracker(),
- }}
- className="mt-10 w-fit"
- />
- <AllowTrainingCallout featureName="Tasks" />
- <div className="flex flex-1 min-h-0 flex-col overflow-hidden">
- <TaskComposer />
- </div>
- </SceneContent>
- )
- }
- // Full-height column so the virtualized list has a bounded height to fill; the header stays
- // fixed and the list owns its own scroll (the page no longer scrolls).
+ if (selectedTaskId || activeCreation) {
return (
- <SceneContent className="h-full">
- <SceneTitleSection
- name={sceneConfigurations[Scene.TaskTracker].name}
- description={sceneConfigurations[Scene.TaskTracker].description}
- resourceType={{ type: sceneConfigurations[Scene.TaskTracker].iconType || 'default_icon_type' }}
- />
- <AllowTrainingCallout featureName="Tasks" />
- <TasksListColumn selectedTaskId={null} isMobile />
- </SceneContent>
+ <div className="flex flex-col h-full min-h-0">
+ <AllowTrainingCallout featureName={selectedTaskId ? 'PostHog Desktop' : 'Tasks'} />
+ <div className="flex flex-1 min-h-0 flex-col overflow-hidden">
+ {selectedTaskId ? (
+ <TaskDetailPage taskId={selectedTaskId} isMobile={isMobile} />
+ ) : (
+ <TaskCreateThread streamKey={activeCreation!.streamKey} isMobile={isMobile} />
+ )}
+ </div>
+ </div>
)
}
return (
<SceneContent className="h-full">
<AllowTrainingCallout featureName="Tasks" />
- <div className="flex flex-1 min-h-0 gap-4">
- <div className="w-72 shrink-0 pl-0 flex flex-col min-h-0 border-r border-primary">
- <TasksListColumn selectedTaskId={selectedTaskId} />
- </div>
- <div className="flex-1 min-w-0 flex flex-col min-h-0">{rightPane}</div>
+ <div className="flex flex-1 min-h-0 flex-col overflow-hidden">
+ <TaskComposer />
</div>
</SceneContent>
)
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx
index 6e07f9e2102a..4441bd85d14f 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskCreateThread.tsx
@@ -22,7 +22,6 @@ export function TaskCreateThread({ streamKey, isMobile }: TaskCreateThreadProps)
<TaskRunSceneShell
task={null}
selectedRun={null}
- sceneMenuBarEnabled={false}
onArchive={() => {}}
taskError={null}
onRetry={() => {}}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDebugLogsMenu.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDebugLogsMenu.tsx
deleted file mode 100644
index 6c7e759a4fff..000000000000
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDebugLogsMenu.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { SceneMenuBarCheckboxItem, SceneMenuBarMenu } from '~/layout/scenes/components/SceneMenuBar'
-
-import { debugLogsLogic } from '../../../logics/debugLogsLogic'
-
-/**
- * Staff-only menu exposing the debug-logs toggle for the run thread. Renders nothing unless the current
- * user may control debug logs (staff or local dev) — impersonated sessions force debug logs on and have
- * no toggle. The checkmark reflects the persisted (localStorage) preference, off by default.
- */
-export function TaskDebugLogsMenu(): JSX.Element | null {
- const { canControlDebugLogs, debugLogsEnabled } = useValues(debugLogsLogic)
- const { setDebugLogsEnabled } = useActions(debugLogsLogic)
-
- if (!canControlDebugLogs) {
- return null
- }
-
- return (
- <SceneMenuBarMenu label="Staff only" dataAttr="task-menubar-staff">
- <SceneMenuBarCheckboxItem
- checked={debugLogsEnabled}
- onCheckedChange={(checked) => setDebugLogsEnabled(!!checked)}
- data-attr="task-menubar-show-debug-logs"
- >
- Show debug logs
- </SceneMenuBarCheckboxItem>
- </SceneMenuBarMenu>
- )
-}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDebugLogsPanelToggle.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDebugLogsPanelToggle.tsx
index ac7bb062a6ad..2ae7f50c968d 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDebugLogsPanelToggle.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDebugLogsPanelToggle.tsx
@@ -7,10 +7,8 @@ import { ScenePanelActionsSection, ScenePanelDivider } from '~/layout/scenes/Sce
import { debugLogsLogic } from '../../../logics/debugLogsLogic'
/**
- * Scene-panel twin of `TaskDebugLogsMenu` — the same debug-logs toggle for users without the scene
- * menu bar. Both surfaces read and write the one persisted preference, so the menu bar and the panel
- * never disagree. Renders nothing (not even its divider) unless the current user may control debug
- * logs: impersonated sessions force debug logs on and have no toggle.
+ * Renders nothing, including its divider, unless the current user may control debug logs.
+ * Impersonated sessions force debug logs on and do not show the toggle.
*/
export function TaskDebugLogsPanelToggle(): JSX.Element | null {
const { canControlDebugLogs, debugLogsEnabled } = useValues(debugLogsLogic)
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
index 05e342417014..40ae96fe1a98 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
@@ -4,8 +4,6 @@ import { IconExternal, IconGithub, IconPlay } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
import { NotFound } from 'lib/components/NotFound'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
import { isPiTaskRuntime } from '../../../types/taskTypes'
@@ -17,7 +15,6 @@ import { TaskRunSceneShell } from './TaskRunSceneShell'
export interface TaskDetailPageProps {
taskId: string
- /** Mobile shows the single-column layout, where a back button is needed to return to the list. */
isMobile: boolean
}
@@ -26,9 +23,7 @@ export function TaskDetailPage({ taskId, isMobile }: TaskDetailPageProps): JSX.E
const { task, taskNotFound, taskError, latestRun, selectedRun, isTaskPending, isHeaderLoading, runTaskInFlight } =
useValues(sceneLogic)
const { runTask, deleteTask, loadTask } = useActions(sceneLogic)
- const { featureFlags } = useValues(featureFlagLogic)
const { activeCreation, hasDesktopAccess } = useValues(taskTrackerSceneLogic)
- const sceneMenuBarEnabled = !!featureFlags[FEATURE_FLAGS.SCENE_MENU_BAR]
const isActiveCreation = activeCreation?.taskId === taskId
if (taskNotFound && !task) {
@@ -100,7 +95,6 @@ export function TaskDetailPage({ taskId, isMobile }: TaskDetailPageProps): JSX.E
selectedRun={selectedRun}
isHeaderLoading={isHeaderLoading && !isActiveCreation}
titleActions={titleActions}
- sceneMenuBarEnabled={sceneMenuBarEnabled}
onArchive={deleteTask}
taskError={taskError}
onRetry={loadTask}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskHistory.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskHistory.tsx
index 4d727b228a61..f693280d7f52 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskHistory.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskHistory.tsx
@@ -129,7 +129,6 @@ export function TaskHistoryList(): JSX.Element {
function TaskHistoryCard({ task, onOpen }: TaskHistoryRowProps): JSX.Element {
const { deleteTask } = useActions(tasksLogic)
- const { taskArchived } = useActions(taskHistoryLogic)
return (
<div
@@ -159,7 +158,6 @@ function TaskHistoryCard({ task, onOpen }: TaskHistoryRowProps): JSX.Element {
onClick={(e) => {
e.stopPropagation()
deleteTask({ taskId: task.id })
- taskArchived(task.id)
}}
/>
</div>
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskListItem.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskListItem.tsx
deleted file mode 100644
index 8d1201e9f24f..000000000000
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskListItem.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import { useActions } from 'kea'
-import { router } from 'kea-router'
-import { memo } from 'react'
-
-import { IconArchive } from '@posthog/icons'
-
-import { dayjs } from 'lib/dayjs'
-import { Link } from 'lib/lemon-ui/Link'
-import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
-import { DropdownMenuGroup, DropdownMenuItem } from 'lib/ui/DropdownMenu/DropdownMenu'
-import { LinkListItem } from 'lib/ui/LinkListItem/LinkListItem'
-import { cn } from 'lib/utils/css-classes'
-import { humanFriendlyDuration } from 'lib/utils/durations'
-import { urls } from 'scenes/urls'
-
-import { TaskRunLivenessDot } from 'products/posthog_ai/frontend/api/primitives'
-
-import { tasksLogic } from '../../../logics/tasksLogic'
-import { Task } from '../../../types/taskTypes'
-
-// Compact "time ago" using a single largest unit, e.g. 18m, 1h, 7d.
-function compactTimeAgo(iso: string): string {
- const seconds = dayjs().diff(dayjs(iso), 'second')
- if (seconds < 60) {
- return 'now'
- }
- return humanFriendlyDuration(seconds, { maxUnits: 1 })
-}
-
-// Memoized: the parent re-renders the whole list on every task projection, but a row only changes
-// when its task or active state does.
-export const TaskListItem = memo(function TaskListItem({
- task,
- isActive,
-}: {
- task: Task
- isActive: boolean
-}): JSX.Element {
- const { deleteTask } = useActions(tasksLogic)
-
- const displayTitle = task.title || task.slug
- // "Started" reflects when the latest run began; fall back to creation for never-run tasks.
- const startedAt = task.latest_run?.created_at ?? task.created_at
-
- return (
- <LinkListItem.Root>
- <LinkListItem.Group>
- <Link
- to={urls.taskDetail(task.id)}
- onClick={(e) => {
- // Let cmd/ctrl/middle-click open a new tab natively.
- if (e.metaKey || e.ctrlKey || e.button === 1) {
- return
- }
- e.preventDefault()
- router.actions.push(urls.taskDetail(task.id))
- }}
- buttonProps={{
- active: isActive,
- fullWidth: true,
- // Taller tap target on mobile (min-height wins over the base menu-item height).
- className: 'group',
- menuItem: true,
- }}
- tooltip={displayTitle}
- tooltipPlacement="right"
- >
- <div className="flex-1 min-w-0 flex items-center gap-1.5">
- <span className="min-w-0 line-clamp-1 text-primary">{displayTitle}</span>
- {task.latest_run && <TaskRunLivenessDot status={task.latest_run.status} />}
- </div>
- <span
- className={cn(
- 'opacity-30 text-xs pr-1.5 transition-opacity duration-100',
- 'group-hover:opacity-0 group-has-[[data-state=open]]:opacity-0 group-has-focus-within:opacity-0'
- )}
- >
- {compactTimeAgo(startedAt)}
- </span>
- </Link>
- <LinkListItem.Trigger />
- </LinkListItem.Group>
- <LinkListItem.Actions>
- <DropdownMenuGroup>
- <DropdownMenuItem asChild>
- <ButtonPrimitive menuItem variant="danger" onClick={() => deleteTask({ taskId: task.id })}>
- <IconArchive className="size-4 text-danger" />
- <span className="text-danger">Archive task</span>
- </ButtonPrimitive>
- </DropdownMenuItem>
- </DropdownMenuGroup>
- </LinkListItem.Actions>
- </LinkListItem.Root>
- )
-})
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx
index 9622dbb2ff91..007964bd16a9 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx
@@ -3,18 +3,12 @@ import { type ReactNode } from 'react'
import { IconArchive } from '@posthog/icons'
import { LemonDivider } from '@posthog/lemon-ui'
-import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'
import { dayjs } from 'lib/dayjs'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
+import { cn } from 'lib/utils/css-classes'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import {
- SceneMenuBar,
- SceneMenuBarItem,
- SceneMenuBarMenu,
- SceneMenuBarSeparator,
-} from '~/layout/scenes/components/SceneMenuBar'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import {
ScenePanel,
@@ -26,7 +20,6 @@ import {
import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'
import type { Task } from '../../../types/taskTypes'
-import { TaskDebugLogsMenu } from './TaskDebugLogsMenu'
import { TaskDebugLogsPanelToggle } from './TaskDebugLogsPanelToggle'
import { TaskPanelSkeleton, TaskRunMetadataSkeleton } from './taskDetailSkeletons'
import { TaskErrorBanner } from './TaskErrorBanner'
@@ -41,11 +34,9 @@ export interface TaskRunSceneShellProps {
isHeaderLoading?: boolean
/** Title-bar action buttons (or their skeleton). Supplied by the caller so the shell stays presentational. */
titleActions?: JSX.Element
- sceneMenuBarEnabled: boolean
onArchive: () => void
taskError: string | null
onRetry: () => void
- /** Mobile shows the single-column layout, where the title needs a back button to return to the list. */
isMobile: boolean
/** The run-log slot (the streamed thread). */
children: ReactNode
@@ -61,7 +52,6 @@ export function TaskRunSceneShell({
selectedRun,
isHeaderLoading = false,
titleActions,
- sceneMenuBarEnabled,
onArchive,
taskError,
onRetry,
@@ -70,19 +60,6 @@ export function TaskRunSceneShell({
}: TaskRunSceneShellProps): JSX.Element {
return (
<SceneContent className="h-full min-h-0 gap-y-0">
- {sceneMenuBarEnabled && task && (
- <SceneMenuBar>
- <SceneMenuBarMenu label="File" dataAttr="task-menubar-file">
- <SceneMenuBarFileItems dataAttrKey="task" />
- <SceneMenuBarSeparator />
- <SceneMenuBarItem variant="destructive" onClick={onArchive} data-attr="task-menubar-archive">
- <IconArchive />
- Archive task
- </SceneMenuBarItem>
- </SceneMenuBarMenu>
- <TaskDebugLogsMenu />
- </SceneMenuBar>
- )}
<ScenePanel>
{isHeaderLoading ? (
<TaskPanelSkeleton />
@@ -145,8 +122,9 @@ export function TaskRunSceneShell({
/>
)}
- <header className="flex flex-col gap-y-2 mt-4">
+ <header className={cn('flex flex-col gap-y-2', taskError && 'mt-4')}>
<SceneTitleSection
+ className="-mt-2"
name={task?.title || 'Task'}
description={null}
resourceType={{ type: 'task' }}
@@ -155,9 +133,9 @@ export function TaskRunSceneShell({
forceBackTo={
isMobile
? {
- key: 'tasks',
- name: 'Tasks',
- path: urls.taskTracker(),
+ key: 'posthog-ai',
+ name: 'PostHog AI',
+ path: urls.ai(),
}
: undefined
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TasksListColumn.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TasksListColumn.tsx
deleted file mode 100644
index a0e6591d42c3..000000000000
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TasksListColumn.tsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { IconPlus, IconPlusSmall } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonDivider, LemonSkeleton } from '@posthog/lemon-ui'
-import { Input } from '@posthog/quill-primitives'
-
-import { cn } from 'lib/utils/css-classes'
-import { urls } from 'scenes/urls'
-
-import { tasksLogic } from '../../../logics/tasksLogic'
-import { TaskAssigneeFilterMenu } from './TaskAssigneeFilterMenu'
-import { VirtualizedTasksList } from './VirtualizedTasksList'
-
-interface TasksListColumnProps {
- /** Currently selected task id, used to highlight its row. Null when showing the composer. */
- selectedTaskId: string | null
- /** On mobile the column is the whole screen: the list scrolls in its own container and a floating button creates a task. */
- isMobile?: boolean
-}
-
-export function TasksListColumn({ selectedTaskId, isMobile = false }: TasksListColumnProps): JSX.Element {
- const {
- tasks,
- tasksLoading,
- tasksError,
- tasksNext,
- tasksLoadingMore,
- searchQuery,
- assigneeFilter,
- taskListParams,
- } = useValues(tasksLogic)
- const { loadTasks, loadMoreTasks, setSearchQuery } = useActions(tasksLogic)
-
- // With tasks present the list is virtualized (it fills a bounded-height container); the empty,
- // loading, and error states render as plain blocks since they need no windowing.
- const content =
- tasks.length > 0 ? (
- <VirtualizedTasksList
- tasks={tasks}
- selectedTaskId={selectedTaskId}
- hasMore={!!tasksNext}
- loadingMore={tasksLoadingMore}
- onLoadMore={() => loadMoreTasks()}
- />
- ) : tasksLoading ? (
- <div className="flex flex-col gap-1 px-1">
- <LemonSkeleton className="h-8" />
- <LemonSkeleton className="h-8 opacity-60" />
- <LemonSkeleton className="h-8 opacity-30" />
- </div>
- ) : // A failed load with no cached tasks must not look like "No tasks yet" — show the error + a retry.
- // A refresh that fails while tasks already exist keeps the stale list rather than wiping good data.
- tasksError ? (
- <LemonBanner
- type="error"
- className="mx-1"
- action={{ children: 'Retry', onClick: () => loadTasks(taskListParams) }}
- data-attr="tasks-load-error"
- >
- <p className="mb-0">We couldn't load your tasks.</p>
- <p className="text-muted mb-0">{tasksError}</p>
- </LemonBanner>
- ) : (
- <div className="flex flex-col items-center justify-center text-center py-8 text-muted">
- <p className="text-sm mb-0">
- {searchQuery || assigneeFilter !== 'for_you'
- ? 'No tasks match your filters'
- : // "For you" leaves scout runs out, so someone whose only tasks are scout runs
- // lands here. Point them at the filter that does show them.
- 'No tasks yet. Scout runs are under "My scouts".'}
- </p>
- </div>
- )
-
- const searchInput = (
- <div className="flex items-center gap-1">
- <Input
- type="search"
- placeholder="Search tasks…"
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- data-attr="tasks-search"
- className="flex-1"
- />
- <TaskAssigneeFilterMenu />
- </div>
- )
-
- if (isMobile) {
- // The virtualized list owns its own scroll inside this bounded-height column. The trailing
- // spacer ends the list above the floating create button so it never hides the last row.
- return (
- <div className="flex flex-col flex-1 min-h-0">
- <div className="shrink-0 lg:px-1">{searchInput}</div>
- <LemonDivider className="mb-0 mt-4" />
- <div className={cn('flex flex-col flex-1 min-h-0', tasks.length > 0 && '-mx-4')}>{content}</div>
- <LemonButton
- type="primary"
- icon={<IconPlus />}
- to={urls.taskNew()}
- size="large"
- data-attr="tasks-new-mobile"
- className="fixed bottom-[calc(1rem_+_env(safe-area-inset-bottom))] right-4 z-20 shadow-md"
- >
- New task
- </LemonButton>
- </div>
- )
- }
-
- const composerAlreadyOpen = selectedTaskId === null
-
- return (
- <div className="flex flex-col h-full min-h-0">
- <div className="flex items-center justify-between gap-1 py-2 pr-2 pl-1 shrink-0">
- <span className="text-sm font-semibold pl-1">Tasks</span>
- {/* Keyed remount: LemonButton swaps its root element (<a> ↔ <button>) when disabled
- toggles, stranding the tooltip's hover binding on the removed node. */}
- <LemonButton
- key={composerAlreadyOpen ? 'composer-open' : 'task-selected'}
- type="secondary"
- size="small"
- icon={<IconPlusSmall />}
- to={urls.taskNew()}
- data-attr="tasks-new"
- tooltip={composerAlreadyOpen ? undefined : 'New task'}
- disabledReason={
- composerAlreadyOpen ? "You're already on a new task. Enter a prompt to start it." : undefined
- }
- />
- </div>
- <div className="px-1 pb-4 shrink-0">{searchInput}</div>
- <LemonDivider className="m-0 shrink-0" />
-
- {/* flex-1 min-h-0 gives the virtualized list a bounded height to fill (it owns the scroll). */}
- <div className="flex flex-col flex-1 min-h-0">{content}</div>
- </div>
- )
-}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/VirtualizedTasksList.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/VirtualizedTasksList.tsx
deleted file mode 100644
index 05161a01d57a..000000000000
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/VirtualizedTasksList.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import { useVirtualizer } from '@tanstack/react-virtual'
-import { useCallback, useEffect, useRef } from 'react'
-
-import { Spinner } from 'lib/lemon-ui/Spinner'
-
-import { Task } from '../../../types/taskTypes'
-import { TaskListItem } from './TaskListItem'
-
-// Menu-item row height; the virtualizer's dynamic measurement corrects rows whose title wraps to two lines.
-const DEFAULT_TASK_ROW_HEIGHT = 40
-// Start fetching the next page this many rows before the end so it lands before the user hits the bottom.
-const LOAD_MORE_THRESHOLD = 5
-
-interface VirtualizedTasksListProps {
- tasks: Task[]
- /** Currently selected task id, used to highlight its row. */
- selectedTaskId: string | null
- /** Whether another page can be fetched (the response still has a `next` cursor). */
- hasMore: boolean
- /** Whether a page fetch is already in flight, to avoid duplicate loads. */
- loadingMore: boolean
- onLoadMore: () => void
-}
-
-export function VirtualizedTasksList({
- tasks,
- selectedTaskId,
- hasMore,
- loadingMore,
- onLoadMore,
-}: VirtualizedTasksListProps): JSX.Element {
- const scrollRef = useRef<HTMLDivElement>(null)
-
- // Stable per-task keys so pagination appends don't remount already-measured rows.
- const getItemKey = useCallback((index: number): string => tasks[index]?.id ?? '__tasks_loader__', [tasks])
-
- const virtualizer = useVirtualizer({
- // One extra row hosts the loader spinner while more pages remain.
- count: tasks.length + (hasMore ? 1 : 0),
- getScrollElement: () => scrollRef.current,
- estimateSize: () => DEFAULT_TASK_ROW_HEIGHT,
- overscan: 10,
- paddingStart: 16,
- paddingEnd: 16,
- getItemKey,
- })
-
- const virtualItems = virtualizer.getVirtualItems()
- const lastRenderedIndex = virtualItems[virtualItems.length - 1]?.index ?? -1
-
- useEffect(() => {
- if (hasMore && !loadingMore && lastRenderedIndex >= tasks.length - LOAD_MORE_THRESHOLD) {
- onLoadMore()
- }
- }, [hasMore, loadingMore, lastRenderedIndex, tasks.length, onLoadMore])
-
- return (
- <div
- ref={scrollRef}
- className="h-full overflow-y-auto overflow-x-hidden pb-[calc(5rem_+_env(safe-area-inset-bottom))]"
- >
- <div style={{ position: 'relative', width: '100%', height: virtualizer.getTotalSize() }}>
- {virtualItems.map((virtualRow) => {
- const task = tasks[virtualRow.index]
-
- return (
- <div
- key={virtualRow.key}
- data-index={virtualRow.index}
- ref={virtualizer.measureElement}
- className="px-4 lg:px-0"
- style={{
- position: 'absolute',
- top: 0,
- left: 0,
- width: '100%',
- transform: `translateY(${virtualRow.start}px)`,
- }}
- >
- {task ? (
- <TaskListItem task={task} isActive={task.id === selectedTaskId} />
- ) : (
- <div className="flex items-center justify-center py-3">
- <Spinner />
- </div>
- )}
- </div>
- )
- })}
- </div>
- </div>
- )
-}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index 4483d2170229..e333a82df746 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -96,6 +96,56 @@ describe('taskTrackerSceneLogic', () => {
toolEvents?.unmount()
})
+ it.each([
+ ['/ai', '/ai', { task: 'new-task' }],
+ ['/tasks/new', '/tasks/new-task', {}],
+ ])('keeps a newly created task in its host at %s', async (start, pathname, searchParams) => {
+ router.actions.push(start)
+ logic.mount()
+ logic.actions.setNewTaskData({ description: 'Summarize a sample funnel' })
+ await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.submitNewTask()).toFinishAllListeners()
+
+ expect(router.values.location.pathname).toBe(`/project/997${pathname}`)
+ expect(router.values.searchParams).toEqual(searchParams)
+ expect(logic.values.activeCreation).toMatchObject({ taskId: 'new-task', runId: 'run-1' })
+
+ router.actions.push('/ai?task=another-task')
+ expect(logic.values.activeCreation).toBeNull()
+ })
+
+ // Regression coverage: under the shared navigation a task or a chat is opened through the query
+ // string, so a pending creation that only remembered the pathname stayed attached, and the
+ // success navigation then pulled the user off the page they had just opened.
+ it.each([
+ ['another task', '/ai?task=another-task', { task: 'another-task' }],
+ ['a chat', '/ai?chat=another-chat', { chat: 'another-chat' }],
+ ])(
+ 'releases a pending creation when %s is opened from the same page',
+ async (_name, destination, expectedParams) => {
+ let finishCreation!: (response: [number, Record<string, unknown>]) => void
+ const creation = new Promise<[number, Record<string, unknown>]>((resolve) => {
+ finishCreation = resolve
+ })
+ useMocks({ post: { '/api/projects/:team/tasks/': () => creation } })
+ router.actions.push('/ai')
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setNewTaskData({ description: 'Summarize a sample funnel' })
+ logic.actions.submitNewTask()
+
+ router.actions.push(destination)
+ expect(logic.values.activeCreation).toBeNull()
+
+ await expectLogic(logic, () =>
+ finishCreation([200, { id: 'new-task', latest_run: { id: 'run-1' } }])
+ ).toFinishAllListeners()
+
+ expect(router.values.location.pathname).toBe('/project/997/ai')
+ expect(router.values.searchParams).toEqual(expectedParams)
+ }
+ )
+
it.each([
[null, ''],
['/tasks/another-task', ''],
@@ -658,7 +708,8 @@ describe('taskTrackerSceneLogic', () => {
expect(router.values.location.pathname).toContain(destination)
} else {
expect(logic.values.activeCreation).toMatchObject({ taskId: 'new-task', runId: 'run-1' })
- expect(router.values.location.pathname).toContain('/tasks/new-task')
+ expect(router.values.location.pathname).toBe('/project/997/ai')
+ expect(router.values.searchParams).toEqual({ task: 'new-task' })
}
} finally {
jest.useRealTimers()
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index ed91b4f80028..216175616c27 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -7,8 +7,10 @@ import { lemonToast } from '@posthog/lemon-ui'
import { ApiError } from 'lib/api-error'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { uuid } from 'lib/utils/dom'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { projectLogic } from 'scenes/projectLogic'
import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
+import { urls } from 'scenes/urls'
import { codeInvitesCheckAccessRetrieve, tasksCreate, tasksRunCreate } from 'products/tasks/frontend/generated/api'
import {
@@ -82,6 +84,17 @@ export interface TaskTrackerSceneLogicProps {
const LAST_REPOSITORY_CONFIG_STORAGE_KEY = 'posthog_ai.tasks.lastRepositoryConfig'
+/**
+ * The page a pending creation belongs to, before the created task has an id to compare against.
+ *
+ * `/ai` selects a task or a chat through the query string, so the pathname alone can't tell that the user
+ * opened a different one. `ask` is deliberately left out: the composer seed strips it from the URL as the
+ * seeded creation starts, and reading that as navigation would release the creation it just opened.
+ */
+function creationRouteKey(pathname: string, searchParams: Record<string, any>): string {
+ return `${pathname}|${searchParams.task ?? ''}|${searchParams.chat ?? ''}`
+}
+
/**
* The warm request for the current composer selection, or `null` when this selection can't be warmed.
*
@@ -664,7 +677,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
'active-creation',
{ pauseOnPageHidden: false }
)
- cache.creationPath = router.values.location.pathname
+ cache.creationRoute = creationRouteKey(router.values.location.pathname, router.values.searchParams)
actions.setActiveCreation({ streamKey, interactionKey: streamKey })
stream.actions.startOptimisticRun(description)
@@ -792,7 +805,11 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// An embedded instance (`panelId` set) keeps the run in place because the host renders
// `activeCreation` instead of navigating the main app to the `/tasks/:id` detail page.
if (!props.panelId) {
- router.actions.push(`/tasks/${newTask.id}`)
+ router.actions.push(
+ removeProjectIdIfPresent(router.values.location.pathname) === urls.ai()
+ ? urls.aiTask(newTask.id)
+ : urls.taskDetail(newTask.id)
+ )
}
} else {
actions.releaseApplyBackTargets(streamKey)
@@ -897,10 +914,9 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
},
})),
- events(({ actions, values }) => ({
+ events(({ actions }) => ({
afterMount: () => {
actions.loadDesktopAccess()
- actions.loadTasks(values.taskListParams)
actions.loadRepositories()
// Roll a headline seed once per mount (pickHeadline forces index 0 under Storybook for
// stable snapshots regardless of seed).
@@ -926,7 +942,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
activeCreation &&
(activeCreation.taskId
? activeCreation.taskId !== taskId
- : router.values.location.pathname !== cache.creationPath)
+ : creationRouteKey(router.values.location.pathname, router.values.searchParams) !==
+ cache.creationRoute)
) {
actions.clearActiveCreation()
}
@@ -935,6 +952,10 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// An embedded instance never navigates the main app on its own creation (see `submitNewTask`), so
// main-app URL changes are unrelated to its run — never release the side panel's active creation.
'/tasks/:taskId': ({ taskId }) => (props.panelId ? undefined : clearIfLeftCreatedTask(taskId)),
+ [urls.ai()]: (_, search) =>
+ props.panelId
+ ? undefined
+ : clearIfLeftCreatedTask(typeof search.task === 'string' ? search.task : undefined),
'*': () => (props.panelId ? undefined : clearIfLeftCreatedTask()),
}
}),
diff --git a/products/posthog_ai/frontend/types/taskTypes.ts b/products/posthog_ai/frontend/types/taskTypes.ts
index 4da48e3a6a38..3e4d061aec9a 100644
--- a/products/posthog_ai/frontend/types/taskTypes.ts
+++ b/products/posthog_ai/frontend/types/taskTypes.ts
@@ -1,6 +1,10 @@
import { Optional } from 'lib/utils/types'
-import { type TaskRunDetailDTOApi, TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
+import {
+ type TaskRunDetailDTOApi,
+ TaskRuntimeEnumApi,
+ type TasksListOrdering,
+} from 'products/tasks/frontend/generated/api.schemas'
export function isPiTaskRuntime(runtime: TaskRuntimeEnumApi | undefined): boolean {
return runtime === TaskRuntimeEnumApi.Pi
@@ -72,6 +76,12 @@ export interface Task {
latest_run: TaskRun | null
created_at: string
updated_at: string
+ /**
+ * When something last happened in the task (a thread message, or a run starting, streaming, or
+ * finishing). Deliberately decoupled from `updated_at`, which only moves when the row is edited —
+ * a run can stream for hours without touching it. Null for rows written outside the ORM.
+ */
+ last_activity_at?: string | null
created_by: {
id: number
uuid: string
@@ -97,8 +107,15 @@ export interface TaskListParams {
internal?: 'true' | 'false' | 'all'
search?: string
status?: TaskRunStatus
- /** Staff-only. List every task on the team, bypassing the per-user visibility filter. Ignored server-side for non-staff. */
+ /**
+ * Drops the `created_by` pin, so the list widens to every task the caller can read.
+ * The server's full bypass of the per-user visibility filter is local development only: it needs
+ * `ph_debug=true` on the internal debug team, and staff alone does not unlock it. Production
+ * therefore returns the caller's readable tasks, not every task on the team.
+ */
all_team_tasks?: boolean
+ /** Sort order; the server defaults to `-created_at` when unset. */
+ ordering?: TasksListOrdering
/** Page size (LimitOffset pagination); the viewset caps it at 100. */
limit?: number
offset?: number
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index b7b8cc2d2c96..6a7946d69b70 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -189,6 +189,11 @@
"params": [],
"scope": "project"
},
+ "aiTask": {
+ "template": "/ai",
+ "params": [],
+ "scope": "project"
+ },
"alert": {
"template": "/alerts",
"params": [],