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(tasks): add team and user default models for task agent runs (#70683)

Vojta Bartoš7c748a7740c7
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 10e4d775afee..39b4c34d4bb0 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -202,6 +202,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"TeamDataWarehouseConfig",
"TeamExperimentsConfig",
"TeamFeatureFlagsConfig",
+ "TeamTasksConfig",
"TeamLogsConfig",
"TeamMarketingAnalyticsConfig",
"TeamRevenueAnalyticsConfig",
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 5494bdc42aa8..90347cf6c9a6 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -354,6 +354,7 @@ rules:
|TaskWorkflowDispatch
|TaskSearchDocument
|TaskSession
+ |UserTasksConfig
|TaskThreadMessage
|TaskThreadMessageMention
|Channel
@@ -732,6 +733,7 @@ rules:
|TaskRun
|TaskWorkflowDispatch
|TaskSession
+ |UserTasksConfig
|TaskThreadMessage
|TaskThreadMessageMention
|Channel
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b54ceb0bd446..f28e0eb4dfee 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1997,9 +1997,9 @@ snapshots:
components-search--product-recents-and-starred--light:
hash: v1.k794b7964.f2c75682469c037327f94f22550286ed866d4883e03ef7c66a3f234a31b1017b.1gKkr-42m5_F8qJMq6ahElSjOFRERpPTay3A0__UOo0
components-search--searching--dark:
- hash: v1.k794b7964.7b5de739918a3105f14ef1b5c831b8ddc13f3e33cbf3f2d99f45b74e1bdb5212.Vml_l6q1RdulTgTpPJtHtfW26V4T71fyXmdz1e8eakk
+ hash: v1.k794b7964.b5b6392f03b88199976388751bd330e913a0bacaa169cfbd7556e31d938b031b.WojPbjfmz4xLp10A6oORUyfgggXE27MbiDetkbVfVtU
components-search--searching--light:
- hash: v1.k794b7964.749679cdf00b2d0892c9132e603542b4eab245e0ec4ac480e4cde730173e8fb3.nU303Ca0l5AQaU3QJBLpStoi54YwzrVTwJSrD5ggQL4
+ hash: v1.k794b7964.89872c07596f30d630ef8416102ea447a1ded4e66c0edca46017095620a090ab.UkIcBzbQDZt16dnO-Xph7b06JgK7nDAP3o0AP-1ra1E
components-sentencelist--full-sentence--dark:
hash: v1.k794b7964.7e8e5dd2e09d246cc3668f362f2391fe67618bd1143aa393832297f5dc30e558.yptEWKc5RAUY613Fwd5cQ0VIinMvpdoI6cuKgagAGxk
components-sentencelist--full-sentence--light:
@@ -8321,107 +8321,107 @@ snapshots:
scenes-app-settings-authentication-domains--boost-needs-upgrade--light:
hash: v1.k794b7964.f2e9c2eb21a4c51655c4a3a0aa51337cfb25a148b09b2b9e287eeb8e0cb108af.t6ZC79QgERyt8zxKmk77gqilvhiKGt4Wpyo1eN3l0Fg
scenes-app-settings-authentication-domains--enterprise-mixed--dark:
- hash: v1.k794b7964.3a79302e05dc7901dae87f7c32770b88d4fdb9e81bd889be4885bd1fb3e61efc.0-I8CGximFaHRl67GnS-U5dHTPVBFi6ewETJLCPVxKk
+ hash: v1.k794b7964.108c87c596109921b63f0a0d31a15f573332b30f0dffd7cd6188c0122d7f710f.cFlzhGvQoqCOJL5vynqvLCJZbE9MXFyrK6L6AgCJWvA
scenes-app-settings-authentication-domains--enterprise-mixed--light:
- hash: v1.k794b7964.107a26b0e6bf1d40c81a73e1f0297b2383dbccb9f9db80967a411394832ebc6d.Jz7K67QaKgv0b-BUVOnryqFg-IwTL4FeRv5GT3XJNfg
+ hash: v1.k794b7964.40932ded575174a10f507abcd661f02ef7bf721c5546b00f9614f6bcf7063f58.NDMSU-rKHfmmwNCmAyRzPPRKyfMl2M7_PfL9hcZvDSY
scenes-app-settings-authentication-domains--enterprise-redesigned--dark:
- hash: v1.k794b7964.843775d90f60d073a0289a8d4e3b44fe57a0b46d4f944c2d4143b94767ab76b3.jVd02nb9oxc2_jjzZUjjKigjioJ9Z0Mi-taTFwTqlmM
+ hash: v1.k794b7964.a96c5ab25f9a8c9c9f43b6c845fe17577e04b84b19f38778f0651f124bc8ad8b.BTnTtkK_oKiaZzH5X-8nUmd1Xvzy0IRZnGkHWFbIz7Y
scenes-app-settings-authentication-domains--enterprise-redesigned--light:
- hash: v1.k794b7964.381545e2ec419ea92fbc63dc004d9b7f7e1977f4eb1d5c8dd8aadf2fc8e4f109.oUtrDDKcm-sDAEKYKxrdHB1LdD6AgSuO9IPsNrbNltw
+ hash: v1.k794b7964.1c6061a7cb2babc063fb5872b7ffc79acb513ad41eec2af0da1fc04f6e9a2930.nLhUebfXcY6fCTNb3mOXfCz6SNk9-nxWfjZEHjK3gGk
scenes-app-settings-authentication-domains--enterprise-redesigned-not-configured--dark:
- hash: v1.k794b7964.0d70a3fafe00daf6006308afbc2905ef5aa1b70e0b3d2c552fceac6943e1829e.HKBvZmtYFRW-h7wmHprZOq_1vsl2I4KA4jG6NXbdKKw
+ hash: v1.k794b7964.2fdc9a20542dea412ee10393c75a2039283875f7e959f0f2de01c11a45e98750.0lydVdG76e3mbLl2ts4aLlgp0nW3LvB-fh0wBuHHqI8
scenes-app-settings-authentication-domains--enterprise-redesigned-not-configured--light:
- hash: v1.k794b7964.8e609b0a4670b1ac54fe089f546f7b5738c9dd0e2c494cefca71edecf0ec3665.lDfkPm-z-FeNF-8YedixP0jkJxMm_NdMi7ziInt6mJk
+ hash: v1.k794b7964.f6fbf0d09cd3f8e831fe9be8d1c582a79467f94b0791356bfc54a10a58c594bc.HCC-fvhlRh7md1tIrNnv6Ztb3ney24usQOnx65ooIDM
scenes-app-settings-authentication-domains--enterprise-redesigned-partially-configured--dark:
- hash: v1.k794b7964.4eb15b95f5f69aedac4d91cd255bd05211af52955f16adedf78ab201ebb51fa6.n414ChvQre8_ZqBV5GZLIqkmamwmwENnQ6KJLBGiTAY
+ hash: v1.k794b7964.5c272a77606e8727b8d41d3ed7c309a341e5d71164c4c0070c50091a64041d66.WquEiNdfptYw31QiZj0ubKn2jCSkkw8z9s1ZDIN-05o
scenes-app-settings-authentication-domains--enterprise-redesigned-partially-configured--light:
- hash: v1.k794b7964.d07f68500fc6c3abed420978b7e58f543ad6b65c510589d1c7f3ac581df1046f.d2keUaRFCTvah3BZwGVehFSIZtBHnTDSrCB8JwwytbI
+ hash: v1.k794b7964.5b07c4ae5675d77ca2e99d84f959e2090d4ef39b27bc284501d6f1ab08ab8258.kiqvVkGTPkUnNFaucQv0CIz3tFgfA2_SL3r8VIIFUAI
scenes-app-settings-authentication-domains--no-domains--dark:
- hash: v1.k794b7964.c74f79241a848394887ac511de002b4ca628cab0501d91d524e8a00796256219.K_aW3PO6ztJ5Ud3eyR0RBjJ0-xtroy9Z_i2u7pBjyZg
+ hash: v1.k794b7964.5c8bc48d98f10a9efd4d1fafa6722d3381833f215ea82a28513c57a1fe765041.lo9x0c4PjWT1botVgJurhdR_I3qVX8hg51CihShtn4E
scenes-app-settings-authentication-domains--no-domains--light:
- hash: v1.k794b7964.37755257eeeb09bcb190a4623e6554e356ffcc6b4e61086b8d2427a3796af34b.eJhnmp6Mqw_TfNQhRHgzZylOtfr8VMwxaRjOdzUHuiI
+ hash: v1.k794b7964.62e9606c6fc3ad03f66212a2297becccc25c54a3aca53538d3774784c968e963.wg2hA3OQoZz8rC_XYdLkvFzINODB5d2WCvQVDJVYX7s
scenes-app-settings-authentication-domains--one-unverified-domain--dark:
- hash: v1.k794b7964.8d6bbbc38ca11184bf0db82d2eb03da5e10564e0a2c2c80177f481d686c4d292.XR2LOmWg7Nkr_Ww68b5uenhYerh1ZAGwI2b_x2SDgvk
+ hash: v1.k794b7964.8ae32ffb957adf75d2a84fd9ff7b483db433b725b7848139ec093dcd66d284b2.4nQJHb7vxDmInsfm3fyYZIANa4XQo8idgvGtxi3eX_A
scenes-app-settings-authentication-domains--one-unverified-domain--light:
- hash: v1.k794b7964.826b954e1c03e3156d0c10598975c3fd43583672372c163fa08264506f929cd7.C22X_4g68JpmDtmjwe33M24AQZ4CTTIwW2cMZPL0JCo
+ hash: v1.k794b7964.c8a0f7769778cddceb7039294f329579d3cbd4cebf8213244bb587e31b3594e7.M2L5rnKZhsweIrTL7P1WVrsy7iU_rXs5cgCg7OVX45c
scenes-app-settings-authentication-domains--redesigned-needs-upgrade--dark:
- hash: v1.k794b7964.f8192b194fbb4fa39bd378b17481a8f0b9a51a10bfbce6fa1066b56977f0cacb.Wggik125fZlOESF9Qm7nukIjrd1bRV7yBMPEGaGQYP8
+ hash: v1.k794b7964.921c4829637465833f4ba5097f830a98f4a1a876df15bd8bc42985ea7732735f.aEP0S3QLtuDeX0No-xM4PvLEpMrChH0-TRfx-vjm-CI
scenes-app-settings-authentication-domains--redesigned-needs-upgrade--light:
- hash: v1.k794b7964.4b5a266868dc1940520295c984cfb39605c4d390c8c4ff95ea6e2feb18b83322.u3WQPP9cbRpyWOVVLcKqirce0oSloq_Kmf5nsxwe-uk
+ hash: v1.k794b7964.87f701cbae0118c13f2bc5d4ee5d2ba6b325a8bf40d1500e045a89894f6c2a8d.BPLSU7sY_VBMrCQeaUrvDKKcJhsk81kfy7gBaG9KNpI
scenes-app-settings-environment--settings-environment-access-control--dark:
hash: v1.k794b7964.c9ccaaba4bf03f6923b41fe85e387d17139a6d7d69a6e06913a37cb5dd019532.bpCeuesKb9InCkdPuMqRPNFckeU7o1u6QcQfQf5ogSE
scenes-app-settings-environment--settings-environment-access-control--light:
hash: v1.k794b7964.e2a2721a0bbfca9bb459d0b991cedd912f1af81eff8ff15996bcc73984417aee.j7jFwv6YnpcoUKYfoXaZaluFS2_lDIFHE7TtSSvBOlI
scenes-app-settings-environment--settings-environment-autocapture--dark:
- hash: v1.k794b7964.2183cf0082a1556d6df553572df4ab3813c96288a8b9a80e669c005908230c3e.-ybX8d6KyxaSa-yJDVccZm2CkK8Fl8qLSbw9jGhSIx4
+ hash: v1.k794b7964.8defefc8ee81d152212ad970ee03afd0170e149183c700875620b83c94041edb.1GgekWHSuFhNxSx6MSUDbX9I0RjLB_eJK_x9Y356OXU
scenes-app-settings-environment--settings-environment-autocapture--light:
- hash: v1.k794b7964.9ef469fe5d9773481881830b71fe22637d5e90ebb4575b6c73be94c798e5deb5.6sbis8zsRXgxhP6EHAqTWJiGr4DDIqOOfSsIcDZu--8
+ hash: v1.k794b7964.397d4848babe9a8d2fd98b15ffe998d685521cb5135ff4ad1a70951e6062ec71.lHocWsuL-A9IGiBxs67-309ZaiJNT6VF4vCrp962Ctw
scenes-app-settings-environment--settings-environment-csp-reporting--dark:
- hash: v1.k794b7964.a344bd7d74f3836596742927cc416d9e7143a3f34b19aa8e11f885e4cfa6c496.bJQvxjCsvIEnkyDVzXlPeNgOS18QHi6hU2m9WYJi-8o
+ hash: v1.k794b7964.3723594a81604be934dc679e9468874356486722c63ee6131f8058f00a0dff70.5xrmmv44yWNLB3iddpZGdJOsA5tRM1m7BwvZ01dANlA
scenes-app-settings-environment--settings-environment-csp-reporting--light:
- hash: v1.k794b7964.fd469d98fbaae429c7a81f49593b7f5723a4e068f3ceb03ed5f047b0535e227c.NLE5KInsuUjiK_nTGOj4Pgh43vBGeZXEgKsn6Rw5hXQ
+ hash: v1.k794b7964.a842c3f0ee5a6731d1051c47f04fd6da35d42f85cc3e0ba40afba80d2ea66b91.uj0d249fCiw0N7_QZI0owaFQ77omJCKRsMDMnmJrX5k
scenes-app-settings-environment--settings-environment-customization--dark:
- hash: v1.k794b7964.b2b538c8df6d6b783d47c2be8817bb2f861b008fa847c50d5c99af59cbfa4cac.i6X_OHC5u_KV0XlPvyAcdu8QrZ93MD0OrVZQmaPcgMI
+ hash: v1.k794b7964.20a4c0114ee5bc5239d8f7379d3b524fab7792f5cbe4e955af67f2b628c6740a.B2_rKR1OO-ZWVFAXJIorDCuW7DQI7cccnguK9OQ1crQ
scenes-app-settings-environment--settings-environment-customization--light:
- hash: v1.k794b7964.a393b6bb989d93d6b36362c11e1d6dfb4019d8d631c0d250ec0cc295301e2b96.Hn0smGMdrsefh679kAsc4_NCm7DZwG063H7cj1I5iiM
+ hash: v1.k794b7964.90efacec6b8b33b059eb3574c8379b997f3774b71a6b8b5f044abacceab629d6.dE0G8aMXIav3GKTW7wwf0rXCFnhSzF2YCOLu3nRtvu8
scenes-app-settings-environment--settings-environment-danger-zone--dark:
- hash: v1.k794b7964.b2709895d612381724c2275aeaa291853ad3460c7a70f82f44f9b68b53d48da7.5LGiSsDKJB9hs5AsxbeWNNMpCqNP39jEiu5P91ZXcGY
+ hash: v1.k794b7964.586910a373b9a9cf63d114f527d0bb8580033d25a81be6f830e07bf244a7c316.-ID92-MgwgAf0sdCeF84tYBSJ1RcHGOvApRVSsJNYeE
scenes-app-settings-environment--settings-environment-danger-zone--light:
- hash: v1.k794b7964.d4b5e0030757796876fa680f389ca76201f098f3b1b65eb303ca73b5e1be6ae4.ZOx74ZcJLsqbVA90pvoVi3CB4HTXwYLSPYjCqN2ZAc8
+ hash: v1.k794b7964.2f88af8027b27ba1f501476836abac1f4267142ccbcc55edde60d7c313e1a3ac.3cRp6vCr-SWYXLUZPlBr1wLywjk75Fz4AVncZt28Y-w
scenes-app-settings-environment--settings-environment-details--dark:
- hash: v1.k794b7964.e5e03f4c2344daa40a41b7ee79a43fdd3124ffcfb53952ddaee65228ba4687f8.2i4m52DzdEshDo85sF5UhmWywcMc_gbf38lqwygCTQo
+ hash: v1.k794b7964.586910a373b9a9cf63d114f527d0bb8580033d25a81be6f830e07bf244a7c316.AVV72X9fcKhnOkfheY9j7OZhh6KG1Yy_PxKskBsYYr0
scenes-app-settings-environment--settings-environment-details--light:
- hash: v1.k794b7964.d4b5e0030757796876fa680f389ca76201f098f3b1b65eb303ca73b5e1be6ae4.nm2ebJO-70lgkubc-wOB4EFtPnO-885kq4I93mt0TNs
+ hash: v1.k794b7964.2f88af8027b27ba1f501476836abac1f4267142ccbcc55edde60d7c313e1a3ac.n63FdGA48rC3kVk0HimuNrt56IIiyvKnrwQPxKRSsiU
scenes-app-settings-environment--settings-environment-error-tracking--dark:
- hash: v1.k794b7964.e6cf54c9386285877955daddf35940e48e435cf6d1e5040662c4e239ebd97fb8.vT3knk-UEsF5TKxAOnmLdi_4uIfbHYfBRW8Zz51BryA
+ hash: v1.k794b7964.f6c8b8c2726bce22aba11706a37707cdc206c27f0dcedba1afb0d139ea9793ca.uzaqmTbJqdTizTPO0lI27FZKaTVuNiO_jQpD7SJKGFc
scenes-app-settings-environment--settings-environment-error-tracking--light:
- hash: v1.k794b7964.5ac167271f00184ce6159d0072ce163542658b08419f6e70b5cf6a6ca201a718.X6dKpM6uGw_g_FAwdQ5PukTVcKWGAa77bMOzgw-kiXY
+ hash: v1.k794b7964.24eab8142b2b935340cf876e03fea9017f537be55894c67244d826aba11e32aa.hLonDyz9UamqstkzKg-IaCJ0RkvSNWRfCtK-rEwHZaE
scenes-app-settings-environment--settings-environment-error-tracking-configuration--dark:
hash: v1.k794b7964.3d7a3006130bdc66e1456cb81566e21bb2179f19d17caf91ead7a41ba4be9234.tbIKl_Tlb1T7RBNR3Ic9n51t6kNpTkGsw28sXZHW-Gs
scenes-app-settings-environment--settings-environment-error-tracking-configuration--light:
hash: v1.k794b7964.7d62fa47841096cceaa13c9a7cb15c1152b2f929ee030674bc0d97c5bc66c239.GptZ3dbdhoABnDP-dWhaqUCQOTeKYOsMFokkyWuNjwQ
scenes-app-settings-environment--settings-environment-feature-flags--dark:
- hash: v1.k794b7964.56670f556ffac0360ec521741db9822f4e545e25b45bd8ed4ad012da8885c30a.qj9dLuAFy8v0TwEH-UTymXnlWPe2eu-YjAOpe2zc3Q8
+ hash: v1.k794b7964.c624ec79ffb024f5c696bfcbad8b9064bd14c5a9dcd5bf8cbede79619a7e49e6.dH9TnaljbVHGlDeLswbLC1fMhgjhpV1m9vMIflWx8A0
scenes-app-settings-environment--settings-environment-feature-flags--light:
- hash: v1.k794b7964.a75d48c515b605a99cfd76c57830849c850c07ae3694e73b52c117095e489497.bh3Qsafj4UigFS0Z-DDe15ZdQwiilaKZWTR4-ESKijI
+ hash: v1.k794b7964.4600cafc552dd45dd31dd0fa332c43520ac385fe26989554d0d96ae64853ebd4.yLyNFD0f4Xs0aAkEwfdeGR1acGWM1K8NAMMYocpUFBM
scenes-app-settings-environment--settings-environment-heatmaps--dark:
- hash: v1.k794b7964.1562a01b0a70e04f8e738a84b1f4fad61f94fde8e35b5768179e1c230485ee57.v2cJdkb0JPIw7-6TIaaSWqiJMrjU5pb9YRj09dwvGfQ
+ hash: v1.k794b7964.e217c83d622c4dcf42234a33170cdeea692e1688ea84cacd41891af1b1c8eab5.PfryefOdpcOK2e69VOc4ShxwiAjxVzXciIhVF3-s9jU
scenes-app-settings-environment--settings-environment-heatmaps--light:
- hash: v1.k794b7964.05c858527b6a3deecc54799e4d4fad6c2b88ff83a26dc0baadff3448bf6635b4.u3Xak3I8OzaYGlO_KlLOvHMh7sWvmjOVDrKURMJBQLs
+ hash: v1.k794b7964.e4288444e37724d683fa2fbbf5a51ab0492fd48c4916434e351ab29fb2c5b351.c-AReSv9uTZ7o6ZoZRM1yPxQJ2r95YegRYBjlbCpy8s
scenes-app-settings-environment--settings-environment-integrations--dark:
- hash: v1.k794b7964.eab246ccd1136c9853b8c784aee1ed549e3410869c14caf0ecdc44d4aadb7afa.OKw8YuAkErqsXqkceBujJ31q0OfGd13jMbDXDY6R5Rs
+ hash: v1.k794b7964.1aa226e2340f780cab3be2c4c58df4aa306c192093f889275b54db44761ed25e.ccM_UnCvJUb9zfhFndR5ofGzycIBCfRJXSqDwIF7SBc
scenes-app-settings-environment--settings-environment-integrations--light:
- hash: v1.k794b7964.676337e86614067960e5921914c746aa754fca36c8661e45f4413e9bab9f45eb.ARcWzCLx7_AvaL7WC9dutNLoampsgNI0YsTQ2d5vfEk
+ hash: v1.k794b7964.78000b9fb5415dc591e2d554b15eda54e4cf236fea779b643c8d00bfabe01024.p6Ujh3FxCnQ_41qRipE2VOs75GXpswtsVvrmoqJH0OU
scenes-app-settings-environment--settings-environment-marketing-analytics--dark:
- hash: v1.k794b7964.0c2038ca1ba04301309d89f6abed6353c1cd1cc948342a960ecfcce3a9619a48.K04BuaEcGkJJ30IFKapU7MOOl-6jjagnB0ZddGTrkaU
+ hash: v1.k794b7964.6fda112d7e907b0580ca43fa0d81490fbbac26c0a94fa440f8d29e6cd0df7819.beqB-GcbyDLLUIJE16RriuZ77_VdVwn9gcd5uZdc9Ps
scenes-app-settings-environment--settings-environment-marketing-analytics--light:
- hash: v1.k794b7964.dfd28876bac00e6bb2aa3ab49bcd2c9e70278cda4faa5eb3670e3b381ed2302a.1AcmLKo0J4iBvrfykKx0r-bmrYe1VsQ8w2tPLai2D8Y
+ hash: v1.k794b7964.e128ae9b216e65b3538ada9e554650d40a0c20657ea92ba73832bc3e8f30c43f.hmtrpSKPGWHckiOIkWUMG_nRc1VPxBYcJayfpfOwGRk
scenes-app-settings-environment--settings-environment-max--dark:
- hash: v1.k794b7964.5fba71e345f66c96bd52f80c2d78ee18a79f717cfc32188057c677cb0837b79b.BK_CfpOtoMIJqBf8dKx9h8mKmik2W-B9npTPyW3-nSM
+ hash: v1.k794b7964.10de30368179db18ceff52d0f6b407a5c51e77fab7f802975c982fd1bda8cfb5.b-2EhAiwfOMLrB-AhJWGRvIfxZ7v8ZDngl6e1quRSXE
scenes-app-settings-environment--settings-environment-max--light:
- hash: v1.k794b7964.07164181401e2754e235fd3c4b4bb7469e1568fb7d0dc0546a69050c4106b515._mo4cd-H1bIxLf_3v_wWV51fDPnglyLk8gd0AOF2orA
+ hash: v1.k794b7964.6e379c5f60d4111fc73ebed2fbf2eb318af47138ff026bf1727643bf9526bfa1.3rnuzvS968zzKhtViiWbQuYCDjPjnaBfJU5eRvk3xKQ
scenes-app-settings-environment--settings-environment-privacy--dark:
- hash: v1.k794b7964.d7e0744dc2018ac69eacfc1079f9573e17880bf27cc76d88a2cbfe1eb8bc36c9.F7HP9RQaWx4NtnLbJ6q00w44rjXGhEScXnNMvWqR68s
+ hash: v1.k794b7964.8b706ecfab6bfeab8d6151358a40be05b454272cdf7707e351e46c0b3b1f895f._J0xKene9zTgvU3WnktzmalGcaOAHTw2CmIeYTBr2yI
scenes-app-settings-environment--settings-environment-privacy--light:
- hash: v1.k794b7964.8a66709400822bfa0ce716ad8ab87c844f6e255d6d147ffc1d0786ae6f0c88a4.YpDwS8AJgUCgRHrbfP00tREEmFzdh7uSlh1jUPiZwgk
+ hash: v1.k794b7964.bb73820f77fc306f6e5b117a93ca3866a5909d66028abb78c39603a3c626573c.cg2WRsv88gr8fEVoyCYZ88tGVptScIN6bYKdsQnsM4E
scenes-app-settings-environment--settings-environment-product-analytics--dark:
- hash: v1.k794b7964.f0bb165601b375795b1440ba408d76fb5a24321c168532c927ec3667a242ae37.WtinNtrrUMh5H-EeXUWPQo-C-4h1ro_YhnnqfXousu4
+ hash: v1.k794b7964.1fef081a30244913d7af1c0489e69591279037f958fd11d6b9a8358bad8c8944.r6B-hRoH3q1PWY32YV8WQ6dlGdC3UXlWaxCQSv1_g1o
scenes-app-settings-environment--settings-environment-product-analytics--light:
- hash: v1.k794b7964.70bf7959ecd4f39a1ac0d069beec0f6cdaf24d9afaee70e70b4cf75619f56de5.xQCvIAWzmRCUGafz6moNuItTspGJA6dwjKLb3mE16Uk
+ hash: v1.k794b7964.0f591a3aec17fa23dbe9faaeb8c158d20c851e1f1aef7733ac4dd034e0f77269.YAIPB4LQdDIS6ovHSYMQDhnRWIMG--vbs5iEP6YCGRk
scenes-app-settings-environment--settings-environment-replay--dark:
hash: v1.k794b7964.42643eba5e571cd19b8da6a56ab4dcf0c38b78a143e66bbe8b281bfab9701687.rkZDYwuuvWK4tFHCoBKaPoZZiawEzTJoVySnlduobP4
scenes-app-settings-environment--settings-environment-replay--light:
hash: v1.k794b7964.e0e88948b99c8a38e602dfe6ff8c26f68c346742b703d9b85e8a7ee319501e42.BPVUCBswE78Ps2DAYwsH5YW-rayV4hi7jswSw5UKwAM
scenes-app-settings-environment--settings-environment-revenue-analytics--dark:
- hash: v1.k794b7964.1b59813d53eb3cf7f0505a250ff6dcac0c25785011679e74420d389dabe25582.Gn5HB_rvDNmwFNIlRts1ZZ17hRhFJ88yILUevtuwy0g
+ hash: v1.k794b7964.737806fa824229e06cab2f6c02e531b33a3003df6cfe59119dd8bc769914acb6.zYPY7CyMuafB3i_N4VD1oW-MiD7SWBqlG3ewH7KOwC8
scenes-app-settings-environment--settings-environment-revenue-analytics--light:
- hash: v1.k794b7964.77cf085b98ea239ac8099dc7029e7d5f3119a63c0acc0f2975ab1cd0cd9d1352.Ntrf1s6Mgj0jsR4plqravLs06H-iQKoXPS66gC1cKf4
+ hash: v1.k794b7964.9016357e0bf3399f7f7ab0a72ae85cf76f99220d94b763bb7c4e5223f5204c7c.P1MrRxAt8_StJxcjAE68Paf7cCy5-yqwLNiNZx-P36I
scenes-app-settings-environment--settings-environment-surveys--dark:
- hash: v1.k794b7964.9424008ef6e0bc475ae46dcc42939d11a90dc71893efa8dde13301f4eea41a1d.mV1JbZ4Ez9GVNnY_PeUUH8FLUujg4SphJv1J42gOWws
+ hash: v1.k794b7964.5263da8ba06a17af7684b53b726e7cb6836f4190c36578c51f9259177beb8cdc.anfdcEu9d90qvC-AjriNQuz0WVrwKY88QNDHrDAwWxU
scenes-app-settings-environment--settings-environment-surveys--light:
- hash: v1.k794b7964.82a6d0673ae37171eb0f50012e837e8417d965f747a21d0a728425dd53209fc1.YyKQuLivmwjiIilN3bvDszBRrnZ207pshWSu8nSp_j4
+ hash: v1.k794b7964.44354f487f0f9c1e8e24cc2e6247265571d4092d02f2708f644226afaaa64ca4.9PFYDux0v89SlcP4qzLl2QLWPtFqBDz7EMAKehKyd30
scenes-app-settings-environment--settings-environment-web-analytics--dark:
- hash: v1.k794b7964.a567e4149d492d035796f56fba2a0d9ce9b92c728e0482caf7a0411b8f6c2cfa.iB20iEO2ClZEgTxEgoJyBGUCjDTp7zYjnXkUfG0S-bE
+ hash: v1.k794b7964.eb79f313f1c5dbf00e0689c0146e5116234b52f8835fd7d5c3fe2f9b41cf1bbb.2ixJGP2YQe4fQy9SW5hHOT5Kwam27dvHJgJps1yZ3h8
scenes-app-settings-environment--settings-environment-web-analytics--light:
hash: v1.k794b7964.e319bd2edb8a9c629f2e8c6c01900ac1d603faf2e751ec10bcaa9021305c71f3.92jZVjrbRQ_R17e0vaR0uRtzu6t6ss_cuAWyg9-1md8
scenes-app-settings-identity-provider-configuration--saml--dark:
@@ -8445,105 +8445,105 @@ snapshots:
scenes-app-settings-identity-provider-configuration--xaa-needs-upgrade--light:
hash: v1.k794b7964.9d93b0682bf14e191da3fa9614a1500ec01fbe7a9c313680c5fa2d776ae65806.KFggaDLcSJvceGa1JimS0m5ayPo6m_OtoH7_tzeqR-8
scenes-app-settings-organization--settings-organization-authentication--dark:
- hash: v1.k794b7964.5b76bcaed658869e97ff2d15c91554833182cfc09863f10ebaf519d5c99b92f5.vMFYe_DUaRNj5T-zABsbjXs3omFMD95Ch0h4pldlKbQ
+ hash: v1.k794b7964.a92c53208573be95eb2d121a63c97da2e0cb42acb4e1b3e91d84f84f66b1c961.WPCnXrULsBNC4Eg9DhVZ2_2P5WgGl5yJ0DKxCMznCYo
scenes-app-settings-organization--settings-organization-authentication--light:
- hash: v1.k794b7964.18c8d0fa52ff3494e6f990156901958a35eb96bdbb3893f73e0ca7bb11763bf2.B_W6hHr15JDLi0VWDw8tBn-gMf5hDB4XuwUZZFAmMuM
+ hash: v1.k794b7964.96a9e91d0b28deb7de9118d277d5909a9e155bb1685106d8d9659bfbbd895b97.PPexQj6we-P3SwhqOr9hULNB6P-kIdD9d3qnobJr_SI
scenes-app-settings-organization--settings-organization-billing--dark:
- hash: v1.k794b7964.b2709895d612381724c2275aeaa291853ad3460c7a70f82f44f9b68b53d48da7.Jz5OoUecWaosBkoyKe1t79ypi05lM4inlLcCVqXXESo
+ hash: v1.k794b7964.586910a373b9a9cf63d114f527d0bb8580033d25a81be6f830e07bf244a7c316.ddsAKbm-zY3SbnudYISUg1QKtsIxUJxu4nCHOlMx4bo
scenes-app-settings-organization--settings-organization-billing--light:
- hash: v1.k794b7964.d4b5e0030757796876fa680f389ca76201f098f3b1b65eb303ca73b5e1be6ae4.bisG2Rrhp6kgmqbOtUQGs_484Kn8TkyRsaRSBlNVVl4
+ hash: v1.k794b7964.2f88af8027b27ba1f501476836abac1f4267142ccbcc55edde60d7c313e1a3ac.YTLCZdF1s_pbiELr-YwAvxB6U8QuC8u4DZpwmPYF2bo
scenes-app-settings-organization--settings-organization-cimd-verification-tokens--dark:
- hash: v1.k794b7964.a0efb34409ff03a8a94d527a39101882a124357800b9ebce870c124ba665b643.H5ZBcbmWeVY9BgSRWeSYkjfOCmCRmGGsipKPFigGqUA
+ hash: v1.k794b7964.922fb84f5e21a68406330a9a63e84156d2498cff3a703b8df438b9325e8941f1.BD-HYgMGIB3YXxozWZHy5IWlD_T14h12a7QDGkm-EtU
scenes-app-settings-organization--settings-organization-cimd-verification-tokens--light:
- hash: v1.k794b7964.a170546647ece777290b1868dc4c9fb6b4c67d2f4d63c2aed321f3155220fb4b.H1Y1g89WwXye_1nxkBwTgMxkT6a0hqW7SV6cFKtFJtU
+ hash: v1.k794b7964.4c9a9514329c8312c2747c5f292b5039f48a8e8098ec025683a0b101549a9823.kMjmWPVmjqlINGC1hrKQ1aBZ6bDqORXXig3MlKSM3lY
scenes-app-settings-organization--settings-organization-danger-zone--dark:
- hash: v1.k794b7964.459d4562ee5b565df4810e3d27235dd302cf95293a62903e35bfef2ed1c21a77.9b4ajnjIa9Fmj4VPX98HECmrnRzyeHsjwUYdxIypN24
+ hash: v1.k794b7964.539893ae72f831a39bd8636b92439fed51965bcc4384092aafffde78d6dcaf97.sbWNCVMXvFJDHlwfmUGX6fjUh9Gu_sQO0jNUXwUbQtU
scenes-app-settings-organization--settings-organization-danger-zone--light:
- hash: v1.k794b7964.19386d6d09b047ca2d49fd8582eb35e3938b7af6ce93d404800c3792a29c1920.1lKFcp1iYxB0ZFGEv-VVd4kp2SzOR2pNFXvGi5h3ht4
+ hash: v1.k794b7964.d01f1bd613d0307bffce16134986a8762bf4aca66a9416cd2103372122fa8d5b.uG1YD37zS59eOv_7c4znA0CRnxIWGtY3iwKYpO7DNIA
scenes-app-settings-organization--settings-organization-details--dark:
- hash: v1.k794b7964.69657172bee616de03342472fcee605a8118ddac7d83396df2615c80251b7374.2ZFUCWs0Tck1tIgh7fAEnEubRA41QuvM8LNEE6Cd6Vs
+ hash: v1.k794b7964.9a04c21dceebc9696571c0fc34cf0c2516bbf3f1a074761d43dcffda890be79b.lO9rwp3DjSyySvMiDW4hNWrHZypLgy2VB9pDFKG752Y
scenes-app-settings-organization--settings-organization-details--light:
- hash: v1.k794b7964.b70acc85617155084e80f0a0531246b0f25e733f0da6becf0b9a8271b9b31504.37_E354oj-BWquICYG5XIsORUb04cpuYoqiLpImc7hI
+ hash: v1.k794b7964.de85b7c1f7324f502584fd14eb6ede11f37ca6ecacbf49e66265029590ad9aaa.V1MDGgnsvNpAjuAyk5835ffGmYXHYYvIoTsXMATmyEU
scenes-app-settings-organization--settings-organization-members--dark:
- hash: v1.k794b7964.148013b5e0a79d8506cdd38ed7738616075aa5afd6f9070fa83e78444bafb970.o2ISJUVIrsKaC6wEN4Qs7perYXsyNgC0U0z92ZZlVDM
+ hash: v1.k794b7964.a561a8ad91b85b874a9ba474185111abca567348623411a36dfd2709d3596f42.oo5KW6o6enyb02ODSJy-wi_X7SlTGWhaiumDV5BxsC0
scenes-app-settings-organization--settings-organization-members--light:
- hash: v1.k794b7964.fc72f736b2e2b2b6f1c0d2b97b940aae55781c76cc08311cc331e9926fbb465d.bpQHyHS05N8skB65nl9afZQobSFSbyvvc5YeyjfXbtA
+ hash: v1.k794b7964.d6832d35ed79184a1d8a599c057edf2a97bbad7acb426e512303b5cbf4365988.i2O99WNtXNkbyTbq8x4bVBlkf2TTObxcTAIFebeEBGo
scenes-app-settings-organization--settings-organization-proxy--dark:
- hash: v1.k794b7964.049e074f2f6ceba6d187340fa44f38eb9e67b5b43686f7f49b9085f8bff3804c.NDdP7uys0rQE_tzcFVmr2vbZTgehdykMt7Z9SuJOGes
+ hash: v1.k794b7964.f84a41dbb936b06564d7b13247ea82871ba101d41a71d9a6ed4b274cd0279920.X8eeuAzAWRgDuFHx_JEyu1g_dx3Ndb9YlDa202P4tdo
scenes-app-settings-organization--settings-organization-proxy--light:
- hash: v1.k794b7964.11b8a936bbaf0181e6a8d5d1cd6aba2c77274f65874896fce004ff7796526aa8.HkYLMi54K8Iu5RHMQoMp-bvU8AHq7xhi0Q5W9VVaErs
+ hash: v1.k794b7964.32396594b8d5ee8c9449f00e113cab24f6b926397aaa088f95c1d2e53bc250e6.ovEIENEGsvsCuWlUcNiR_PgdXKh3S2P9H9ORrJGAuLo
scenes-app-settings-organization--settings-organization-roles--dark:
- hash: v1.k794b7964.afb3f2f3c50071a2619443aea8a356fa256580eafee49f7c0162392d0bec4409.ssq3Sr1zH8hPFuVhTPA7fArpsCEmlyxvOX_cttBcRzg
+ hash: v1.k794b7964.3cb5017afbdab3243df1ee42ad4d6ec66fc653830855e99025a012affaae2150.mF6FWMMg3noMlTEKAMRVpkzwsnX6yNeTZmSMIBiD240
scenes-app-settings-organization--settings-organization-roles--light:
- hash: v1.k794b7964.85771b45ce9aae44390b2639b5e9c4c0054c8c941863ddfd3214c7bc5458a05c.60Wo3QT89ayqlAFUPigg3oDQwBDSDPeWpz4eCKAVwk0
+ hash: v1.k794b7964.41a38d2a61521107d414a90db09553b36c3e3be08b4bf030e838c65432fbcba9.BJ1BiTEPuPg3gJhPdLmqFHI6q5jpLFVOiR-h0HDNJoQ
scenes-app-settings-organization--settings-organization-startup-program--dark:
- hash: v1.k794b7964.7350d5c1608a11048e1dff1177936f88054a8b2f59f9364c7c0b4e1b532902e8.XL6fWFjzvdgrLqq__qTijTy70fAAQb47k0MhN5vST6U
+ hash: v1.k794b7964.78b7152f2861c979df8fb83531a1642cb86161f3efddb9510cf0fc3128c8bfc4.ncgHu5O8P9EXZ_2jQUXUIzpYCyLe1_Ql1y-lxCIAnm0
scenes-app-settings-organization--settings-organization-startup-program--light:
- hash: v1.k794b7964.7d547c57552c1d279a0787f9a45f964f745e00aaf8d24f40d558af6023ca6547.2pq0EfQs-iWVHK7_LfHkmQjXOo6wt9L8qWdc5nwU8Eg
+ hash: v1.k794b7964.7222ef55a316f23dc0d9f96e1ed84e975d9bdc80007a23a9aa6ac0987237d711.1XfGr_Qoo7WP_hs-YBHOstabGSH_lAoAt3jfEEZMnw0
scenes-app-settings-project--settings-project-access-control--dark:
- hash: v1.k794b7964.0d4b21ea939d87af256459c8617d2bd61a8f16975b00e3f6ee9de61fb2bdb3ea.DyAdtBg-avD0tcklEKCyBC4txMEjtAndsQG0BxlQ3to
+ hash: v1.k794b7964.20316d2923c33cc6254535a36f8ad31f05c07b38b07928087541246ec8b1e2c3.tlaW5XXuNU2hcBH35Gn3TxpZQjbbhAKD4_jdKPI1HyU
scenes-app-settings-project--settings-project-access-control--light:
- hash: v1.k794b7964.2d927bdf43b96297fc73c7407f2f1ba1bcec796e398af766d774541b94bfcb27.hsuUgEwrIyKJjXLZndhUP-RlAcdJBpmtzRhI17T2koo
+ hash: v1.k794b7964.fa2c7f6d463ece38c0243c44acae759bcdbd3854903564402179da9c0faab924.Sd8KENQ88hATd2MxGetpJVDZST1w0eQQyrNE_GvhnVc
scenes-app-settings-project--settings-project-autocapture--dark:
- hash: v1.k794b7964.2183cf0082a1556d6df553572df4ab3813c96288a8b9a80e669c005908230c3e.9fS6u7tUTV5SdXcHSH55nTlDMRiIS9KX8HVoHv76R7g
+ hash: v1.k794b7964.8defefc8ee81d152212ad970ee03afd0170e149183c700875620b83c94041edb.5f5prfRZbGCHJZ5SXwCfvu5BsuOjCWSch49ouOMP4iU
scenes-app-settings-project--settings-project-autocapture--light:
- hash: v1.k794b7964.9ef469fe5d9773481881830b71fe22637d5e90ebb4575b6c73be94c798e5deb5.PvLh4snB_tYC6sxv7Hc6aphqd_RfRx656bzYp5AUjmM
+ hash: v1.k794b7964.397d4848babe9a8d2fd98b15ffe998d685521cb5135ff4ad1a70951e6062ec71.HMYh2-IfWjQd_PDBPGoPGrX_LVi2OHg7wzBFzJAmslA
scenes-app-settings-project--settings-project-danger-zone--dark:
- hash: v1.k794b7964.af1058fc8ad92640a30987d7ca08ac23675af7de0e04e1a11212934434ffe8d0.AH8znHD6nOVeQaA-biiKFtdlrzEDyHjJ9zXiW0-inyg
+ hash: v1.k794b7964.d18bc16d7f8d14a2168e67a889a5229659191e35393f829ce1b5eb6c0876a269.nQC3Mf7fvxzoZTD0m9ndbrfXV9nQin3tsW49wkX6Zqk
scenes-app-settings-project--settings-project-danger-zone--light:
- hash: v1.k794b7964.ccb4076af018bd942766ece896ed42545b08665a695728b5146c495e32a70e09.gaWS_dz8lVJzeaQNwDZmJRfJTEZ8ofu2BTn_nI8--Gs
+ hash: v1.k794b7964.e9dd56463ef139c825e0ecd5c14ed5ec67f1d5afb9d2387e9019a8cb7c2cf16b.t1vg2Vgm16aslvFWPUJ5p6aqRj3GbUZ4XS8OgEMk0nM
scenes-app-settings-project--settings-project-details--dark:
- hash: v1.k794b7964.017ab15c5a5c4f47330f54f21812c6555d9fd15be6bd65d713d946de0ef13583.MHpPYLm7AICx5m5OTHpaHNDon7CRcNkJQt3FlRBLrdk
+ hash: v1.k794b7964.cf1fc23aa5d5f8063b067b068eed72dc6f6fa6638840c1223d9b63a2eaa8f6bf.3L_zGX_JbstMqwhvsYQyZPsCJc2lU8O-lxm-DMklP9w
scenes-app-settings-project--settings-project-details--light:
- hash: v1.k794b7964.92d131dadd962625b5dfdd78a2cb9c42017b230b1c39f9ae1b293e8f6e9fe788.ufkrkTmgF764iFDi-uaHriqBvleJci3OVpjBAwJxiUw
+ hash: v1.k794b7964.18db4f056202d3a55f1c53692497d96bd7b709ff582707dcacae7080b487c1f1.liWFj-mqCpcucn8gpFi_PEQ0CGKRQFuQNznAK8HVpPQ
scenes-app-settings-project--settings-project-integrations--dark:
- hash: v1.k794b7964.eab246ccd1136c9853b8c784aee1ed549e3410869c14caf0ecdc44d4aadb7afa.WtnZtBw3LuOsLLSWPJuRdXKbPKfnwKTZ9ntBKIXDJ5M
+ hash: v1.k794b7964.1aa226e2340f780cab3be2c4c58df4aa306c192093f889275b54db44761ed25e.4fAT0IldZHoHUB5OJKtr1MU7DN0n0t-8eEPKH-Mrzm8
scenes-app-settings-project--settings-project-integrations--light:
- hash: v1.k794b7964.676337e86614067960e5921914c746aa754fca36c8661e45f4413e9bab9f45eb.AVzu-ilxexc1vSvtOeilduBEcoxNiQxxY8-H9A83EJk
+ hash: v1.k794b7964.78000b9fb5415dc591e2d554b15eda54e4cf236fea779b643c8d00bfabe01024.pPGoBVvfxP-T4iYNRwqo_DfXZWCiOhtD1bUcStUoDHY
scenes-app-settings-project--settings-project-product-analytics--dark:
- hash: v1.k794b7964.925784616ac6ad5cb556351ede1916440226c9089930265fc96df7e14863046c.6iXpmU_M40nsD_JokXYH4Ey-T5YaQsEB1jGl35jRBgo
+ hash: v1.k794b7964.5a07f89b3cfdd21f4db69f6efd92794257b59cc2d743dc5bd3e801fc249c1fc6.teJLydFRlsuGeFHnCiQBE2Fxcc6YKf8mCBLTv6bXMKM
scenes-app-settings-project--settings-project-product-analytics--light:
- hash: v1.k794b7964.527360edf55b268b83ba976288336721af6da9af6088605669a4395b5a9b7a20.qnXEVYP868iG2Q0bj-z9_tORjlspkGdyJEMj5GDuG-8
+ hash: v1.k794b7964.1da2f92fbdce59ceaf6e66e709fa0fa4e0cdc79bee775d53421609178a071f90.VEYFFNL2Mr8ynrhgcBojw8VLR168k9SyRh0L6Pz8M6g
scenes-app-settings-project--settings-project-replay--dark:
hash: v1.k794b7964.42643eba5e571cd19b8da6a56ab4dcf0c38b78a143e66bbe8b281bfab9701687.nqBxikOTaNS7A47m4-kBKi9aJSEd9SlbWrbcQKszW5I
scenes-app-settings-project--settings-project-replay--light:
hash: v1.k794b7964.e0e88948b99c8a38e602dfe6ff8c26f68c346742b703d9b85e8a7ee319501e42.T9RgA2E-vBxzIliieWNns9bWN5kfnmtyalIcc8DpQy8
scenes-app-settings-project--settings-project-surveys--dark:
- hash: v1.k794b7964.116b8618e7355d13ff8ddc83c5095b98edd1bca44d8326d7a05c2922e967b0d8.mYqdrV9UEmN1USMnHw5MMm3DWaOk8_s_BNmFP-aRMFU
+ hash: v1.k794b7964.c80c81f50f54f13dbf5ede6e49f950335820671b7da01af8fc6ac7d413859055.DBq3H6WTaNnCvebpnOdgB6jNZGpTuvxjaeJVwuDtfx4
scenes-app-settings-project--settings-project-surveys--light:
- hash: v1.k794b7964.05d0573cf0252d1549ddfdde190a1e64f027739f6a7a2ac7c6edd7a24a26ffed.LwAXwEamreGuDqHSbURcZulpp9tsSNdO4sbRdZsWJks
+ hash: v1.k794b7964.97243580bea1faf882a55366a4f58714fb949f424fa876ceddcd46e7073a4c1c.9oWG98TLM7F9ZTRN9WYBYNP8C8ND8Kc8PXh3Zn5PUKE
scenes-app-settings-user--settings-user-api-keys--dark:
- hash: v1.k794b7964.6c46852b405cb760dab14988a6eb02e5e92fc74a235cefbb30ff5ddb631dd8b8.o4qpPFNUTlyxEJoVa6fehPE0O-djha-vzB8IfuPNQe4
+ hash: v1.k794b7964.33cd95c60200c07d0f73f4e88b432f54115ba9428ab9749a1239deb83a505142.STCKAEoPv_Fpp0yN3dx6iUsZL_oIL422sWMaL4qKUcQ
scenes-app-settings-user--settings-user-api-keys--light:
- hash: v1.k794b7964.694d513a5ff1f388bac6e9a019f23477d9060e1b7e69fba0135de4cd58e8f9c1.6wkrK7WjZauWxu-ClgABmK9238u5hum58lC-MyK8gkc
+ hash: v1.k794b7964.b89facafc7d9c6ba971eb3e495e51c6d41a1831fcf5e0af7ea26ff537991b8ce.YrhVuKeYKMWUYseZOSw0GSsA2ikI34wjkRho26HSDWc
scenes-app-settings-user--settings-user-customization--dark:
- hash: v1.k794b7964.9c96f0c7fd4a98227d6ba8d3c6cacea48ebc834193dbbdd18f71f3eb1581ebc7.tM4oASIUWbj1claWP-77_zKowWy8ya_wOFntM5KDkVo
+ hash: v1.k794b7964.38e71db924ca619b51ff10673243172f94a43c77ed2df3633b85c7ed567e1c99.UnGKZC7wW8jBAMlDp9UypEvtNbLfikrDPGb2PSjHw-g
scenes-app-settings-user--settings-user-customization--light:
- hash: v1.k794b7964.1c00f1a229bd98e7d1c3611b1c1de34d2c251b2c523d75d0b3007d1ed00c80f2.wL8rm5IcCIV9SDvShp8ok8ztZlUTmWvJ9-KXzgPzUMQ
+ hash: v1.k794b7964.3d60e7761964da031f1edbe4728ba0791248091a34abbf37eae0abb9be39620c.AbMHgulyJJdQUiUQl9_EulRVpkzpPLT4XIaCoZdNqbM
scenes-app-settings-user--settings-user-danger-zone--dark:
- hash: v1.k794b7964.dc6b6575cab56e03e45623a66310f420afe58dea530cff4b14e4f498ec74372b.LaVjuAO7tExYpsnsG9uV2MsCUVihAsA_rroSnQ1Jf44
+ hash: v1.k794b7964.c3b90ff095de1b4bcaf6d178622999620ce9a6d3693c5a6ae5ed6bc6d94e98df.ujOTBQwucF2-xUciRXLiC75Ws5FggdndAuBtDPSj-CI
scenes-app-settings-user--settings-user-danger-zone--light:
- hash: v1.k794b7964.96846d7823357e89a9d91350f6f435373fe287f713250b59ccce2dbd31b6f69c.kl21kygOhH1SlNOJ6VekMMlGUuyNg5Ka7NXFoHcG6M0
+ hash: v1.k794b7964.79eed09f0cfe8e6549abccd8227287b15a0646d4825cbed200a4eba872f39154.4oekofwaE2cUfD8BER8Cy-_z3BLisKp5Wk735NkF6kI
scenes-app-settings-user--settings-user-navigation--dark:
hash: v1.k794b7964.87ca468f0949495f6fb53cc8b07900f724e8cecdcd38c3791d49c6683a83f379.nPpp4yuzr2RtTIvFvDjlxk835WS_N7K8qVWNNxPCxgQ
scenes-app-settings-user--settings-user-navigation--light:
hash: v1.k794b7964.90007325cf24bd688266d36edca8206e11eb24d6aa98fc0208533ba74adb668b.Vjg6puokORg18-P-bIOttdR-X6L8hXOxoOklyUTlkiY
scenes-app-settings-user--settings-user-notifications--dark:
- hash: v1.k794b7964.a09a57f1c0bbcebf82942edebeba7772b2f684ba235bcef3a816aec2beb4cbce.AtQZhdZeeMVvpcmyBhPvprSMZawliTZaIFE5G8M_MVg
+ hash: v1.k794b7964.c8335086f8abd883b6dd1741a29670701c64dcc461080e1340e9b77d2fece219.WOZKv6IhgYXYbZEYmUDVx-mkYXMNYo2dZpv0s4ERQQ0
scenes-app-settings-user--settings-user-notifications--light:
- hash: v1.k794b7964.22b7ef8dce439a47cc7ca3da644d7f647f2615a7b16c3a55a0837dcea0f3cc2a.QnD-njyuDUa0lrABBsIuNCY8TExZql8lQCQBW7Vw6q4
+ hash: v1.k794b7964.90273cebc583a00056bfa1731001443305275d1ca018fcf3a17654c0e64178a5.9Sv2AD67xtzoF0R4xODU6b--urwaZZ-DeELmtk_pei8
scenes-app-settings-user--settings-user-profile--dark:
- hash: v1.k794b7964.477a820fd8ddcbd96fb4789d7407a6e21d1b37d889323e8bdcfcb7b4c1b2215c.OiIp-MDSCgN7eFiofAkbaB_vFBF9lVAd-E6rXlfI40A
+ hash: v1.k794b7964.be9766f7fb3b4767d3dca23a38adb9b03f781d3c7bcafed8c14b66279b1c319b.JJrVYzunXlrqVcxX2KUwSpzjwKp1gekUbzBDaAFum-c
scenes-app-settings-user--settings-user-profile--light:
- hash: v1.k794b7964.c5b1e953a68dcc2a7440de9061298b07a705a4f786b1948f385ff364fecd76bb.tpJwhfDqbEMdWhFcueay9wUV0sTGjxBSyQ63IWZgSqs
+ hash: v1.k794b7964.b511b0741535a94c3ae2b8d92a49616575ae094856964f62694b08266568dc17.KEUQBnu0veHFP6wYgeaFKBrxyxXnji7QiClDK_eqvow
scenes-app-settings-user--settings-user-profile-hedgehog-avatar--dark:
- hash: v1.k794b7964.c4331c34e1eca9ef27b39bf54eb2f63d1938d5860c58761289ef6f22553298b7.-fUQly4FV_2sclXXFOsbFrLvj52Hy1jGHUPvsBuyAdE
+ hash: v1.k794b7964.ed10faf9a444537be980a72ea990c42d94c0555a5f79c60849ded07872b31143.TG2uoQWjoFKXOZoVats3PxrABgKEq81BGsEyj9r89Ko
scenes-app-settings-user--settings-user-profile-hedgehog-avatar--light:
- hash: v1.k794b7964.21df030ff0d23324c716f8da3ba1bcb157eda37de4456006591d24c4be43799a.VY-j0yn8MJtQDqWoRtkbNdH2rc1dZ6zRp3n8yfUJf3c
+ hash: v1.k794b7964.b321293603b35ac02d1e1776b884133b618607f0c6cce74a8ac9dd1c857f716f.0QAkSVwqVTUCx9A8Gb_Fnd1cI8is19xHR0vCI9m7jSM
scenes-app-settings-user--settings-user-reminders-modal--dark:
- hash: v1.k794b7964.242ae233bc621d826310883788ad4e89b47d5d9d9c2c09279c675165f94384ce.nApdQbX5odqe7aMVihM5X4WlwlneicqcFebSJ_N1hVE
+ hash: v1.k794b7964.5f1527469dc059025dfe4ad1c65195efd587ca4df4b9a70f1a99cabb13dc250f.YHM_sJIzdyWLi5BKco7ccM3GQxW84xO6VRanaNE4kGc
scenes-app-settings-user--settings-user-reminders-modal--light:
- hash: v1.k794b7964.fbcf3f0f69a5b43c28ea7537ce6f1aab3c21e70f9c2cbb6fdfef4546dadba86c.yYIPurSofuNP1kZXYzNBOa3YU5Zy7VLaSegvGrNZ8Mw
+ hash: v1.k794b7964.379aad89d136825966d35e82eaf315333111a16548f360f092a524b41ac7255a.m8WVS2AfjkIM5oORAV5j0qqAEoUKRyrD6OLCMqrC5fE
scenes-app-sidepanels--side-panel-access-control--dark:
hash: v1.k794b7964.554435d39f0216bb1d1d2bd30bb5349b832871a832d7e751dbe3817cfad7f725.Am91eP-EhuYx4YS1IBHDk1fnSvVGke9GchLJs2t6pQQ
scenes-app-sidepanels--side-panel-access-control--light:
@@ -8677,9 +8677,9 @@ snapshots:
scenes-app-tasks--mobile-list--light:
hash: v1.k794b7964.9fd49300ca0d02ce3fe8cf6ea7eb850af2f42332d19a821ac73a6108f33fd651.aHbvQ9EqCKA43njPMkK_xgXEq4rToiJ0U8zAsxjwEWA
scenes-app-tasks--mobile-new-task--dark:
- hash: v1.k794b7964.5ec7cbf0273544a983f9eb54695debfeb9328356f25c9ecf497a67b76ffb519b.J0OsmJ_b0Egf48R-VZhYjS-sAEdRzD29UL-Fc4HHmdU
+ hash: v1.k794b7964.769ea87b534e9349dce86bd8288578fdc367515923f19715c8547d77afbb401b.sppYSyaZvxn8yw2wisc1oDBq5cQpXG2xZktdkQc2OBU
scenes-app-tasks--mobile-new-task--light:
- hash: v1.k794b7964.5e5e1f065eddc09b14bc089a6c99118150a347c0d7ae50c05a88dd1ec3b3fffc.3ytBwe_ptE121gVzRRFFLyy5g0mnyxw2Re6Qv9vjZ9M
+ hash: v1.k794b7964.ff1d06e8ac15222e5e15ef40f8498e1f1bbf1cfdd40cb09c6955ee302bc74927.K0Knbgd_yAx-hUhip40iw-gEWVhY7vkTMQUoGeycXIE
scenes-app-tasks--mobile-task-selected--dark:
hash: v1.k794b7964.db0156b3fd83b5c3494116788236075e0bc2c5ace019e4c1d9947d2b21fa70fb.4HfTdy-PBBkgEn0HFlUkrJm0D6GCiujf_ljrGGrLrsc
scenes-app-tasks--mobile-task-selected--light:
@@ -9309,17 +9309,17 @@ snapshots:
scenes-other-onboarding-shared-wizard-sync-card--stalled--light:
hash: v1.k794b7964.b52a107e85cd22687e6bc1dcf23a4067f185915e7aaa4518b39ef1bbfefe87ac.TU0cv3huC_bueumE3zh9JXnBoRGtM6FKvdbtqCcUL4c
scenes-other-org-member-invites--current-user-is-admin--dark:
- hash: v1.k794b7964.13d61a1f851d8a47af27a8cfc8fee58c2a8dc2c386e0b41cc5fc77334600602b.qV4Isf32N337QmR-OVFNnp_iYmVgfjZf1JIOKApTZkI
+ hash: v1.k794b7964.035587a8b5e312e7090802ce64658770e8203ed95a272199a59fb854d07b8e4c.XbOOmt8eKoxqNnPNpcMU_rABcnBTy9ICdNUsySQlSjs
scenes-other-org-member-invites--current-user-is-admin--light:
- hash: v1.k794b7964.13a17f5426828aa5f372d3e730ca4bf1ece9f304eaa146d6abf7ff27e365f094.x899Oy5UyUQyBX_f1LVuoOZX5F_6TrAhvFGYaWxqkwI
+ hash: v1.k794b7964.f4fe409e93f3be73dbbd723a795233dafc57b47fa9a10e1586bb123bd4975dfd.v2X3e-FoFHDGOxCv2SoHwWmDQXl98vl0XMukl692R2M
scenes-other-org-member-invites--current-user-is-member--dark:
- hash: v1.k794b7964.31c03d908d49053a3af2d9daa512ded19c5269199396930477a176a2c4198378.pM51psTftdv46yX-GwGCqSQfz1VrqY-9Gs90hw7f7bI
+ hash: v1.k794b7964.b083f20a5ed20f1c3ed80d9f018c7808f972b74314a32d650921a298620cd1f5.WkFiqKCT5WXbqg3tJ_R4VBYRIb9ebHiLtWgRApYpnHs
scenes-other-org-member-invites--current-user-is-member--light:
- hash: v1.k794b7964.23553f9818ce4d023546149d9c008a5fff2b33c740b0e48079e94807decf0ff5.hFLcnpyCafv5CgVLn9694Kq2g2_w93EcKZ_Zdix7vbM
+ hash: v1.k794b7964.8f20d80b6cf99a8ae6f1c36c78930e120e612d53f13b9335653ed66cf812fd2c.10MnNNz01Z5VKUGakMSMqxmesm4R7tDa09ZEUNC8iKM
scenes-other-org-member-invites--current-user-is-owner--dark:
- hash: v1.k794b7964.13d61a1f851d8a47af27a8cfc8fee58c2a8dc2c386e0b41cc5fc77334600602b.Aj6GmJwM4D_Dni5CfWfH0OwPKkpCoT1D2smbBAyudl8
+ hash: v1.k794b7964.035587a8b5e312e7090802ce64658770e8203ed95a272199a59fb854d07b8e4c.xPEsURT17vLAz5gEM4ChIgLSXTy8WIipv5pZUUhoSwA
scenes-other-org-member-invites--current-user-is-owner--light:
- hash: v1.k794b7964.13a17f5426828aa5f372d3e730ca4bf1ece9f304eaa146d6abf7ff27e365f094.Anlc-OVFnrsOeEyxe6aQoVLkD6eJtKO72-KNeRz2bko
+ hash: v1.k794b7964.f4fe409e93f3be73dbbd723a795233dafc57b47fa9a10e1586bb123bd4975dfd.oCEutKjA-YPKNncWVj3xSWMHnOgv6_xXWT7ZJr2wVqw
scenes-other-password-reset--initial--dark:
hash: v1.k794b7964.e3d5f708ff09306e1f06f485f1e389207698e60a0388f606900b947ca5a70ec9.3XJguWf4w1HF8NIOqLCRARBInuoUXmbo9esa81izrrM
scenes-other-password-reset--initial--light:
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 68e1af7e1982..2b9e1364ba80 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -36,6 +36,10 @@ import { PreAggregatedTablesSetting } from 'scenes/settings/environment/PreAggre
import { ReplayTriggers } from 'scenes/settings/environment/ReplayTriggers'
import { SessionsTableVersion } from 'scenes/settings/environment/SessionsTableVersion'
import { SessionsV2JoinModeSettings } from 'scenes/settings/environment/SessionsV2JoinModeSettings'
+import {
+ TaskAgentMyPreferenceSettings,
+ TaskAgentProjectDefaultSettings,
+} from 'scenes/settings/environment/TaskAgentDefaultsSettings'
import { OrganizationMCPAccess } from 'scenes/settings/organization/OrganizationMCPAccess'
import { urls } from 'scenes/urls'
@@ -350,6 +354,30 @@ export const SETTINGS_MAP: SettingSection[] = [
},
],
},
+ {
+ level: 'environment',
+ id: 'environment-task-agents',
+ title: 'Task agents',
+ group: 'AI',
+ settings: [
+ {
+ id: 'task-agent-project-default',
+ title: 'Project default model',
+ description:
+ 'The model agent runs launch with when nobody picks one. Everyone on this project inherits it, for runs started from the task composer, Slack, and PostHog Desktop.',
+ component: <TaskAgentProjectDefaultSettings />,
+ keywords: ['ai', 'model', 'claude', 'codex', 'agent', 'tasks', 'default'],
+ },
+ {
+ id: 'task-agent-my-preference',
+ title: 'My default model',
+ description:
+ 'The model your own runs launch with, overriding the project default. Applies everywhere in PostHog: the task composer, Slack, and PostHog Desktop.',
+ component: <TaskAgentMyPreferenceSettings />,
+ keywords: ['ai', 'model', 'claude', 'codex', 'agent', 'tasks', 'preference'],
+ },
+ ],
+ },
{
level: 'environment',
id: 'posthog-mcp',
diff --git a/frontend/src/scenes/settings/environment/TaskAgentDefaultsSettings.tsx b/frontend/src/scenes/settings/environment/TaskAgentDefaultsSettings.tsx
new file mode 100644
index 000000000000..cc58f962b99b
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/TaskAgentDefaultsSettings.tsx
@@ -0,0 +1,187 @@
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { LemonButton, LemonSelect } from '@posthog/lemon-ui'
+
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TeamMembershipLevel } from 'lib/constants'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'
+import {
+ filterEffortForModel,
+ getEffortLabel,
+ getEffortsForModel,
+ getModelLabel,
+ getRuntimeAdapterLabel,
+ listRuntimeAdapters,
+ modelsForRuntimeAdapter,
+} from 'products/posthog_ai/frontend/utils/composerModels'
+
+import { type AIRunPreferenceDraft, taskAgentDefaultsLogic } from './taskAgentDefaultsLogic'
+
+function PreferenceEditor({
+ draft,
+ dirty,
+ saving,
+ inheritLabel,
+ onChange,
+ onSave,
+ onReset,
+ canReset,
+ restrictionReason,
+}: {
+ draft: AIRunPreferenceDraft
+ dirty: boolean
+ saving: boolean
+ inheritLabel: string
+ onChange: (draft: Partial<AIRunPreferenceDraft>) => void
+ onSave: () => void
+ onReset?: () => void
+ canReset?: boolean
+ /** Set when the viewer may not edit this level, which disables every control here. */
+ restrictionReason?: string | null
+}): JSX.Element {
+ const { catalogue } = useValues(modelCatalogueLogic)
+
+ // Grouped by harness off the same catalogue the composer renders, so a model you can pick for a
+ // run is always settable as a default and vice versa — including the Codex models that only
+ // Slack and PostHog Desktop drive today.
+ const modelOptions = useMemo(
+ () =>
+ listRuntimeAdapters(catalogue).map((adapter) => ({
+ title: getRuntimeAdapterLabel(adapter),
+ options: modelsForRuntimeAdapter(catalogue, adapter).map((choice) => ({
+ value: choice.model,
+ label: choice.display_name,
+ })),
+ })),
+ [catalogue]
+ )
+ const effortOptions = useMemo(() => getEffortsForModel(catalogue, draft.model), [catalogue, draft.model])
+
+ return (
+ <div className="flex flex-wrap items-end gap-2">
+ <LemonField.Pure label="Model" className="min-w-60">
+ <LemonSelect
+ fullWidth
+ value={draft.model}
+ onChange={(model) =>
+ onChange({
+ model,
+ // A model switch may invalidate the picked effort; drop it rather than store one
+ // the model can't run, and let the server-side default apply instead.
+ reasoning_effort:
+ draft.reasoning_effort && model
+ ? filterEffortForModel(catalogue, draft.reasoning_effort, model)
+ : null,
+ })
+ }
+ options={[{ options: [{ value: null as string | null, label: inheritLabel }] }, ...modelOptions]}
+ placeholder={inheritLabel}
+ disabledReason={restrictionReason ?? (saving ? 'Saving…' : undefined)}
+ data-attr="task-agent-default-model"
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Reasoning effort" className="min-w-48">
+ <LemonSelect
+ fullWidth
+ value={draft.reasoning_effort}
+ onChange={(reasoning_effort) => onChange({ reasoning_effort })}
+ options={[
+ { value: null as string | null, label: 'Default effort' },
+ ...effortOptions.map(({ value, label }) => ({ value: value as string, label })),
+ ]}
+ disabledReason={
+ restrictionReason ?? (saving ? 'Saving…' : draft.model ? undefined : 'Pick a model first')
+ }
+ data-attr="task-agent-default-effort"
+ />
+ </LemonField.Pure>
+ <LemonButton
+ type="primary"
+ onClick={onSave}
+ loading={saving}
+ disabledReason={restrictionReason ?? (dirty ? undefined : 'No changes to save')}
+ >
+ Save
+ </LemonButton>
+ {onReset && (
+ <LemonButton
+ type="secondary"
+ onClick={onReset}
+ loading={saving}
+ disabledReason={canReset ? undefined : 'Already using the project default'}
+ >
+ Reset to project default
+ </LemonButton>
+ )}
+ </div>
+ )
+}
+
+export function TaskAgentProjectDefaultSettings(): JSX.Element {
+ const { teamDraft, teamDraftDirty, teamPreferencesLoading } = useValues(taskAgentDefaultsLogic)
+ const { setTeamDraft, submitTeamDraft } = useActions(taskAgentDefaultsLogic)
+ // This one default applies to everyone on the project, so it's admin-only — unlike the personal
+ // preference below, which each person owns.
+ const restrictionReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: TeamMembershipLevel.Admin,
+ })
+
+ return (
+ <div className="flex flex-col gap-2">
+ <PreferenceEditor
+ draft={teamDraft}
+ dirty={teamDraftDirty}
+ saving={teamPreferencesLoading}
+ inheritLabel="No project default"
+ onChange={setTeamDraft}
+ onSave={submitTeamDraft}
+ restrictionReason={restrictionReason}
+ />
+ {restrictionReason ? (
+ <p className="text-secondary mb-0">
+ Only project admins can change this. You can still set your own default below.
+ </p>
+ ) : null}
+ </div>
+ )
+}
+
+export function TaskAgentMyPreferenceSettings(): JSX.Element {
+ const { myDraft, myDraftDirty, myPreferencesLoading, canResetMyPreference, resolvedDefaults } =
+ useValues(taskAgentDefaultsLogic)
+ const { catalogue } = useValues(modelCatalogueLogic)
+ const { setMyDraft, submitMyDraft, resetMyPreference } = useActions(taskAgentDefaultsLogic)
+
+ return (
+ <div className="flex flex-col gap-2">
+ <PreferenceEditor
+ draft={myDraft}
+ dirty={myDraftDirty}
+ saving={myPreferencesLoading}
+ inheritLabel="Use project default"
+ onChange={setMyDraft}
+ onSave={submitMyDraft}
+ onReset={resetMyPreference}
+ canReset={canResetMyPreference}
+ />
+ <p className="text-secondary mb-0">
+ {resolvedDefaults?.model ? (
+ <>
+ Runs you start without picking a model will use{' '}
+ <strong>{getModelLabel(catalogue, resolvedDefaults.model)}</strong>
+ {resolvedDefaults.reasoning_effort ? (
+ <> ({getEffortLabel(resolvedDefaults.reasoning_effort)} effort)</>
+ ) : null}{' '}
+ from {resolvedDefaults.source === 'user' ? 'your default above' : 'the project default'}.
+ </>
+ ) : (
+ <>No default is set — runs use each surface's built-in model.</>
+ )}
+ </p>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.test.ts b/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.test.ts
new file mode 100644
index 000000000000..4b1d440a384c
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.test.ts
@@ -0,0 +1,111 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { taskAgentDefaultsLogic } from './taskAgentDefaultsLogic'
+
+describe('taskAgentDefaultsLogic', () => {
+ let logic: ReturnType<typeof taskAgentDefaultsLogic.build>
+ let posted: any[]
+
+ function useConfigMocks(myPreferences: Record<string, any> | null): void {
+ posted = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/tasks/config/': () => [200, { ai_run_preferences: null }],
+ '/api/projects/:team_id/tasks/@me/config/': () => [
+ 200,
+ { ai_run_preferences: myPreferences, resolved_ai_run_defaults: null },
+ ],
+ '/api/projects/:team_id/tasks/models/': () => [200, { models: [] }],
+ },
+ post: {
+ '/api/projects/:team_id/tasks/@me/config/': async ({ request }) => {
+ posted.push(await request.json())
+ return [200, { ai_run_preferences: null, resolved_ai_run_defaults: null }]
+ },
+ '/api/projects/:team_id/tasks/config/': async ({ request }) => {
+ const body = await request.json()
+ return [200, { ai_run_preferences: body }]
+ },
+ },
+ })
+ }
+
+ function mount(): void {
+ logic = taskAgentDefaultsLogic()
+ logic.mount()
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ // Resetting is the only way back to inheriting once a personal default is stored, so it has to clear
+ // the stored preference server-side rather than just blank the pickers.
+ it('clears the stored preference and drops back to the project default', async () => {
+ useConfigMocks({ runtime_adapter: 'claude', model: 'claude-opus-5', reasoning_effort: 'high' })
+ mount()
+ await expectLogic(logic)
+ .toDispatchActions(['loadMyConfigSuccess'])
+ .toMatchValues({
+ canResetMyPreference: true,
+ myDraft: { model: 'claude-opus-5', reasoning_effort: 'high' },
+ })
+
+ logic.actions.resetMyPreference()
+
+ await expectLogic(logic)
+ .toDispatchActions(['saveMyPreferencesSuccess'])
+ .toMatchValues({
+ myDraft: { model: null, reasoning_effort: null },
+ canResetMyPreference: false,
+ myDraftDirty: false,
+ })
+ expect(posted).toEqual([{ runtime_adapter: null, model: null, reasoning_effort: null }])
+ })
+
+ // Nothing stored and nothing picked means there's nothing to fall back to — the button has to say so
+ // rather than post an empty preference over an already-empty one.
+ it('has nothing to reset while the project default is already what applies', async () => {
+ useConfigMocks(null)
+ mount()
+
+ await expectLogic(logic).toDispatchActions(['loadMyConfigSuccess']).toMatchValues({
+ canResetMyPreference: false,
+ myDraftDirty: false,
+ })
+
+ // An unsaved pick is resettable too: reset discards it as well as anything stored.
+ logic.actions.setMyDraft({ model: 'claude-opus-5' })
+ await expectLogic(logic).toMatchValues({ canResetMyPreference: true, myDraftDirty: true })
+ })
+
+ // Saving the project default refetches the personal config; that load result used to
+ // overwrite whatever the person was editing in the other card, and the Save button then
+ // read "No changes to save" over the silently discarded pick.
+ it('keeps an in-progress personal edit across the refetch a project save triggers', async () => {
+ useConfigMocks(null)
+ mount()
+ await expectLogic(logic).toDispatchActions(['loadMyConfigSuccess'])
+
+ logic.actions.setMyDraft({ model: 'claude-opus-5' })
+ logic.actions.setTeamDraft({ model: 'claude-fable-5' })
+ logic.actions.submitTeamDraft()
+
+ // Anchor on submitTeamDraft so the matched loadMyConfigSuccess is the refetch,
+ // not the mount-time load already in the action history.
+ await expectLogic(logic)
+ .toDispatchActions(['submitTeamDraft', 'saveTeamPreferencesSuccess', 'loadMyConfigSuccess'])
+ .toFinishAllListeners()
+ .toMatchValues({
+ myDraft: { model: 'claude-opus-5', reasoning_effort: null },
+ myDraftDirty: true,
+ })
+ })
+})
diff --git a/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.ts b/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.ts
new file mode 100644
index 000000000000..85af283e4f53
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/taskAgentDefaultsLogic.ts
@@ -0,0 +1,308 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { projectLogic } from 'scenes/projectLogic'
+
+import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'
+import { taskRunDefaultsLogic } from 'products/posthog_ai/frontend/logics/taskRunDefaultsLogic'
+import { getRuntimeAdapterForModel } from 'products/posthog_ai/frontend/utils/composerModels'
+import { tasksConfigCreate, tasksConfigList, tasksMeConfigCreate } from 'products/tasks/frontend/generated/api'
+import type {
+ ModelChoiceApi,
+ TasksAIRunPreferencesApi,
+ TasksResolvedAIRunDefaultsApi,
+ TasksUserConfigResponseApi,
+} from 'products/tasks/frontend/generated/api.schemas'
+
+/** A model/effort pick being edited in the settings UI; null model = inherit (no default stored). */
+export interface AIRunPreferenceDraft {
+ model: string | null
+ reasoning_effort: string | null
+}
+
+const EMPTY_DRAFT: AIRunPreferenceDraft = { model: null, reasoning_effort: null }
+
+interface DraftState {
+ draft: AIRunPreferenceDraft
+ touched: boolean
+}
+
+function isDraftChanged(draft: AIRunPreferenceDraft, stored: AIRunPreferenceDraft): boolean {
+ return draft.model !== stored.model || draft.reasoning_effort !== stored.reasoning_effort
+}
+
+function draftFromStored(stored: TasksAIRunPreferencesApi | null | undefined): AIRunPreferenceDraft {
+ return { model: stored?.model ?? null, reasoning_effort: stored?.reasoning_effort ?? null }
+}
+
+// The adapter is a property of the model, so it comes off the catalogue rather than the model id's
+// spelling — the settings picker offers Codex models too, and a new harness must not be mislabelled.
+function payloadFromDraft(draft: AIRunPreferenceDraft, catalogue: ModelChoiceApi[]): TasksAIRunPreferencesApi {
+ return {
+ runtime_adapter: draft.model ? getRuntimeAdapterForModel(catalogue, draft.model) : null,
+ model: draft.model,
+ reasoning_effort: draft.model ? (draft.reasoning_effort as TasksAIRunPreferencesApi['reasoning_effort']) : null,
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taskAgentDefaultsLogicValues {
+ catalogue: ModelChoiceApi[] // modelCatalogueLogic
+ currentProjectId: number | null // projectLogic
+ myConfig: TasksUserConfigResponseApi | null // taskRunDefaultsLogic
+ resolvedDefaults: TasksResolvedAIRunDefaultsApi | null // taskRunDefaultsLogic
+ canResetMyPreference: boolean
+ myDraft: AIRunPreferenceDraft
+ myDraftDirty: boolean
+ myDraftState: DraftState
+ myPreferenceStored: AIRunPreferenceDraft
+ myPreferences: TasksUserConfigResponseApi | null
+ myPreferencesLoading: boolean
+ teamDraft: AIRunPreferenceDraft
+ teamDraftDirty: boolean
+ teamDraftState: DraftState
+ teamPreferences: TasksAIRunPreferencesApi | null
+ teamPreferencesLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taskAgentDefaultsLogicActions {
+ loadMyConfig: () => any // taskRunDefaultsLogic
+ loadMyConfigSuccess: (
+ myConfig: TasksUserConfigResponseApi | null,
+ payload?: any
+ ) => {
+ myConfig: TasksUserConfigResponseApi | null
+ payload?: any
+ } // taskRunDefaultsLogic
+ loadTeamPreferences: () => any
+ loadTeamPreferencesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadTeamPreferencesSuccess: (
+ teamPreferences: TasksAIRunPreferencesApi | null,
+ payload?: any
+ ) => {
+ teamPreferences: TasksAIRunPreferencesApi | null
+ payload?: any
+ }
+ resetMyPreference: () => {
+ value: true
+ }
+ saveMyPreferences: (preferences: TasksAIRunPreferencesApi) => TasksAIRunPreferencesApi
+ saveMyPreferencesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ saveMyPreferencesSuccess: (
+ myPreferences: TasksUserConfigResponseApi | null,
+ payload?: TasksAIRunPreferencesApi
+ ) => {
+ myPreferences: TasksUserConfigResponseApi | null
+ payload?: TasksAIRunPreferencesApi
+ }
+ saveTeamPreferences: (preferences: TasksAIRunPreferencesApi) => TasksAIRunPreferencesApi
+ saveTeamPreferencesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ saveTeamPreferencesSuccess: (
+ teamPreferences: TasksAIRunPreferencesApi | null,
+ payload?: TasksAIRunPreferencesApi
+ ) => {
+ teamPreferences: TasksAIRunPreferencesApi | null
+ payload?: TasksAIRunPreferencesApi
+ }
+ setMyDraft: (draft: Partial<AIRunPreferenceDraft>) => {
+ draft: Partial<AIRunPreferenceDraft>
+ }
+ setTeamDraft: (draft: Partial<AIRunPreferenceDraft>) => {
+ draft: Partial<AIRunPreferenceDraft>
+ }
+ submitMyDraft: () => {
+ value: true
+ }
+ submitTeamDraft: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taskAgentDefaultsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ teamDraft: (teamDraftState: DraftState) => AIRunPreferenceDraft
+ myDraft: (myDraftState: DraftState) => AIRunPreferenceDraft
+ myPreferenceStored: (
+ myPreferences: TasksUserConfigResponseApi | null,
+ myConfig: TasksUserConfigResponseApi | null
+ ) => AIRunPreferenceDraft
+ teamDraftDirty: (teamDraft: AIRunPreferenceDraft, teamPreferences: TasksAIRunPreferencesApi | null) => boolean
+ myDraftDirty: (myDraft: AIRunPreferenceDraft, myPreferenceStored: AIRunPreferenceDraft) => boolean
+ canResetMyPreference: (myDraft: AIRunPreferenceDraft, myPreferenceStored: AIRunPreferenceDraft) => boolean
+ }
+}
+
+export type taskAgentDefaultsLogicType = MakeLogicType<
+ taskAgentDefaultsLogicValues,
+ taskAgentDefaultsLogicActions,
+ Record<string, any>,
+ taskAgentDefaultsLogicMeta
+>
+
+export const taskAgentDefaultsLogic = kea<taskAgentDefaultsLogicType>([
+ path(['scenes', 'settings', 'environment', 'taskAgentDefaultsLogic']),
+
+ connect(() => ({
+ // `taskRunDefaultsLogic` already owns reading `@me/config` for the composers, and its
+ // resolution is what this page is editing — sharing it keeps one cache and one fetch
+ // instead of two that drift.
+ values: [
+ projectLogic,
+ ['currentProjectId'],
+ taskRunDefaultsLogic,
+ ['myConfig', 'resolvedDefaults'],
+ modelCatalogueLogic,
+ ['catalogue'],
+ ],
+ actions: [taskRunDefaultsLogic, ['loadMyConfig', 'loadMyConfigSuccess']],
+ })),
+
+ actions({
+ setTeamDraft: (draft: Partial<AIRunPreferenceDraft>) => ({ draft }),
+ setMyDraft: (draft: Partial<AIRunPreferenceDraft>) => ({ draft }),
+ submitTeamDraft: true,
+ submitMyDraft: true,
+ resetMyPreference: true,
+ }),
+
+ // Each card's draft carries a `touched` flag in the same reducer, so a load result can be
+ // gated right where it lands: a refetch (the team save triggers one, and the shared
+ // `myConfig` loader can resolve mid-edit) must never overwrite a pick someone is in the
+ // middle of making. Saves untouch the draft — the stored value is the edit again.
+ reducers({
+ teamDraftState: [
+ { draft: EMPTY_DRAFT, touched: false } as DraftState,
+ {
+ setTeamDraft: (state, { draft }) => ({ draft: { ...state.draft, ...draft }, touched: true }),
+ loadTeamPreferencesSuccess: (state, { teamPreferences }) =>
+ state.touched ? state : { draft: draftFromStored(teamPreferences), touched: false },
+ saveTeamPreferencesSuccess: (_, { teamPreferences }) => ({
+ draft: draftFromStored(teamPreferences),
+ touched: false,
+ }),
+ },
+ ],
+ myDraftState: [
+ { draft: EMPTY_DRAFT, touched: false } as DraftState,
+ {
+ setMyDraft: (state, { draft }) => ({ draft: { ...state.draft, ...draft }, touched: true }),
+ loadMyConfigSuccess: (state, { myConfig }) =>
+ state.touched ? state : { draft: draftFromStored(myConfig?.ai_run_preferences), touched: false },
+ saveMyPreferencesSuccess: (_, { myPreferences }) => ({
+ draft: draftFromStored(myPreferences?.ai_run_preferences),
+ touched: false,
+ }),
+ },
+ ],
+ }),
+
+ loaders(({ values }) => ({
+ teamPreferences: {
+ __default: null as TasksAIRunPreferencesApi | null,
+ loadTeamPreferences: async (): Promise<TasksAIRunPreferencesApi | null> => {
+ if (values.currentProjectId == null) {
+ return null
+ }
+ return (await tasksConfigList(String(values.currentProjectId))).ai_run_preferences
+ },
+ saveTeamPreferences: async (
+ preferences: TasksAIRunPreferencesApi
+ ): Promise<TasksAIRunPreferencesApi | null> => {
+ const response = await tasksConfigCreate(String(values.currentProjectId), preferences)
+ lemonToast.success(preferences.model ? 'Project default saved' : 'Project default cleared')
+ return response.ai_run_preferences
+ },
+ },
+ myPreferences: {
+ __default: null as TasksUserConfigResponseApi | null,
+ saveMyPreferences: async (
+ preferences: TasksAIRunPreferencesApi
+ ): Promise<TasksUserConfigResponseApi | null> => {
+ const response = await tasksMeConfigCreate(String(values.currentProjectId), preferences)
+ lemonToast.success(preferences.model ? 'Your default saved' : 'Reset to the project default')
+ return response
+ },
+ },
+ })),
+
+ selectors({
+ teamDraft: [(s) => [s.teamDraftState], (state: DraftState): AIRunPreferenceDraft => state.draft],
+ myDraft: [(s) => [s.myDraftState], (state: DraftState): AIRunPreferenceDraft => state.draft],
+ // The save response is read first so the reset button settles in the same tick as the
+ // save; `myConfig` (refreshed alongside it) is what's there on mount and after a
+ // project-level write.
+ myPreferenceStored: [
+ (s) => [s.myPreferences, s.myConfig],
+ (saved: TasksUserConfigResponseApi | null, loaded: TasksUserConfigResponseApi | null) =>
+ draftFromStored((saved ?? loaded)?.ai_run_preferences),
+ ],
+ // Whether there's anything to send.
+ teamDraftDirty: [
+ (s) => [s.teamDraft, s.teamPreferences],
+ (draft: AIRunPreferenceDraft, stored: TasksAIRunPreferencesApi | null): boolean =>
+ isDraftChanged(draft, draftFromStored(stored)),
+ ],
+ myDraftDirty: [
+ (s) => [s.myDraft, s.myPreferenceStored],
+ (draft: AIRunPreferenceDraft, stored: AIRunPreferenceDraft): boolean => isDraftChanged(draft, stored),
+ ],
+ // Nothing to fall back to when neither the draft nor the stored preference pins a model — the
+ // effort alone is never stored without one.
+ canResetMyPreference: [
+ (s) => [s.myDraft, s.myPreferenceStored],
+ (draft: AIRunPreferenceDraft, stored: AIRunPreferenceDraft): boolean =>
+ Boolean(draft.model || stored.model),
+ ],
+ }),
+
+ listeners(({ actions, values }) => ({
+ submitTeamDraft: () => {
+ actions.saveTeamPreferences(payloadFromDraft(values.teamDraft, values.catalogue))
+ },
+ submitMyDraft: () => {
+ actions.saveMyPreferences(payloadFromDraft(values.myDraft, values.catalogue))
+ },
+ // Clearing the stored preference is what hands the choice back to the project default, so the
+ // reset discards any unsaved edit and saves the empty draft in one go.
+ resetMyPreference: () => {
+ actions.setMyDraft(EMPTY_DRAFT)
+ actions.saveMyPreferences(payloadFromDraft(EMPTY_DRAFT, values.catalogue))
+ },
+ // Both writes change what an unpinned run resolves to, so the shared read the composers
+ // render from has to move too. The team write can't say what the user-level answer
+ // becomes, so it refetches; the personal write already has it in its own response.
+ saveTeamPreferencesSuccess: () => {
+ actions.loadMyConfig()
+ },
+ saveMyPreferencesSuccess: ({ myPreferences }) => {
+ if (myPreferences) {
+ actions.loadMyConfigSuccess(myPreferences)
+ }
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadTeamPreferences()
+ }),
+])
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 9f4056ac3954..4352a62cd786 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -45,6 +45,7 @@ export type SettingSectionId =
| 'environment-revenue-analytics'
| 'environment-secret-api-keys'
| 'environment-surveys'
+ | 'environment-task-agents'
| 'environment-web-analytics'
| 'environment-workflows'
| 'environment-danger-zone'
@@ -268,6 +269,8 @@ export type SettingId =
| 'snippet-v2'
| 'surveys-default-appearance'
| 'surveys-interface'
+ | 'task-agent-my-preference'
+ | 'task-agent-project-default'
| 'theme'
| 'user-delete'
| 'user-groups'
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.py
index dcaff423af75..54e345968a44 100644
--- a/posthog/temporal/ai/slack_app/activities/task_creation.py
+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py
@@ -640,7 +640,9 @@ def create_posthog_code_task_for_repo_activity(
from products.slack_app.backend.facade.run_preferences import resolve_run_preferences
- run_prefs = resolve_run_preferences(integration, slack_user_id, override=model_override)
+ run_prefs = resolve_run_preferences(
+ integration, slack_user_id, override=model_override, team_id=integration.team_id, user_id=user_id
+ )
# File into the creator's personal "#me" channel so the task surfaces in PostHog Desktop's
# Spaces feed, which is strictly channel-scoped — a NULL-channel task shows up in no space.
@@ -1135,6 +1137,9 @@ def _run_preference_state(
integration: Any,
slack_user_id: str,
model_override: SlackAppModelOverride | None,
+ *,
+ team_id: int | None = None,
+ user_id: int | None = None,
) -> dict[str, Any]:
"""The run-state keys that pin a new run's harness, model and effort.
@@ -1145,7 +1150,9 @@ def _run_preference_state(
from products.slack_app.backend.facade.run_preferences import resolve_run_preferences
from products.tasks.backend.facade.run_config import get_provider_for_runtime_adapter
- prefs = resolve_run_preferences(integration, slack_user_id, override=model_override)
+ prefs = resolve_run_preferences(
+ integration, slack_user_id, override=model_override, team_id=team_id, user_id=user_id
+ )
provider = get_provider_for_runtime_adapter(prefs.runtime_adapter) if prefs.runtime_adapter else None
state = {
"runtime_adapter": prefs.runtime_adapter,
@@ -1309,7 +1316,11 @@ def _resume_task_with_new_run(
# including the runtime a live run could never be moved onto. Resolved rather than
# carried over, like the keys above: a preference changed since the previous run is
# picked up too.
- extra_state.update(_run_preference_state(integration, slack_user_id, model_override))
+ extra_state.update(
+ _run_preference_state(
+ integration, slack_user_id, model_override, team_id=mapping.task.team_id, user_id=run_actor.id
+ )
+ )
extra_state.update(tasks_facade.get_resume_snapshot_carry_state(previous_state))
extra_state["resume_from_run_id"] = str(previous_run.id)
@@ -1339,7 +1350,12 @@ def _resume_task_with_new_run(
extra_state["slack_mention_workflow_id"] = derive_mention_workflow_id(inputs)
try:
- new_run = tasks_facade.create_run(mapping.task_id, mode="interactive", extra_state=extra_state)
+ # The replying user, not the task creator: the safety-net default resolution and
+ # its gated-model entitlement check inside `create_run` must run against whoever
+ # launches this follow-up.
+ new_run = tasks_facade.create_run(
+ mapping.task_id, mode="interactive", extra_state=extra_state, acting_user_id=run_actor.id
+ )
except Exception:
logger.exception(
"posthog_code_resume_create_run_failed",
diff --git a/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx
index c69132090c70..f7f32bbeb20b 100644
--- a/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx
+++ b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx
@@ -49,6 +49,12 @@ export interface ComposerModelEffortPickersProps {
* offered as disabled. `null`/omitted means nothing is running and every harness is selectable.
*/
lockedRuntimeAdapter?: string | null
+ /** The selection shown is the resolved default (user/project preference), not an explicit pick for
+ * this run — the model trigger renders a "Default ·" prefix so that's visible at a glance. */
+ isDefaultSelection?: boolean
+ /** Clears the explicit pick so the run falls back to the resolved default. Omit on a surface with no
+ * configured default and the reset row falls back to the ladder's balanced notch. */
+ onResetToDefault?: () => void
}
interface PickerSectionProps {
@@ -83,9 +89,9 @@ function PickerSection({ title, current, value, onValueChange, children }: Picke
* send time), the new-task composer wires it to the form that seeds the first run.
*
* One chip opens the Faster/Smarter capability slider, whose stops are model + effort pairings from the shared ladder.
- * Behind Advanced sits the full Harness → Model → Reasoning cascade and a reset row. This mirrors the desktop app's
- * merged model + reasoning control so the two surfaces read the same. Every option comes from the passed catalogue;
- * nothing about a specific model is hardcoded here.
+ * Behind Advanced sits the full Harness → Model → Reasoning cascade; a single reset row closes both views. This mirrors
+ * the desktop app's merged model + reasoning control so the two surfaces read the same. Every option comes from the
+ * passed catalogue; nothing about a specific model is hardcoded here.
*/
export function ComposerModelEffortPickers({
models,
@@ -94,6 +100,8 @@ export function ComposerModelEffortPickers({
onModelChange,
onEffortChange,
lockedRuntimeAdapter,
+ isDefaultSelection = false,
+ onResetToDefault,
}: ComposerModelEffortPickersProps): JSX.Element {
const [open, setOpen] = useState(false)
const [advanced, setAdvanced] = useState(false)
@@ -183,7 +191,7 @@ export function ComposerModelEffortPickers({
<DropdownMenuTrigger
render={
<Button variant="outline" size="sm">
- {modelLabel}
+ {isDefaultSelection ? `Default · ${modelLabel}` : modelLabel}
{effortOptions.length > 0 && (
<span className="text-muted">{getEffortLabel(selectedEffort)}</span>
)}
@@ -257,21 +265,6 @@ export function ComposerModelEffortPickers({
))}
</PickerSection>
)}
-
- {stops.length > 0 && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={() =>
- // The middle notch is the balanced default for the whole ladder.
- selectAndClose(() => selectStop(stops[Math.floor((stops.length - 1) / 2)]))
- }
- >
- <IconRevert />
- Reset to default
- </DropdownMenuItem>
- </>
- )}
</>
) : (
<ComposerReasoningSlider
@@ -284,6 +277,26 @@ export function ComposerModelEffortPickers({
}}
/>
)}
+
+ {/* One reset for both meanings of "default": drop the pick so the configured project/user
+ default applies where a surface knows about one, else land on the ladder's balanced
+ notch. Two rows for the two notions read as a duplicate, since only one ever acts. */}
+ {(onResetToDefault || stops.length > 0) && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ disabled={Boolean(onResetToDefault) && isDefaultSelection}
+ onClick={() =>
+ selectAndClose(
+ onResetToDefault ?? (() => selectStop(stops[Math.floor((stops.length - 1) / 2)]))
+ )
+ }
+ >
+ <IconRevert />
+ Reset to default
+ </DropdownMenuItem>
+ </>
+ )}
</DropdownMenuContent>
</DropdownMenu>
)
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
index 0672bae643ae..abf5db483fc6 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
@@ -8,7 +8,6 @@ import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
import {
buildRunCreateRequest,
- DEFAULT_COMPOSER_EFFORT,
DEFAULT_COMPOSER_MODEL,
resolveEffortForModel,
} from 'products/posthog_ai/frontend/utils/composerModels'
@@ -37,6 +36,7 @@ import { attachedContextLogic } from './attachedContextLogic'
import { modelCatalogueLogic } from './modelCatalogueLogic'
import { isTerminalRunStatus, runStreamLogic } from './runStreamLogic'
import type { RunStatus } from './runStreamLogic'
+import { taskRunDefaultsLogic } from './taskRunDefaultsLogic'
import { taskWarmLogic } from './taskWarmLogic'
import { toolStreamEventsLogic } from './toolStreamEventsLogic'
@@ -98,6 +98,8 @@ export interface runInteractionLogicValues {
isThinking: boolean // runStreamLogic
pendingPermissionRequest: PermissionRequestRecord | null // runStreamLogic
respondingToPermission: boolean // runStreamLogic
+ defaultEffort: string | null // taskRunDefaultsLogic
+ defaultModel: string | null // taskRunDefaultsLogic
canSend: boolean
clearing: boolean
composerForm: {
@@ -347,10 +349,11 @@ export interface runInteractionLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
isTerminal: (currentRunStatus: RunStatus | null) => boolean
- selectedModel: (modelOverride: string | null, arg: any) => string
+ selectedModel: (modelOverride: string | null, arg: any, defaultModel: string | null) => string
selectedEffort: (
effortOverride: string | null,
arg: any,
+ defaultEffort: string | null,
selectedModel: string,
catalogue: ModelChoiceApi[]
) => ReasoningEffortEnumApi
@@ -416,6 +419,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
['dataProcessingAccepted'],
modelCatalogueLogic,
['catalogue'],
+ taskRunDefaultsLogic,
+ ['defaultModel', 'defaultEffort'],
],
actions: [
runStreamLogic({ streamKey: props.streamKey ?? props.runId }),
@@ -626,20 +631,22 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
(status: null | import('./runStreamLogic').RunStatus): boolean => isTerminalRunStatus(status),
],
// The model/effort to display in the picker and launch the next run with: the optimistic client-side
- // override, else the run's stored value, else the default. Effort is clamped to one the model supports.
+ // override, else the run's stored value, else the server-resolved default (user preference over
+ // project default), else the built-in default. Effort is clamped to one the model supports.
selectedModel: [
- (s) => [s.modelOverride, (_, p) => p.currentModel],
- (override: string | null, current): string => override ?? current ?? DEFAULT_COMPOSER_MODEL,
+ (s) => [s.modelOverride, (_, p) => p.currentModel, s.defaultModel],
+ (override: string | null, current, serverDefault: string | null): string =>
+ override ?? current ?? serverDefault ?? DEFAULT_COMPOSER_MODEL,
],
selectedEffort: [
- (s) => [s.effortOverride, (_, p) => p.currentEffort, s.selectedModel, s.catalogue],
+ (s) => [s.effortOverride, (_, p) => p.currentEffort, s.defaultEffort, s.selectedModel, s.catalogue],
(
override: string | null,
current: string | null | undefined,
+ serverDefault: string | null,
model: string,
catalogue: ModelChoiceApi[]
- ): ReasoningEffortEnumApi =>
- resolveEffortForModel(catalogue, override ?? current ?? DEFAULT_COMPOSER_EFFORT, model),
+ ): ReasoningEffortEnumApi => resolveEffortForModel(catalogue, override ?? current ?? serverDefault, model),
],
// The permission mode to display and launch with: the client-side override, else the session's live
// mode (from the stream's `current_mode_update` frames), else the run's stored launch mode, else the
@@ -773,10 +780,11 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
// `set_config_option` command before the message rather than ride inside `user_message`. A
// failure here aborts the send (the catch restores the content); `setSent*` runs only after a
// successful sync so the next send retries an unsent change.
- const activeModel = values.sentModel ?? props.currentModel ?? DEFAULT_COMPOSER_MODEL
+ const activeModel =
+ values.sentModel ?? props.currentModel ?? values.defaultModel ?? DEFAULT_COMPOSER_MODEL
const activeEffort = resolveEffortForModel(
values.catalogue,
- values.sentEffort ?? props.currentEffort ?? DEFAULT_COMPOSER_EFFORT,
+ values.sentEffort ?? props.currentEffort ?? values.defaultEffort,
activeModel
)
if (values.selectedModel !== activeModel) {
diff --git a/products/posthog_ai/frontend/logics/taskRunDefaultsLogic.ts b/products/posthog_ai/frontend/logics/taskRunDefaultsLogic.ts
new file mode 100644
index 000000000000..2092dda6e10c
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/taskRunDefaultsLogic.ts
@@ -0,0 +1,119 @@
+import { MakeLogicType, afterMount, connect, kea, path, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { projectLogic } from 'scenes/projectLogic'
+
+import { tasksMeConfigList } from 'products/tasks/frontend/generated/api'
+import type {
+ TasksResolvedAIRunDefaultsApi,
+ TasksUserConfigResponseApi,
+} from 'products/tasks/frontend/generated/api.schemas'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taskRunDefaultsLogicValues {
+ currentProjectId: number | null // projectLogic
+ defaultEffort: string | null
+ defaultModel: string | null
+ defaultRuntimeAdapter: string | null
+ myConfig: TasksUserConfigResponseApi | null
+ myConfigLoading: boolean
+ resolvedDefaults: TasksResolvedAIRunDefaultsApi | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taskRunDefaultsLogicActions {
+ loadMyConfig: () => any
+ loadMyConfigFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadMyConfigSuccess: (
+ myConfig: TasksUserConfigResponseApi | null,
+ payload?: any
+ ) => {
+ myConfig: TasksUserConfigResponseApi | null
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taskRunDefaultsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ resolvedDefaults: (myConfig: TasksUserConfigResponseApi | null) => TasksResolvedAIRunDefaultsApi | null
+ defaultModel: (resolvedDefaults: TasksResolvedAIRunDefaultsApi | null) => string | null
+ defaultEffort: (resolvedDefaults: TasksResolvedAIRunDefaultsApi | null) => string | null
+ defaultRuntimeAdapter: (resolvedDefaults: TasksResolvedAIRunDefaultsApi | null) => string | null
+ }
+}
+
+export type taskRunDefaultsLogicType = MakeLogicType<
+ taskRunDefaultsLogicValues,
+ taskRunDefaultsLogicActions,
+ Record<string, any>,
+ taskRunDefaultsLogicMeta
+>
+
+/**
+ * The server-side default AI run configuration for the current user in the current project —
+ * the user's per-project preference over the project default, as resolved by the tasks backend.
+ * Composers read it to show what a run launches with when nothing is picked; a run created
+ * without an explicit selection gets the same defaults applied server-side.
+ */
+export const taskRunDefaultsLogic = kea<taskRunDefaultsLogicType>([
+ path(['products', 'posthog_ai', 'frontend', 'logics', 'taskRunDefaultsLogic']),
+
+ connect(() => ({
+ values: [projectLogic, ['currentProjectId']],
+ })),
+
+ loaders(({ values }) => ({
+ myConfig: {
+ __default: null as TasksUserConfigResponseApi | null,
+ loadMyConfig: async (): Promise<TasksUserConfigResponseApi | null> => {
+ if (values.currentProjectId == null) {
+ return null
+ }
+ try {
+ return await tasksMeConfigList(String(values.currentProjectId))
+ } catch {
+ // Defaults are a nicety — a failed fetch (missing scope, transient error) must never
+ // break the composer, which falls back to its built-in defaults.
+ return null
+ }
+ },
+ },
+ })),
+
+ selectors({
+ resolvedDefaults: [
+ (s) => [s.myConfig],
+ (myConfig: TasksUserConfigResponseApi | null): TasksResolvedAIRunDefaultsApi | null =>
+ myConfig?.resolved_ai_run_defaults ?? null,
+ ],
+ // Whatever runtime the default names: the composer's pickers are runtime-aware (they scope the
+ // permission modes to the selected model's harness), so a Codex default renders as readily as a
+ // Claude one. Filtering by adapter here would drop the preference to the built-in model rather
+ // than to the next level that configured one, which reads as the setting being ignored.
+ defaultModel: [
+ (s) => [s.resolvedDefaults],
+ (defaults: TasksResolvedAIRunDefaultsApi | null): string | null => defaults?.model ?? null,
+ ],
+ defaultEffort: [
+ (s) => [s.resolvedDefaults],
+ (defaults: TasksResolvedAIRunDefaultsApi | null): string | null => defaults?.reasoning_effort ?? null,
+ ],
+ // The server already resolved which runtime the default belongs to; carrying it beats
+ // re-deriving from the client catalogue, which can be stale and mislabel the harness.
+ defaultRuntimeAdapter: [
+ (s) => [s.resolvedDefaults],
+ (defaults: TasksResolvedAIRunDefaultsApi | null): string | null => defaults?.runtime_adapter ?? null,
+ ],
+ }),
+
+ afterMount(({ actions }) => {
+ actions.loadMyConfig()
+ }),
+])
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
index f7c7aa30acb4..2f3e0f7dd994 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
@@ -31,11 +31,20 @@ import { RepositorySelector } from './RepositorySelector'
export function TaskComposer(): JSX.Element {
const { submitNewTask, setNewTaskData, setActiveSuggestionGroup, applySuggestion, clearConsentBlock } =
useActions(taskTrackerSceneLogic)
- const { newTaskData, isSubmittingTask, activeSuggestionGroup, displayHeadline, consentBlocked } =
- useValues(taskTrackerSceneLogic)
+ const {
+ newTaskData,
+ isSubmittingTask,
+ activeSuggestionGroup,
+ displayHeadline,
+ consentBlocked,
+ displayModel,
+ displayEffort,
+ isDefaultSelection,
+ // Permission modes belong to the harness, so they follow the model actually shown — the
+ // server-resolved default's own runtime when nothing is picked, the pick's otherwise.
+ composerAdapter,
+ } = useValues(taskTrackerSceneLogic)
const { catalogue } = useValues(modelCatalogueLogic)
- // Permission modes belong to the harness, so they follow the picked model.
- const composerAdapter = getRuntimeAdapterForModel(catalogue, newTaskData.model)
// The bound instance's key — 'scene' on `/ai` and `/tasks`, the panel key when embedded. The onboarding
// takeover is keyed the same way, so a starter prompt chosen on replay reaches this composer.
@@ -106,8 +115,9 @@ export function TaskComposer(): JSX.Element {
/>
<ComposerModelEffortPickers
models={catalogue}
- selectedModel={newTaskData.model}
- selectedEffort={newTaskData.reasoningEffort}
+ selectedModel={displayModel}
+ selectedEffort={displayEffort}
+ isDefaultSelection={isDefaultSelection}
onModelChange={(model) =>
setNewTaskData({
model,
@@ -126,6 +136,9 @@ export function TaskComposer(): JSX.Element {
})
}
onEffortChange={(reasoningEffort) => setNewTaskData({ reasoningEffort })}
+ // Clearing both pins is what hands the choice back to the resolved
+ // default — submit then omits the triple entirely.
+ onResetToDefault={() => setNewTaskData({ model: null, reasoningEffort: null })}
/>
</Composer.Footer>
</Composer.Frame>
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index 362eb6b61a1a..84d46a685cd3 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -40,6 +40,16 @@ describe('taskTrackerSceneLogic', () => {
let runBody: Record<string, any> | null
let toolEvents: ReturnType<typeof toolStreamEventsLogic.build>
+ const myConfigResponse = (resolved: Record<string, any> | null): Record<string, any> => ({
+ ai_run_preferences: {},
+ resolved_ai_run_defaults: resolved ?? {
+ runtime_adapter: null,
+ model: null,
+ reasoning_effort: null,
+ source: 'none',
+ },
+ })
+
beforeEach(() => {
createBody = null
runBody = null
@@ -48,6 +58,7 @@ describe('taskTrackerSceneLogic', () => {
'/api/code/invites/check-access/': { has_access: true, has_loops_access: false },
'/api/projects/:team/tasks/': { results: [], count: 0 },
'/api/projects/:team/tasks/repositories/': { repositories: [] },
+ '/api/projects/:team/tasks/@me/config/': myConfigResponse(null),
'/api/environments/:team/integrations/': { results: [] },
},
post: {
@@ -144,10 +155,13 @@ describe('taskTrackerSceneLogic', () => {
expect(createBody).toMatchObject({
branch: null,
- model: 'claude-sonnet-5',
initial_permission_mode: 'auto',
pending_user_message: 'do the thing',
})
+ // An untouched selection defers the model triple to the backend, which resolves the
+ // stored default for warm matching the same way the warm was provisioned.
+ expect(createBody?.model).toBeUndefined()
+ expect(createBody?.runtime_adapter).toBeUndefined()
expect(runBody).toBeNull()
expect(logic.values.activeCreation?.runId).toBe('warm-run-1')
})
@@ -202,6 +216,66 @@ describe('taskTrackerSceneLogic', () => {
consent.unmount()
jest.restoreAllMocks()
})
+ // An untouched selection pins nothing: the server resolves the stored team/user default
+ // (or its own fallback), so the run can never freeze a client-side guess — a failed or
+ // in-flight defaults fetch used to pin the built-in model over the configured default.
+ // An explicit pick still sends the full selection.
+ it.each([
+ {
+ description: 'omits the runtime selection when nothing is picked and a default exists',
+ resolved: {
+ runtime_adapter: 'claude',
+ model: 'claude-sonnet-4-6',
+ reasoning_effort: 'high',
+ source: 'team',
+ },
+ pick: null,
+ },
+ {
+ description: 'omits the runtime selection when nothing is picked and no default exists',
+ resolved: null,
+ pick: null,
+ },
+ ])('$description', async ({ resolved, pick }) => {
+ useMocks({ get: { '/api/projects/:team/tasks/@me/config/': myConfigResponse(resolved) } })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setNewTaskData({ description: 'do the thing', ...(pick ? { model: pick } : {}) })
+ logic.actions.submitNewTask()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(runBody?.model).toBeUndefined()
+ expect(runBody?.runtime_adapter).toBeUndefined()
+ // The launch mode is still the composer's to state; the server clamps it to whichever
+ // runtime the default resolves to.
+ expect(runBody?.initial_permission_mode).not.toBeUndefined()
+ })
+
+ it('sends the full selection for an explicit pick even when a server default exists', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team/tasks/@me/config/': myConfigResponse({
+ runtime_adapter: 'claude',
+ model: 'claude-sonnet-4-6',
+ reasoning_effort: 'high',
+ source: 'team',
+ }),
+ },
+ })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setNewTaskData({ description: 'do the thing', model: 'claude-opus-4-8' })
+ logic.actions.submitNewTask()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(runBody?.model).toEqual('claude-opus-4-8')
+ expect(runBody?.runtime_adapter).toEqual('claude')
+ expect(runBody?.initial_permission_mode).not.toBeUndefined()
+ // The one-off pick resets after submit, back to "use default".
+ expect(logic.values.newTaskData.model).toBeNull()
+ })
// The repo picker only renders once `repositoryConfig.integrationId` is set (auto-selected from the
// connected GitHub org). Submitting resets the form, wiping that id; without re-deriving it the picker
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index 59366855986a..6838b2433089 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -11,6 +11,8 @@ import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
import { codeInvitesCheckAccessRetrieve, tasksCreate, tasksRunCreate } from 'products/tasks/frontend/generated/api'
import {
+ type ClaudeTaskRunCreateSchemaApi,
+ type CodexTaskRunCreateSchemaApi,
type LegacyDesktopAccessResponseApi,
type ModelChoiceApi,
TaskOriginProductEnumApi,
@@ -30,6 +32,7 @@ import type { ComposerSeed } from '../../logics/composerSeedLogic'
import { modelCatalogueLogic } from '../../logics/modelCatalogueLogic'
import { runnerPanelLogic } from '../../logics/runnerPanelLogic'
import type { ActiveCreation } from '../../logics/runnerPanelLogic'
+import { taskRunDefaultsLogic } from '../../logics/taskRunDefaultsLogic'
import { tasksLogic } from '../../logics/tasksLogic'
import { taskWarmLogic } from '../../logics/taskWarmLogic'
import type { WarmLease } from '../../logics/taskWarmLogic'
@@ -40,8 +43,9 @@ import type { RepositoryConfig, Task } from '../../types/taskTypes'
import type { TaskListParams } from '../../types/taskTypes'
import {
buildRunCreateRequest,
- DEFAULT_COMPOSER_EFFORT,
+ buildServerResolvedRunCreateRequest,
DEFAULT_COMPOSER_MODEL,
+ getRuntimeAdapterForModel,
resolveEffortForModel,
} from '../../utils/composerModels'
import { DEFAULT_COMPOSER_MODE, type PermissionMode } from '../../utils/composerModes'
@@ -52,8 +56,11 @@ export type { ActiveCreation } from '../../logics/runnerPanelLogic'
export interface TaskCreateForm {
description: string
repositoryConfig: RepositoryConfig
- model: string
- reasoningEffort: ReasoningEffortEnumApi
+ /** null = no explicit pick; the run launches with the server-resolved default (user preference
+ * over project default, else the built-in composer default). An explicit pick applies to this
+ * run only — the form resets to null after submit. */
+ model: string | null
+ reasoningEffort: ReasoningEffortEnumApi | null
permissionMode: PermissionMode
}
@@ -79,30 +86,45 @@ const LAST_REPOSITORY_CONFIG_STORAGE_KEY = 'posthog_ai.tasks.lastRepositoryConfi
* book a sandbox on `null` and then miss on submit. Repo-less drafts carry `null` on both sides and
* warm immediately.
*/
-function buildWarmRequest(form: TaskCreateForm, catalogue: ModelChoiceApi[]): WarmTaskRequestApi | null {
+function buildWarmRequest(
+ form: TaskCreateForm,
+ catalogue: ModelChoiceApi[],
+ // The displayed selection, not the raw form pick: a partially pinned form still warms on
+ // exactly the triple the submit will send.
+ displayModel: string,
+ displayEffort: ReasoningEffortEnumApi
+): WarmTaskRequestApi | null {
const { repositoryConfig, model, reasoningEffort, permissionMode } = form
if (repositoryConfig.repository && !repositoryConfig.branch) {
return null
}
- const runRequest = buildRunCreateRequest(
- catalogue,
- model,
- resolveEffortForModel(catalogue, reasoningEffort, model),
- permissionMode,
- { branch: repositoryConfig.branch ?? null }
- )
+ const base = {
+ repository: repositoryConfig.repository ?? null,
+ github_integration: repositoryConfig.integrationId ?? null,
+ branch: repositoryConfig.branch ?? null,
+ origin_product: WarmTaskRequestOriginProductEnumApi.PosthogAi,
+ }
+ // An untouched selection warms without the triple, mirroring the submit: the backend
+ // resolves the stored default for provisioning and matching alike, so both sides agree
+ // whatever the defaults fetch has or hasn't returned yet.
+ if (!model && !reasoningEffort) {
+ return {
+ ...base,
+ initial_permission_mode: permissionMode as WarmTaskRequestApi['initial_permission_mode'],
+ }
+ }
+ const runRequest = buildRunCreateRequest(catalogue, displayModel, displayEffort, permissionMode, {
+ branch: repositoryConfig.branch ?? null,
+ })
if (!('runtime_adapter' in runRequest)) {
return null
}
return {
- repository: repositoryConfig.repository ?? null,
- github_integration: repositoryConfig.integrationId ?? null,
- branch: runRequest.branch,
+ ...base,
runtime_adapter: runRequest.runtime_adapter,
model: runRequest.model,
reasoning_effort: runRequest.reasoning_effort,
initial_permission_mode: runRequest.initial_permission_mode,
- origin_product: WarmTaskRequestOriginProductEnumApi.PosthogAi,
}
}
@@ -112,8 +134,8 @@ const EMPTY_TASK_FORM: TaskCreateForm = {
integrationId: undefined,
repository: undefined,
},
- model: DEFAULT_COMPOSER_MODEL,
- reasoningEffort: DEFAULT_COMPOSER_EFFORT,
+ model: null,
+ reasoningEffort: null,
permissionMode: DEFAULT_COMPOSER_MODE,
}
@@ -127,18 +149,25 @@ export interface taskTrackerSceneLogicValues {
currentProjectId: number | null // projectLogic
activeCreation: ActiveCreation | null // runnerPanelLogic
historyExpanded: boolean // runnerPanelLogic
+ defaultEffort: string | null // taskRunDefaultsLogic
+ defaultModel: string | null // taskRunDefaultsLogic
+ defaultRuntimeAdapter: string | null // taskRunDefaultsLogic
warmLease: WarmLease | null // taskWarmLogic
repositories: string[] // tasksLogic
taskListParams: TaskListParams // tasksLogic
tasks: Task[] // tasksLogic
overrideHeadlines: string[] | null // welcomeOverrideLogic
activeSuggestionGroup: SuggestionGroup | null
+ composerAdapter: string
consentBlocked: boolean
desktopAccess: LegacyDesktopAccessResponseApi | null
desktopAccessLoading: boolean
+ displayEffort: ReasoningEffortEnumApi
displayHeadline: string
+ displayModel: string
hasDesktopAccess: boolean
headlineSeed: number
+ isDefaultSelection: boolean
isSubmittingTask: boolean
newTaskData: TaskCreateForm
persistedRepositoryConfig: PersistedRepositoryConfig
@@ -386,6 +415,20 @@ export interface taskTrackerSceneLogicMeta {
__keaTypeGenInternalSelectorTypes: {
hasDesktopAccess: (desktopAccess: LegacyDesktopAccessResponseApi | null) => boolean
displayHeadline: (overrideHeadlines: string[] | null, headlineSeed: number) => string
+ displayModel: (newTaskData: TaskCreateForm, defaultModel: string | null) => string
+ displayEffort: (
+ newTaskData: TaskCreateForm,
+ defaultEffort: string | null,
+ displayModel: string,
+ catalogue: ModelChoiceApi[]
+ ) => ReasoningEffortEnumApi
+ composerAdapter: (
+ newTaskData: TaskCreateForm,
+ displayModel: string,
+ defaultRuntimeAdapter: string | null,
+ catalogue: ModelChoiceApi[]
+ ) => string
+ isDefaultSelection: (newTaskData: TaskCreateForm) => boolean
}
}
@@ -429,6 +472,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// the resume endpoint for a task that doesn't exist yet.
taskWarmLogic({ panelId: props.panelId }),
['warmLease'],
+ taskRunDefaultsLogic,
+ ['defaultModel', 'defaultEffort', 'defaultRuntimeAdapter'],
],
actions: [
runnerPanelLogic(props),
@@ -543,6 +588,47 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
],
}),
+ selectors({
+ // The pickers render these and a submit sends exactly these, so the composer can never
+ // show one model or effort while the run launches with another.
+ displayModel: [
+ (s) => [s.newTaskData, s.defaultModel],
+ (newTaskData: TaskCreateForm, defaultModel: string | null): string =>
+ newTaskData.model ?? defaultModel ?? DEFAULT_COMPOSER_MODEL,
+ ],
+ displayEffort: [
+ (s) => [s.newTaskData, s.defaultEffort, s.displayModel, s.catalogue],
+ (
+ newTaskData: TaskCreateForm,
+ defaultEffort: string | null,
+ displayModel: string,
+ catalogue: ModelChoiceApi[]
+ ): ReasoningEffortEnumApi =>
+ resolveEffortForModel(catalogue, newTaskData.reasoningEffort ?? defaultEffort, displayModel),
+ ],
+ // The harness the composer's controls speak for. An explicit pick derives it from the
+ // catalogue; an untouched selection carries the server-resolved default's adapter, which
+ // stays right even when a stale catalogue no longer lists the default's model.
+ composerAdapter: [
+ (s) => [s.newTaskData, s.displayModel, s.defaultRuntimeAdapter, s.catalogue],
+ (
+ newTaskData: TaskCreateForm,
+ displayModel: string,
+ defaultRuntimeAdapter: string | null,
+ catalogue: ModelChoiceApi[]
+ ): string =>
+ newTaskData.model || !defaultRuntimeAdapter
+ ? getRuntimeAdapterForModel(catalogue, displayModel)
+ : defaultRuntimeAdapter,
+ ],
+ // Neither picker touched: submit omits the triple so the backend resolves it, which also
+ // lets a warm run provisioned under the default match.
+ isDefaultSelection: [
+ (s) => [s.newTaskData],
+ (newTaskData: TaskCreateForm): boolean => !newTaskData.model && !newTaskData.reasoningEffort,
+ ],
+ }),
+
listeners(({ actions, values, cache, props }) => ({
// Release the manually-mounted optimistic stream once the create resolves (navigated to the real run)
// or fails (returned to the composer), so the throwaway draft instance never leaks.
@@ -571,7 +657,12 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// sandbox and clones the selected repository, so it must not run before the organization
// accepts AI data processing.
if (!values.activeCreation && values.dataProcessingAccepted) {
- const request = buildWarmRequest(values.newTaskData, values.catalogue)
+ const request = buildWarmRequest(
+ values.newTaskData,
+ values.catalogue,
+ values.displayModel,
+ values.displayEffort
+ )
if (request) {
actions.noteDraft(values.newTaskData.description.trim().length > 0, request)
}
@@ -618,7 +709,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
return
}
- const { description, repositoryConfig, model, reasoningEffort, permissionMode } = values.newTaskData
+ const { description, repositoryConfig, permissionMode } = values.newTaskData
if (!description.trim()) {
lemonToast.error('Description is required')
@@ -647,20 +738,31 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
try {
const pendingUserMessage = wrapWithPosthogContext(description, seededContext)
- const runRequest = buildRunCreateRequest(
- values.catalogue,
- model,
- resolveEffortForModel(values.catalogue, reasoningEffort, model),
- permissionMode,
- {
- branch: repositoryConfig.branch ?? null,
- mode: TaskExecutionModeEnumApi.Interactive,
- pending_user_message: pendingUserMessage,
+ const runPayload = {
+ branch: repositoryConfig.branch ?? null,
+ mode: TaskExecutionModeEnumApi.Interactive,
+ pending_user_message: pendingUserMessage,
+ }
+ // An untouched selection pins nothing: the backend resolves the model triple from the
+ // stored team/user default (correct even while the defaults fetch is in flight or has
+ // failed) and clamps the stated permission mode to the resolved runtime. The warm run
+ // was provisioned the same way, so provisioning and matching resolve alike. An explicit
+ // pick sends the full displayed selection, runtime derived from the model.
+ let pinnedRequest: ClaudeTaskRunCreateSchemaApi | CodexTaskRunCreateSchemaApi | null = null
+ if (!values.isDefaultSelection) {
+ const built = buildRunCreateRequest(
+ values.catalogue,
+ values.displayModel,
+ values.displayEffort,
+ permissionMode,
+ runPayload
+ )
+ if (!('runtime_adapter' in built)) {
+ throw new Error('Run request is missing a runtime adapter')
}
- )
- if (!('runtime_adapter' in runRequest)) {
- throw new Error('Run request is missing a runtime adapter')
+ pinnedRequest = built
}
+ const runRequest = pinnedRequest ?? buildServerResolvedRunCreateRequest(permissionMode, runPayload)
const taskData: TaskWriteApi = {
title: '',
description,
@@ -671,12 +773,17 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// Warm-reuse hints. The backend matches these against an idling warm Run and, on a hit,
// activates it in place and returns it as `latest_run` — no second Run is created. All of
// them are write-only and ignored on a cold create. `branch` must be present as a key
- // (even `null`) or reuse is never attempted at all.
- branch: runRequest.branch ?? null,
- runtime_adapter: runRequest.runtime_adapter,
- model: runRequest.model,
- reasoning_effort: runRequest.reasoning_effort,
- initial_permission_mode: runRequest.initial_permission_mode,
+ // (even `null`) or reuse is never attempted at all. The model triple is left off when
+ // the selection is untouched, so the backend resolves it for warm matching too.
+ branch: runPayload.branch,
+ ...(pinnedRequest
+ ? {
+ runtime_adapter: pinnedRequest.runtime_adapter,
+ model: pinnedRequest.model,
+ reasoning_effort: pinnedRequest.reasoning_effort,
+ initial_permission_mode: pinnedRequest.initial_permission_mode,
+ }
+ : { initial_permission_mode: permissionMode }),
pending_user_message: pendingUserMessage,
}
diff --git a/products/posthog_ai/frontend/utils/composerModels.ts b/products/posthog_ai/frontend/utils/composerModels.ts
index 8194ccae8e04..d94c34e14ca7 100644
--- a/products/posthog_ai/frontend/utils/composerModels.ts
+++ b/products/posthog_ai/frontend/utils/composerModels.ts
@@ -141,6 +141,18 @@ export function getEffortLabel(effort: string | null | undefined): string {
return effort ? (EFFORT_LABELS[effort] ?? effort) : 'Effort'
}
+// Keep an effort only if the model supports it, else nothing. The stored-preference counterpart of
+// `resolveEffortForModel`: a settings row wants "no pick" when the effort no longer applies, where a
+// composer wants a concrete value to send. Mirrors the backend's `filter_unsupported_effort`.
+export function filterEffortForModel(
+ catalogue: ModelChoiceApi[],
+ effort: string | null | undefined,
+ model: string | null | undefined
+): ReasoningEffortEnumApi | null {
+ const allowed = getEffortsForModel(catalogue, model).map((option) => option.value)
+ return effort && allowed.includes(effort as ReasoningEffortEnumApi) ? (effort as ReasoningEffortEnumApi) : null
+}
+
// Clamp an effort to one the selected model actually supports — the new-run path can inherit an effort from a
// previous run on a different model (e.g. `max` carried over to a model that only offers low/medium/high), and the
// backend rejects an out-of-range effort. Falls back to the default when valid, else the highest available.
@@ -161,6 +173,22 @@ export function resolveEffortForModel(
return allowed.includes(DEFAULT_COMPOSER_EFFORT) ? DEFAULT_COMPOSER_EFFORT : allowed[allowed.length - 1]
}
+/**
+ * A run-create request that pins no runtime selection at all: the backend resolves the model
+ * triple from the stored team/user default (or its own fallback), and the permission mode
+ * rides along, clamped server-side to whichever runtime the default names. Used whenever the
+ * composer's selection is untouched — pinning the displayed fallback instead would freeze a
+ * value the server could have resolved better (and would go stale the moment the default
+ * changes or a fetch fails). The generated request types are discriminated on
+ * `runtime_adapter`, so this shape deliberately steps outside them.
+ */
+export function buildServerResolvedRunCreateRequest(
+ permissionMode: PermissionMode,
+ rest: Partial<TaskRunCreateRequestSchemaApi>
+): TaskRunCreateRequestSchemaApi {
+ return { ...rest, initial_permission_mode: permissionMode } as unknown as TaskRunCreateRequestSchemaApi
+}
+
/**
* Build a run-create request for the picked model.
*
diff --git a/products/slack_app/backend/services/run_preferences.py b/products/slack_app/backend/services/run_preferences.py
index 36e856f36e90..5870c1eb55d3 100644
--- a/products/slack_app/backend/services/run_preferences.py
+++ b/products/slack_app/backend/services/run_preferences.py
@@ -34,6 +34,8 @@ from products.slack_app.backend.services.slack_settings import AIPreferences, re
if TYPE_CHECKING:
from posthog.models.integration import Integration
+ from products.tasks.backend.logic.services.ai_run_defaults import ResolvedAIRunConfig
+
# What a Slack run uses when neither the user nor the workspace has pinned a model.
# Chosen here rather than left to the agent server so the App Home card and the run
# itself agree on what "unset" means.
@@ -48,6 +50,17 @@ class ModelOverride(Protocol):
reasoning_effort: str | None
+def _central_run_default(team_id: int, user_id: int | None) -> ResolvedAIRunConfig | None:
+ """The project/user default the run would resolve to downstream, or `None` when no
+ level configures one — in which case Slack's own floor still applies."""
+ from products.tasks.backend.facade import ( # noqa: PLC0415 — keep tasks deps off the slack_app import path
+ ai_run_defaults,
+ )
+
+ resolved = ai_run_defaults.resolve_ai_run_defaults(team_id, user_id)
+ return resolved if resolved.model else None
+
+
def _coherent_preferences(
model: str | None,
reasoning_effort: str | None,
@@ -72,6 +85,8 @@ def resolve_run_preferences(
slack_user_id: str | None,
*,
override: ModelOverride | None = None,
+ team_id: int | None = None,
+ user_id: int | None = None,
) -> AIPreferences:
"""Resolve the full chain for one Slack-triggered run.
@@ -80,6 +95,17 @@ def resolve_run_preferences(
own applies to whichever model the run was already going to use. Either can be
absent, and a request we can't honour — a model that isn't on offer, an effort the
model doesn't support — leaves the run on its saved preferences.
+
+ Below the saved rows sits the project/user default, which this looks up itself so
+ every Slack path — first run and follow-up alike — sits at the same rung. Slack's own
+ floor applies only when there is no central default to defer to. `team_id` and
+ `user_id` say whose defaults those are; omitting `team_id` skips the level, which is
+ what a caller with no project context (or a test exercising the Slack rungs alone)
+ wants.
+
+ Note that `resolve_ai_preferences` yields nothing at all for a workspace that
+ hasn't enabled `slack-app-home`, so there the chain is the fallback plus
+ whatever the mention asked for.
"""
override_model = override.model if override else None
override_effort = override.reasoning_effort if override else None
@@ -92,18 +118,36 @@ def resolve_run_preferences(
return _coherent_preferences(choice.model, override_effort, fallback_runtime_adapter=choice.runtime_adapter)
saved = resolve_ai_preferences(integration, slack_user_id)
+ # Slack's floor would make the project and user defaults unreachable from Slack: the
+ # run would always carry an explicit model. Stepping aside when a central default
+ # exists leaves the triple empty, so `create_run` resolves it (and a warm run
+ # provisioned under that default still matches). Anything pinned in Slack wins.
+ central_default = _central_run_default(team_id, user_id) if team_id is not None else None
base = _coherent_preferences(
- saved.model or SLACK_DEFAULT_MODEL,
+ saved.model or (None if central_default else SLACK_DEFAULT_MODEL),
saved.reasoning_effort,
fallback_runtime_adapter=saved.runtime_adapter,
)
if not override_effort:
return base
+ # An effort has to be validated against a model, and deferring leaves none here. So an
+ # effort-only mention resolves against what the downstream resolver would have chosen
+ # anyway — a run at a different effort is not the run it would have produced, so there
+ # is nothing left to defer.
+ target = base
+ if base.model is None and central_default is not None:
+ target = _coherent_preferences(
+ central_default.model,
+ central_default.reasoning_effort,
+ fallback_runtime_adapter=central_default.runtime_adapter,
+ )
+
# An effort this model can't do is dropped by `_coherent_preferences`; falling back
# to `base` rather than to the stripped result means an impossible ask leaves the
- # run alone instead of quietly clearing the saved effort as well.
- requested = _coherent_preferences(base.model, override_effort, fallback_runtime_adapter=base.runtime_adapter)
+ # run alone — still deferring where it was deferring — instead of quietly clearing
+ # the saved effort as well.
+ requested = _coherent_preferences(target.model, override_effort, fallback_runtime_adapter=target.runtime_adapter)
return requested if requested.reasoning_effort else base
diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.py
index 7d33f481f1f0..6b47e958d634 100644
--- a/products/slack_app/backend/services/slack_app_home.py
+++ b/products/slack_app/backend/services/slack_app_home.py
@@ -34,7 +34,7 @@ from posthog.user_permissions import UserPermissions
from products.slack_app.backend.feature_flags import is_slack_app_oauth_enabled
from products.slack_app.backend.models import SlackSettings, SlackUserProfileCache, UntaggedFollowupMode
-from products.slack_app.backend.services.integration_resolver import load_integrations
+from products.slack_app.backend.services.integration_resolver import load_integrations, resolve_from_candidates
from products.slack_app.backend.services.model_catalogue import (
REASONING_EFFORT_DISPLAY_NAMES,
RUNTIME_ADAPTER_DISPLAY_NAMES,
@@ -394,11 +394,37 @@ class GitHubState:
settings_url: str | None = None
+@dataclass(frozen=True)
+class RunDefaultsState:
+ """The PostHog-side default a Slack run falls back to once nothing in Slack applies.
+
+ Slack's own rows sit above this; below it sits Slack's hardcoded floor. The card reads
+ it so what it names is what a mention would actually launch on, rather than a constant
+ that stopped being the answer once project and personal defaults existed.
+ """
+
+ model: str | None = None
+ reasoning_effort: str | None = None
+ runtime_adapter: str | None = None
+ #: Which level supplied it — "user", "team", or "none".
+ source: str = "none"
+ settings_url: str | None = None
+
+ @property
+ def applies(self) -> bool:
+ return bool(self.model)
+
+ @property
+ def source_label(self) -> str:
+ return "Your PostHog default" if self.source == "user" else "The project default"
+
+
def render_home_view(
*,
effective: AIPreferences,
user_row: SlackSettings | None,
is_admin: bool,
+ run_defaults: RunDefaultsState | None = None,
account_state: AccountState | None = None,
github_state: GitHubState | None = None,
project_state: ProjectState | None = None,
@@ -440,7 +466,7 @@ def render_home_view(
# picker underneath. Purely a per-user preference — there's no workspace-wide
# model default to inherit from.
blocks.append({"type": "divider"})
- blocks.extend(_active_model_blocks(effective, source))
+ blocks.extend(_active_model_blocks(effective, source, run_defaults or RunDefaultsState()))
blocks.extend(_personal_section_blocks(user_row))
# Section 4 — thread follow-ups: whether replies other people leave in the
@@ -575,50 +601,58 @@ def _no_project_access_blocks() -> list[dict]:
return blocks
-def _active_model_blocks(effective: AIPreferences, source: PreferenceSource) -> list[dict]:
+def _active_model_blocks(
+ effective: AIPreferences, source: PreferenceSource, run_defaults: RunDefaultsState
+) -> list[dict]:
"""Headline that shows which model is actually running, and why.
- With nothing set the run falls back to the Slack default, named here from the
- same constant the run resolves against so the card can't drift from it.
+ Three rungs, named in the order the run resolves them: a Slack row, else the PostHog
+ project/personal default, else Slack's own floor. Naming the floor unconditionally
+ would describe a run that isn't going to happen wherever a PostHog default is set.
"""
header = _section_title(
"🤖 AI model",
- "Which Claude / Codex configuration handles your @PostHog mentions.",
+ "Which Claude / Codex configuration handles your @PostHog mentions. "
+ "Set one here to override what your PostHog defaults would pick.",
)
- source_blurb = {"type": "context", "elements": [{"type": "mrkdwn", "text": f"Source: {source.label}"}]}
- if effective.is_empty:
- return [
- header,
- {
- "type": "section",
- "text": {
- "type": "mrkdwn",
- "text": (
- f"Defaulting to {format_model_id(SLACK_DEFAULT_MODEL)}. Pick your own settings to override."
- ),
- },
- },
- source_blurb,
- ]
+ if not effective.is_empty:
+ headline = (
+ # Same phrasing as the notice a mention override posts, so the card and the
+ # thread describe a run the same way.
+ f"Currently running {describe_run_model(effective.model, effective.reasoning_effort)}"
+ f" · {label_for(effective.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)}"
+ )
+ source_label = source.label
+ elif run_defaults.applies:
+ headline = (
+ f"Currently running {describe_run_model(run_defaults.model, run_defaults.reasoning_effort)}"
+ f" · {label_for(run_defaults.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)}"
+ )
+ source_label = f"{run_defaults.source_label} in PostHog"
+ else:
+ headline = f"Defaulting to {format_model_id(SLACK_DEFAULT_MODEL)}. Pick your own settings to override."
+ source_label = source.label
- runtime_label = label_for(effective.runtime_adapter, RUNTIME_ADAPTER_DISPLAY_NAMES)
- return [
+ blocks: list[dict] = [
header,
- {
- "type": "section",
- "text": {
- "type": "mrkdwn",
- # Same phrasing as the notice a mention override posts, so the card and
- # the thread describe a run the same way.
- "text": (
- f"Currently running "
- f"{describe_run_model(effective.model, effective.reasoning_effort)} · {runtime_label}"
- ),
- },
- },
- source_blurb,
+ {"type": "section", "text": {"type": "mrkdwn", "text": headline}},
+ {"type": "context", "elements": [{"type": "mrkdwn", "text": f"Source: {source_label}"}]},
]
+ if run_defaults.settings_url:
+ blocks.append(
+ {
+ "type": "context",
+ "elements": [
+ {
+ "type": "mrkdwn",
+ "text": f"<{run_defaults.settings_url}|Task agent defaults in PostHog> apply everywhere — "
+ "the task composer, PostHog Desktop, and Slack when nothing is set here.",
+ }
+ ],
+ }
+ )
+ return blocks
def _project_section_blocks(state: ProjectState, *, is_admin: bool) -> list[dict]:
@@ -797,7 +831,11 @@ def _personal_section_blocks(user_row: SlackSettings | None) -> list[dict]:
"""Personal AI override sub-card. Always editable by the user themselves."""
has_override = bool(user_row and user_row.runtime_adapter and user_row.model)
- summary = _row_summary(user_row) if has_override else "_No personal override — using PostHog's default._"
+ summary = (
+ _row_summary(user_row)
+ if has_override
+ else "_No personal override. Inheriting your PostHog task agent default._"
+ )
actions: list[dict] = [
{
@@ -1489,6 +1527,7 @@ def handle_app_home_opened(event: dict, slack_team_id: str, *, integration: Inte
effective=effective,
user_row=user_row,
is_admin=is_admin,
+ run_defaults=_resolve_run_defaults_state(integration, slack_user_id, accessible=accessible),
account_state=account_state,
github_state=github_state,
project_state=project_state,
@@ -1876,6 +1915,7 @@ def _republish_home(
effective=effective,
user_row=user_row,
is_admin=is_admin,
+ run_defaults=_resolve_run_defaults_state(integration, slack_user_id, accessible=accessible),
account_state=account_state,
github_state=github_state,
project_state=project_state,
@@ -2063,6 +2103,58 @@ def _format_relative(when: datetime | None, *, now: datetime) -> str:
return when.strftime("%b %d")
+def _resolve_run_defaults_state(
+ integration: Integration, slack_user_id: str, *, accessible: list[Integration]
+) -> RunDefaultsState:
+ """The PostHog default this person's Slack runs fall back to, plus where to change it.
+
+ Resolves the viewer through the same cascade the run path uses (`_resolve_home_user`),
+ so an unlinked but email-matched identity reflects its own personal default rather than
+ dropping to the project rung, matching the model a mention of theirs would actually run.
+
+ Routed and access-filtered like a run, too: the card reads the default for the
+ project this person's mentions would actually launch in — their saved project
+ default, else the workspace's, else the oldest install, all within `accessible`.
+ Reading `integration.team_id` directly both exposed a project the viewer may not
+ reach and described a default their runs would not use.
+ """
+ from products.tasks.backend.facade import ( # noqa: PLC0415 — keep tasks deps off the slack_app import path
+ ai_run_defaults,
+ )
+
+ try:
+ target = resolve_from_candidates(
+ accessible,
+ slack_team_id=integration.integration_id,
+ slack_user_id=slack_user_id,
+ ).resolved_or_first()
+ except Exception:
+ logger.exception("slack_app_home_run_defaults_routing_failed", slack_user_id=slack_user_id)
+ target = None
+ if target is None:
+ # No reachable project: nothing to describe and no settings page to offer.
+ return RunDefaultsState()
+
+ site_url = (settings.SITE_URL or "").rstrip("/")
+ settings_url = f"{site_url}/project/{target.team_id}/settings/environment-task-agents" if site_url else None
+
+ try:
+ home_user = _resolve_home_user(integration, slack_user_id)
+ resolved = ai_run_defaults.resolve_ai_run_defaults(target.team_id, home_user.id if home_user else None)
+ except Exception:
+ # The card is informational; a lookup failure must not cost the whole Home tab.
+ logger.exception("slack_app_home_run_defaults_resolution_failed", slack_user_id=slack_user_id)
+ return RunDefaultsState(settings_url=settings_url)
+
+ return RunDefaultsState(
+ model=resolved.model,
+ reasoning_effort=resolved.reasoning_effort,
+ runtime_adapter=resolved.runtime_adapter,
+ source=resolved.source,
+ settings_url=settings_url,
+ )
+
+
def _resolve_account_state(integration: Integration, slack_user_id: str) -> AccountState:
slack_team_id = integration.integration_id
if not is_slack_app_oauth_enabled(integration):
diff --git a/products/slack_app/backend/services/slack_settings.py b/products/slack_app/backend/services/slack_settings.py
index c75746c69659..d987dfec51c8 100644
--- a/products/slack_app/backend/services/slack_settings.py
+++ b/products/slack_app/backend/services/slack_settings.py
@@ -13,6 +13,12 @@ a half-set row reads as "no preference" rather than half-applying.
stale effort from a previous model choice can't silently stick. Unset keys
stay `None` so the task layer applies its own defaults rather than
duplicating them here.
+
+Layering with the tasks product's central defaults: the resolved triple is
+passed to task creation as explicit per-run values, so Slack preferences sit
+above the central per-user / per-team defaults (see
+`products.tasks.backend.facade.ai_run_defaults`). When both Slack rows are
+empty the task layer falls back to those central defaults on its own.
"""
from __future__ import annotations
@@ -126,15 +132,14 @@ def build_ai_preferences_payload(
) -> dict[str, str]:
"""Pack the triple into the JSON shape stored on `SlackSettings.ai_preferences`.
- Drops keys whose value is `None` so callers can distinguish "intentionally
- cleared" (key absent) from "set to falsy value".
+ The same shape the tasks product stores on `ai_run_preferences`, so the packing
+ rule lives there and this is the Slack-side name for it.
"""
- payload = {
- "runtime_adapter": runtime_adapter,
- "model": model,
- "reasoning_effort": reasoning_effort,
- }
- return {k: v for k, v in payload.items() if v}
+ from products.tasks.backend.facade.ai_run_defaults import ( # noqa: PLC0415 — matches the deferred tasks-facade imports below
+ build_ai_run_preferences_payload,
+ )
+
+ return build_ai_run_preferences_payload(runtime_adapter, model, reasoning_effort)
def validate_ai_preferences(
diff --git a/products/slack_app/backend/tests/services/test_run_preferences.py b/products/slack_app/backend/tests/services/test_run_preferences.py
index 28c3044c4248..214a5ab62a98 100644
--- a/products/slack_app/backend/tests/services/test_run_preferences.py
+++ b/products/slack_app/backend/tests/services/test_run_preferences.py
@@ -45,14 +45,25 @@ class _Override:
reasoning_effort: str | None = None
-def _resolve(saved: AIPreferences, override_model=None, override_effort=None):
- """Resolve with `resolve_ai_preferences` stubbed, so these stay unit tests over the
- precedence rules rather than over the settings rows."""
- with patch.object(run_preferences, "resolve_ai_preferences", return_value=saved):
+def _resolve(
+ saved: AIPreferences,
+ override_model=None,
+ override_effort=None,
+ central_default=None,
+):
+ """Resolve with the saved rows and the central default both stubbed, so these stay
+ unit tests over the precedence rules rather than over the rows behind them."""
+ with (
+ patch.object(run_preferences, "resolve_ai_preferences", return_value=saved),
+ patch.object(run_preferences, "_central_run_default", return_value=central_default),
+ ):
return resolve_run_preferences(
integration=None, # type: ignore[arg-type]
slack_user_id="U1",
override=_Override(model=override_model, reasoning_effort=override_effort),
+ # Any id will do — the lookup it feeds is stubbed; passing one is what opts the
+ # central-default rung into the chain at all.
+ team_id=1,
)
@@ -99,6 +110,42 @@ class TestResolveRunPreferences:
saved = AIPreferences(runtime_adapter="codex", model="claude-fable-5", reasoning_effort=None)
assert _resolve(saved).runtime_adapter == "claude"
+ # Pinning a model unconditionally is what put the project and user defaults out of
+ # reach from Slack, and it fails silently — the run still works, just never on the
+ # configured model. These lock the fall-through in both directions.
+ @pytest.mark.parametrize(
+ "saved,override_model,expected",
+ [
+ (AIPreferences(), None, AIPreferences(None, None, None)),
+ (SAVED, None, SAVED),
+ (AIPreferences(), "claude-fable-5", AIPreferences("claude", "claude-fable-5", None)),
+ ],
+ )
+ def test_with_a_central_default_only_a_slack_selection_pins_the_run(
+ self, catalogue, saved, override_model, expected
+ ):
+ central = AIPreferences(runtime_adapter="claude", model="claude-fable-5", reasoning_effort=None)
+ assert _resolve(saved, override_model=override_model, central_default=central) == expected
+
+ # An effort named on its own has no model to be validated against while the run is
+ # deferring, so without the deferred default it is silently dropped and the mention
+ # does nothing at all.
+ @pytest.mark.parametrize(
+ "deferred_model,override_effort,expected",
+ [
+ ("claude-fable-5", "xhigh", AIPreferences("claude", "claude-fable-5", "xhigh")),
+ # Sonnet 4.6 takes no `xhigh`, so the ask is impossible and the run keeps
+ # deferring rather than pinning a default it was never asked to pin.
+ ("claude-sonnet-4-6", "xhigh", AIPreferences(None, None, None)),
+ ],
+ )
+ def test_an_effort_only_mention_resolves_against_the_central_default(
+ self, catalogue, deferred_model, override_effort, expected
+ ):
+ central = AIPreferences(runtime_adapter="claude", model=deferred_model, reasoning_effort=None)
+ resolved = _resolve(AIPreferences(), override_effort=override_effort, central_default=central)
+ assert resolved == expected
+
class TestResolveLiveRunOverride:
"""A run already in flight can only move within the runtime its sandbox started on."""
diff --git a/products/slack_app/backend/tests/test_app_home_run_defaults_card.py b/products/slack_app/backend/tests/test_app_home_run_defaults_card.py
new file mode 100644
index 000000000000..0d98828362c6
--- /dev/null
+++ b/products/slack_app/backend/tests/test_app_home_run_defaults_card.py
@@ -0,0 +1,39 @@
+from posthog.test.base import APIBaseTest
+
+from posthog.models import Team
+from posthog.models.integration import Integration
+
+from products.slack_app.backend.models import SlackSettings
+from products.slack_app.backend.services.slack_app_home import _resolve_run_defaults_state
+from products.tasks.backend.facade.ai_run_defaults import update_team_ai_run_preferences
+
+WORKSPACE = "TWORKSPACE"
+
+
+class TestRunDefaultsCardRouting(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.team_b = Team.objects.create(organization=self.organization, name="B")
+ self.int_a = Integration.objects.create(
+ team=self.team, kind="slack", integration_id=WORKSPACE, sensitive_config={"access_token": "x"}
+ )
+ self.int_b = Integration.objects.create(
+ team=self.team_b, kind="slack", integration_id=WORKSPACE, sensitive_config={"access_token": "x"}
+ )
+ update_team_ai_run_preferences(self.team.id, runtime_adapter="claude", model="model-a", reasoning_effort=None)
+ update_team_ai_run_preferences(self.team_b.id, runtime_adapter="claude", model="model-b", reasoning_effort=None)
+
+ # The card must never read a project outside the viewer's accessible set — the
+ # install's own team and even the workspace default can both point at a project
+ # the viewer can't reach, whose configuration would otherwise leak (and whose
+ # default their runs would not use anyway).
+ def test_card_reads_the_routed_accessible_project_not_the_installs(self):
+ SlackSettings.objects.create(slack_workspace_id=WORKSPACE, slack_user_id=None, default_integration=self.int_b)
+ state = _resolve_run_defaults_state(self.int_b, "U1", accessible=[self.int_a])
+ assert state.model == "model-a"
+ assert state.settings_url is not None and f"/project/{self.team.id}/" in state.settings_url
+
+ def test_card_renders_empty_without_an_accessible_project(self):
+ state = _resolve_run_defaults_state(self.int_b, "U1", accessible=[])
+ assert state.model is None
+ assert state.settings_url is None
diff --git a/products/tasks/backend/facade/ai_run_defaults.py b/products/tasks/backend/facade/ai_run_defaults.py
new file mode 100644
index 000000000000..9a36f1f62d54
--- /dev/null
+++ b/products/tasks/backend/facade/ai_run_defaults.py
@@ -0,0 +1,29 @@
+"""Facade re-exports for AI run default preferences.
+
+Team-level and per-(user, project) default `(runtime_adapter, model,
+reasoning_effort)` triples, applied to task runs created without an explicit
+runtime selection. Presentation and other products import from here rather
+than reaching the internal ``logic.services`` module.
+"""
+
+from products.tasks.backend.logic.services.ai_run_defaults import (
+ ResolvedAIRunConfig,
+ build_ai_run_preferences_payload,
+ get_team_ai_run_preferences,
+ get_user_ai_run_preferences,
+ resolve_ai_run_defaults,
+ update_team_ai_run_preferences,
+ update_user_ai_run_preferences,
+ validate_ai_run_preferences,
+)
+
+__all__ = [
+ "ResolvedAIRunConfig",
+ "build_ai_run_preferences_payload",
+ "get_team_ai_run_preferences",
+ "get_user_ai_run_preferences",
+ "resolve_ai_run_defaults",
+ "update_team_ai_run_preferences",
+ "update_user_ai_run_preferences",
+ "validate_ai_run_preferences",
+]
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 7ec8fc9a9c51..f159ad01c289 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -1541,10 +1541,15 @@ def create_run(
mode: str = "background",
extra_state: dict | None = None,
branch: str | None = None,
+ acting_user_id: int | None = None,
) -> contracts.TaskRunDTO:
- """Create a new run for an existing task (e.g. resuming an interactive sandbox session)."""
+ """Create a new run for an existing task (e.g. resuming an interactive sandbox session).
+
+ ``acting_user_id`` attributes the run to the user whose AI run preferences should apply
+ when ``extra_state`` pins no runtime selection; it falls back to the task's creator.
+ """
task = Task.objects.get(id=task_id)
- run = task.create_run(mode=mode, extra_state=extra_state, branch=branch)
+ run = task.create_run(mode=mode, extra_state=extra_state, branch=branch, acting_user_id=acting_user_id)
return _task_run_to_dto(run, task=task)
@@ -4691,7 +4696,9 @@ def bootstrap_task_run(
"Creating task run for task %s with mode=%s, branch=%s, environment=%s", task.id, mode, branch, environment
)
try:
- run = task.create_run(environment=environment, mode=mode, branch=branch, extra_state=extra_state)
+ run = task.create_run(
+ environment=environment, mode=mode, branch=branch, extra_state=extra_state, acting_user_id=user_id
+ )
except InvalidTaskOriginError as error:
return contracts.TaskRunCreateResult(
error=contracts.TaskRunValidationError(
@@ -5651,6 +5658,16 @@ def create_task(
# which costs latency but can never hand over a Run booted under another product's budget or
# PR-authorship rules.
if warm_branch_provided and user_id is not None:
+ # Post-defaults comparison: warm runs are provisioned with the default triple
+ # filled in, so the requested selection must be resolved the same way to match.
+ warm_selection = _with_ai_run_defaults(
+ {"runtime_adapter": warm_runtime_adapter, "model": warm_model, "reasoning_effort": warm_reasoning_effort},
+ team_id=team_id,
+ acting_user_id=user_id,
+ )
+ warm_runtime_adapter = warm_selection.get("runtime_adapter")
+ warm_model = warm_selection.get("model")
+ warm_reasoning_effort = warm_selection.get("reasoning_effort")
warm_run = _find_idling_warm_run(
team_id,
user_id,
@@ -6225,6 +6242,26 @@ def can_mint_readonly_github_token(team_id: int) -> bool:
return _can_mint(team_id)
+def _with_ai_run_defaults(data: dict, *, team_id: int, acting_user_id: int | None, internal: bool = False) -> dict:
+ """A copy of ``data`` with the team/user default AI run triple filled in when it pins
+ no runtime selection (see ``resolve_ai_run_selection``).
+
+ Applied ahead of warm-run matching so requests and warm runs compare post-defaults —
+ a warm run provisioned under the default triple must match a submit that pinned
+ nothing. ``Task.create_run`` applies the same resolution as a safety net for every
+ other path, so this is deterministic double-resolution, not a divergence.
+ """
+ if internal:
+ return data
+ from products.tasks.backend.logic.services.ai_run_defaults import ( # noqa: PLC0415 — keep ORM-heavy logic services off the api import path
+ apply_ai_run_defaults,
+ )
+
+ updated = dict(data)
+ apply_ai_run_defaults(updated, team_id, acting_user_id)
+ return updated
+
+
def _find_idling_warm_run(
team_id: int,
user_id: int | None,
@@ -6515,6 +6552,17 @@ def warm_task_sandbox(
if custom_image is None or not custom_image.is_ready:
return None
+ # Resolve team/user defaults up front so the warm run is provisioned (and later
+ # matched) on the runtime the activating submit will effectively request.
+ warm_selection = _with_ai_run_defaults(
+ {"runtime_adapter": runtime_adapter, "model": model, "reasoning_effort": reasoning_effort},
+ team_id=team_id,
+ acting_user_id=user_id,
+ )
+ runtime_adapter = warm_selection.get("runtime_adapter")
+ model = warm_selection.get("model")
+ reasoning_effort = warm_selection.get("reasoning_effort")
+
existing = _find_idling_warm_run(
team_id,
user_id,
@@ -6824,6 +6872,17 @@ def run_task(
team_id, task.repositories[0] if task.repositories else task.repository
)
+ if not resume_from_run_id:
+ # Fill team/user default AI run preferences before warm matching: a warm run
+ # provisioned under the default triple must still match a submit that pinned
+ # nothing. Resumes instead carry the previous run's selection (below).
+ validated_data = _with_ai_run_defaults(
+ validated_data,
+ team_id=task.team_id,
+ acting_user_id=user_id if user_id is not None else task.created_by_id,
+ internal=task.internal,
+ )
+
warm_run = _idling_warm_run_for_task(task)
if warm_run is not None:
warm_state = warm_run.state or {}
@@ -7144,7 +7203,7 @@ def run_task(
logger.info("Creating task run for task %s with mode=%s, branch=%s", task.id, mode, branch)
try:
with transaction.atomic():
- task_run = task.create_run(mode=mode, branch=branch, extra_state=extra_state)
+ task_run = task.create_run(mode=mode, branch=branch, extra_state=extra_state, acting_user_id=user_id)
if report_id_for_slot_check is not None:
enforce_report_implementation_rerun_cap(
team_id=team_id, report_id=report_id_for_slot_check, task_id=str(task.id)
diff --git a/products/tasks/backend/logic/services/ai_run_defaults.py b/products/tasks/backend/logic/services/ai_run_defaults.py
new file mode 100644
index 000000000000..465076326d0b
--- /dev/null
+++ b/products/tasks/backend/logic/services/ai_run_defaults.py
@@ -0,0 +1,336 @@
+"""Central AI run defaults for task runs.
+
+Resolves the effective `(runtime_adapter, model, reasoning_effort)` triple for a
+new task run from, in order: explicit per-run values, the acting user's
+per-project preference (`UserTasksConfig`), and the project default
+(`TeamTasksConfig`). Surfaces with their own preference layer (e.g. the Slack
+app's per-workspace/per-user settings) resolve first and pass the result as
+explicit values, which naturally places them above the central preferences.
+
+Resolution is a whole-triple swap, not a field-by-field merge: if a level
+carries the atomic `(runtime_adapter, model)` pair, that level's entire
+preference object wins (including its absent `reasoning_effort`). A
+field-by-field merge would blend mismatched configurations — for example a
+team `reasoning_effort` glued onto the user's non-thinking model — which is
+never what anyone picked. Mirrors the Slack app's `resolve_ai_preferences`.
+
+Lenient at resolve time by design: preferences are stored as raw ids and the
+available model list drifts as the LLM gateway evolves, so an unknown model id
+passes through (the agent server owns the final fallback), a triple whose
+runtime adapter is no longer valid is skipped in favor of the next level, and
+a reasoning effort the resolved model doesn't support is dropped. This module
+never raises during resolution. The one hard gate is entitlement: a level whose
+model is behind an access flag the acting user doesn't hold is skipped, so a
+stored default can never launch a model the run paths would refuse.
+"""
+
+from dataclasses import dataclass
+from typing import Any, Literal
+
+from django.core.exceptions import ValidationError
+
+from posthog.models.scoping import get_current_team_id
+from posthog.models.scoping.manager import resolve_effective_team_id
+from posthog.models.team.extensions import get_or_create_team_extension
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.tasks.backend.feature_flags import get_model_access_error, get_required_model_flag
+from products.tasks.backend.logic.services.model_catalogue import filter_unsupported_effort
+from products.tasks.backend.models import TeamTasksConfig, UserTasksConfig
+from products.tasks.backend.temporal.process_task.utils import (
+ PUBLIC_REASONING_EFFORTS,
+ RuntimeAdapter,
+ validate_model_selection,
+)
+
+
+@dataclass(frozen=True)
+class ResolvedAIRunConfig:
+ """The effective AI run triple plus which preference level supplied it."""
+
+ runtime_adapter: str | None = None
+ model: str | None = None
+ reasoning_effort: str | None = None
+ source: Literal["explicit", "user", "team", "none"] = "none"
+
+
+def resolve_ai_run_selection(
+ team_id: int,
+ user_id: int | None,
+ *,
+ runtime_adapter: str | None = None,
+ model: str | None = None,
+ reasoning_effort: str | None = None,
+) -> ResolvedAIRunConfig:
+ """The effective runtime selection for a new run: the caller's own selection when it
+ pins anything, otherwise the stored defaults.
+
+ A partial pin (either `runtime_adapter` or `model` alone) is treated as explicit and
+ returned untouched — filling in the other half from a preference would pair values
+ the caller never chose together. When defaults apply, an explicitly passed
+ `reasoning_effort` survives and the default triple's effort only fills a gap.
+ """
+ if runtime_adapter or model:
+ return ResolvedAIRunConfig(
+ runtime_adapter=runtime_adapter,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ source="explicit",
+ )
+
+ resolved = resolve_ai_run_defaults(team_id, user_id)
+ if not (resolved.runtime_adapter and resolved.model):
+ return ResolvedAIRunConfig(reasoning_effort=reasoning_effort, source="none")
+ return ResolvedAIRunConfig(
+ runtime_adapter=resolved.runtime_adapter,
+ model=resolved.model,
+ reasoning_effort=reasoning_effort or resolved.reasoning_effort,
+ source=resolved.source,
+ )
+
+
+def _canonical_team_id(team_id: int) -> int:
+ """`team_id` normalized to its project root, without a query when the caller's
+ scope already answers it.
+
+ The request/activity scope holds a canonical id, so an id equal to it is itself
+ canonical and the `posthog_team` lookup is pure overhead — worth skipping on a
+ path that runs for every task-run creation.
+ """
+ if get_current_team_id() == team_id:
+ return team_id
+ return resolve_effective_team_id(team_id)
+
+
+def apply_ai_run_defaults(selection: dict, team_id: int, user_id: int | None) -> ResolvedAIRunConfig | None:
+ """Fill `selection`'s `(runtime_adapter, model, reasoning_effort)` keys in place from
+ the stored defaults, returning the config that applied — or `None` when the caller
+ pinned a selection or no level has one, leaving `selection` untouched.
+
+ The one place the injection rule lives. Callers that resolve early (warm-run matching
+ compares post-defaults triples) and `Task.create_run` as the safety net must agree
+ byte for byte, or a warm run stops matching the submit that activates it.
+ """
+ resolved = resolve_ai_run_selection(
+ team_id,
+ user_id,
+ runtime_adapter=selection.get("runtime_adapter"),
+ model=selection.get("model"),
+ reasoning_effort=selection.get("reasoning_effort"),
+ )
+ if resolved.source not in ("user", "team"):
+ return None
+ selection["runtime_adapter"] = resolved.runtime_adapter
+ selection["model"] = resolved.model
+ if resolved.reasoning_effort:
+ selection["reasoning_effort"] = resolved.reasoning_effort
+ return resolved
+
+
+def resolve_ai_run_defaults(
+ team_id: int, user_id: int | None, *, user_preferences: dict[str, Any] | None = None
+) -> ResolvedAIRunConfig:
+ """The stored default AI run triple: the acting user's per-project preference wins
+ wholesale, then the project default, then empty.
+
+ Callers holding the user's stored payload already (the `@me` config endpoint reads
+ it to echo back) pass it as `user_preferences` to skip re-reading the same row.
+ """
+ canonical_team_id = _canonical_team_id(team_id)
+
+ # Entitlement gating is lazy: the distinct_id lookup only happens when a level
+ # actually resolves to a flag-gated model, which keeps the per-run-creation
+ # hot path free of an extra query in the common case.
+ acting_distinct_id: str | None = None
+ acting_distinct_id_loaded = False
+
+ def _model_accessible(model: str | None) -> bool:
+ if get_required_model_flag(model) is None:
+ return True
+ nonlocal acting_distinct_id, acting_distinct_id_loaded
+ if not acting_distinct_id_loaded:
+ acting_distinct_id_loaded = True
+ if user_id is not None:
+ acting_distinct_id = User.objects.filter(id=user_id).values_list("distinct_id", flat=True).first()
+ return get_model_access_error(model, distinct_id=acting_distinct_id) is None
+
+ if user_preferences is None and user_id is not None:
+ user_preferences = (
+ UserTasksConfig.objects.for_team(canonical_team_id, canonical=True)
+ .filter(user_id=user_id)
+ .values_list("ai_run_preferences", flat=True)
+ .first()
+ )
+ resolved = _resolve_from_preferences(user_preferences, source="user")
+ # A default naming a model the acting user isn't entitled to falls through to
+ # the next level, the same way an unusable pair does — a stored default must
+ # never launch a model the cold run path would have refused.
+ if resolved is not None and _model_accessible(resolved.model):
+ return resolved
+
+ team_prefs = (
+ TeamTasksConfig.objects.filter(team_id=canonical_team_id).values_list("ai_run_preferences", flat=True).first()
+ )
+ resolved = _resolve_from_preferences(team_prefs, source="team")
+ if resolved is not None and _model_accessible(resolved.model):
+ return resolved
+
+ return ResolvedAIRunConfig(source="none")
+
+
+def _resolve_from_preferences(
+ preferences: dict[str, Any] | None, *, source: Literal["user", "team"]
+) -> ResolvedAIRunConfig | None:
+ """A `ResolvedAIRunConfig` from a stored preference payload, or `None` when the
+ payload carries no usable `(runtime_adapter, model)` pair (fall through to the
+ next level)."""
+ prefs = preferences or {}
+ runtime_adapter = prefs.get("runtime_adapter") or None
+ model = prefs.get("model") or None
+ reasoning_effort = prefs.get("reasoning_effort") or None
+
+ if not (runtime_adapter and model):
+ return None
+ # A stored adapter the registry no longer knows can't pick a harness; skip the level.
+ if runtime_adapter not in {a.value for a in RuntimeAdapter}:
+ return None
+ if reasoning_effort is not None:
+ reasoning_effort = filter_unsupported_effort(runtime_adapter, model, reasoning_effort)
+
+ return ResolvedAIRunConfig(
+ runtime_adapter=runtime_adapter,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ source=source,
+ )
+
+
+def validate_ai_run_preferences(
+ runtime_adapter: str | None,
+ model: str | None,
+ reasoning_effort: str | None,
+) -> None:
+ """Validate the `(runtime_adapter, model, reasoning_effort)` triple on the write
+ path so half-set rows never reach the DB.
+
+ The storage rule — both halves of the pair or neither — lives here; whether the
+ three values may be used together is the model catalogue's call, so that part
+ defers to `validate_model_selection`. Deliberately not strict on model-id
+ membership: the gateway's model list drifts, and resolution handles stale ids
+ leniently.
+
+ Raises `django.core.exceptions.ValidationError` on inconsistency.
+ """
+ if (runtime_adapter is None) != (model is None):
+ raise ValidationError(
+ "runtime_adapter and model must be set together — set both to configure a default, or both to null to clear it."
+ )
+
+ # The catalogue only judges an effort against a model, so an effort stored without a
+ # pair — legal, and inherited by whatever model resolves later — still needs a check.
+ if reasoning_effort is not None:
+ valid_efforts = {e.value for e in PUBLIC_REASONING_EFFORTS}
+ if reasoning_effort not in valid_efforts:
+ raise ValidationError(
+ f"Unknown reasoning_effort '{reasoning_effort}'. Valid: {', '.join(sorted(valid_efforts))}."
+ )
+
+ validate_model_selection(runtime_adapter, model, reasoning_effort)
+
+
+def build_ai_run_preferences_payload(
+ runtime_adapter: str | None,
+ model: str | None,
+ reasoning_effort: str | None,
+) -> dict[str, str]:
+ """Pack the triple into the JSON shape stored on `ai_run_preferences`.
+
+ Drops keys whose value is falsy so a cleared preference is stored as an
+ empty object rather than a triple of nulls.
+ """
+ payload = {
+ "runtime_adapter": runtime_adapter,
+ "model": model,
+ "reasoning_effort": reasoning_effort,
+ }
+ return {k: v for k, v in payload.items() if v}
+
+
+def get_team_ai_run_preferences(team_id: int) -> dict[str, str]:
+ """The stored team-level preference payload ({} when unset)."""
+ prefs = (
+ TeamTasksConfig.objects.filter(team_id=_canonical_team_id(team_id))
+ .values_list("ai_run_preferences", flat=True)
+ .first()
+ )
+ return dict(prefs or {})
+
+
+def update_team_ai_run_preferences(
+ team_id: int,
+ *,
+ runtime_adapter: str | None,
+ model: str | None,
+ reasoning_effort: str | None,
+) -> dict[str, str]:
+ """Validate and store the team-level preference triple; returns the stored payload.
+
+ Raises `django.core.exceptions.ValidationError` on an inconsistent triple.
+ """
+ validate_ai_run_preferences(runtime_adapter, model, reasoning_effort)
+ payload = build_ai_run_preferences_payload(runtime_adapter, model, reasoning_effort)
+ team = Team.objects.get(id=_canonical_team_id(team_id))
+ config = get_or_create_team_extension(team, TeamTasksConfig)
+ config.ai_run_preferences = payload
+ config.save(update_fields=["ai_run_preferences", "updated_at"])
+ return payload
+
+
+def get_user_ai_run_preferences(team_id: int, user_id: int) -> dict[str, str]:
+ """The stored per-(user, project) preference payload ({} when unset)."""
+ canonical_team_id = _canonical_team_id(team_id)
+ prefs = (
+ UserTasksConfig.objects.for_team(canonical_team_id, canonical=True)
+ .filter(user_id=user_id)
+ .values_list("ai_run_preferences", flat=True)
+ .first()
+ )
+ return dict(prefs or {})
+
+
+def update_user_ai_run_preferences(
+ team_id: int,
+ user_id: int,
+ *,
+ runtime_adapter: str | None,
+ model: str | None,
+ reasoning_effort: str | None,
+) -> dict[str, str]:
+ """Validate and upsert the per-(user, project) preference triple; returns the stored
+ payload. Raises `django.core.exceptions.ValidationError` on an inconsistent triple.
+ """
+ validate_ai_run_preferences(runtime_adapter, model, reasoning_effort)
+ payload = build_ai_run_preferences_payload(runtime_adapter, model, reasoning_effort)
+ canonical_team_id = _canonical_team_id(team_id)
+ # team_id repeated in the lookup kwargs: for_team() only filters reads — creation
+ # needs the value passed explicitly.
+ UserTasksConfig.objects.for_team(canonical_team_id, canonical=True).update_or_create(
+ team_id=canonical_team_id,
+ user_id=user_id,
+ defaults={"ai_run_preferences": payload},
+ )
+ return payload
+
+
+__all__ = [
+ "ResolvedAIRunConfig",
+ "build_ai_run_preferences_payload",
+ "get_team_ai_run_preferences",
+ "get_user_ai_run_preferences",
+ "resolve_ai_run_defaults",
+ "resolve_ai_run_selection",
+ "update_team_ai_run_preferences",
+ "update_user_ai_run_preferences",
+ "validate_ai_run_preferences",
+]
diff --git a/products/tasks/backend/migrations/0115_teamtasksconfig_usertasksconfig.py b/products/tasks/backend/migrations/0115_teamtasksconfig_usertasksconfig.py
new file mode 100644
index 000000000000..10e686a2e14d
--- /dev/null
+++ b/products/tasks/backend/migrations/0115_teamtasksconfig_usertasksconfig.py
@@ -0,0 +1,80 @@
+# Generated by Django 5.2.14 on 2026-07-14 10:16
+
+import uuid
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1253_oauth_application_github_grants_rate_limit"),
+ ("tasks", "0114_taskrun_autovacuum_scale_factor"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="TeamTasksConfig",
+ fields=[
+ (
+ "team",
+ models.OneToOneField(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ primary_key=True,
+ related_name="+",
+ serialize=False,
+ to="posthog.team",
+ ),
+ ),
+ ("ai_run_preferences", models.JSONField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ],
+ ),
+ migrations.CreateModel(
+ name="UserTasksConfig",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=uuid.uuid4,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("ai_run_preferences", models.JSONField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("team", "user"),
+ name="user_tasks_config_team_user_unique",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 675d75f7fb67..3ca5fc13a057 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0114_taskrun_autovacuum_scale_factor
+0115_teamtasksconfig_usertasksconfig
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index fb0db4fc410a..cfe87e738dee 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -33,6 +33,7 @@ from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.github_integration_base import INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY
from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.team.extensions import register_team_extension_signal
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.models.utils import DeletedMetaFields, UUIDModel
@@ -634,12 +635,64 @@ class Task(DeletedMetaFields, models.Model):
def ownership_version(self) -> str | None:
return _task_ownership_version(self.state)
+ def _apply_ai_run_defaults(self, state: dict, acting_user_id: int | None) -> None:
+ """Fill the run state's AI runtime selection from the acting user's / team's
+ default preferences when the caller pinned none.
+
+ A partially pinned selection (either `runtime_adapter` or `model` present) is
+ treated as explicit and left untouched — overwriting half a pin would replace a
+ value the caller chose. Internal tasks (custom-prompt infra agents) and
+ Pi-runtime tasks keep their pinned behavior and never inherit preferences — the
+ defaults describe the claude/codex ACP harness, which a Pi run doesn't use. An
+ explicitly set `reasoning_effort` survives injection; the default triple's effort
+ only fills a gap.
+ """
+ if self.internal or self.runtime == Task.Runtime.PI:
+ return
+
+ from products.tasks.backend.logic.services.ai_run_defaults import ( # noqa: PLC0415 — breaks the circular import with ai_run_defaults, which imports this module
+ apply_ai_run_defaults,
+ )
+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keeps temporalio off the import path (matches _build_task)
+ RuntimeAdapter,
+ apply_runtime_adapter_run_state,
+ clamp_initial_permission_mode,
+ )
+
+ resolved = apply_ai_run_defaults(state, self.team_id, acting_user_id or self.created_by_id)
+ if resolved is None:
+ # Nothing resolved here, but the mode may still be paired with a runtime the
+ # serializer never saw together: the facade materializes the default into the
+ # state before this runs (warm matching resolves early), and with no adapter
+ # at all the run launches on the sandbox fallback, which reads an unset
+ # adapter as claude. Clamp against that effective adapter so a mode named in
+ # the other runtime's vocabulary can't persist against a run that won't
+ # honor it. For an explicitly pinned adapter the serializer already paired
+ # the two, so this is a no-op.
+ effective_adapter = state.get("runtime_adapter") or RuntimeAdapter.CLAUDE.value
+ permission_mode = clamp_initial_permission_mode(
+ effective_adapter, state.get("initial_permission_mode") or None
+ )
+ if permission_mode:
+ state["initial_permission_mode"] = permission_mode
+ return
+
+ permission_mode = apply_runtime_adapter_run_state(
+ state,
+ resolved.runtime_adapter,
+ initial_permission_mode=state.get("initial_permission_mode") or None,
+ )
+ if permission_mode:
+ state["initial_permission_mode"] = permission_mode
+ state["ai_defaults_source"] = resolved.source
+
def create_run(
self,
environment: Optional["TaskRun.Environment"] = None,
mode: str = "background",
extra_state: dict | None = None,
branch: str | None = None,
+ acting_user_id: int | None = None,
) -> "TaskRun":
expected_created_by_id = self.created_by_id
expected_ownership_version = self.ownership_version
@@ -679,6 +732,9 @@ class Task(DeletedMetaFields, models.Model):
previous_snapshot = previous.state.get("config_snapshot") if previous else None
if previous_snapshot:
state["config_snapshot"] = previous_snapshot
+ # Every run creation flows through here, so this is where team/user default AI run
+ # preferences apply when the caller didn't pin a runtime selection.
+ task._apply_ai_run_defaults(state, acting_user_id)
if task.ownership_version is not None:
state[TASK_OWNERSHIP_VERSION_STATE_KEY] = task.ownership_version
@@ -862,9 +918,8 @@ class Task(DeletedMetaFields, models.Model):
from products.tasks.backend.temporal.process_task.utils import (
PrAuthorshipMode,
RunSource,
- RuntimeAdapter,
+ apply_runtime_adapter_run_state,
get_pr_authorship_mode,
- get_provider_for_runtime_adapter,
resolve_user_github_integration_for_task,
user_github_integration_is_usable,
)
@@ -1009,11 +1064,9 @@ class Task(DeletedMetaFields, models.Model):
# default permission mode to `auto` so a headless run doesn't stall on a prompt.
if runtime_adapter:
extra_state["runtime_adapter"] = runtime_adapter
- provider = get_provider_for_runtime_adapter(runtime_adapter)
- if provider is not None:
- extra_state["provider"] = provider.value
- if initial_permission_mode is None and runtime_adapter == RuntimeAdapter.CODEX.value:
- initial_permission_mode = "auto"
+ initial_permission_mode = apply_runtime_adapter_run_state(
+ extra_state, runtime_adapter, initial_permission_mode=initial_permission_mode
+ )
if reasoning_effort:
extra_state["reasoning_effort"] = reasoning_effort
@@ -1250,7 +1303,9 @@ class Task(DeletedMetaFields, models.Model):
}
with transaction.atomic():
- task_run = task.create_run(mode=mode, extra_state=run_extra_state or None, branch=branch)
+ task_run = task.create_run(
+ mode=mode, extra_state=run_extra_state or None, branch=branch, acting_user_id=user_id
+ )
if start_workflow:
# Defer the fire-and-forget workflow start until the creating transaction commits.
@@ -3744,6 +3799,54 @@ def bump_task_activity_on_run(sender, instance: TaskRun, created: bool, update_f
bump_task_activity(team_id=instance.team_id, task_id=instance.task_id, at=django_timezone.now())
+class TeamTasksConfig(models.Model):
+ """Team-level tasks settings (Team extension model, singleton per team).
+
+ Read at run creation time to fill in AI run defaults when a run is created
+ without an explicit runtime selection. Rows are keyed on the canonical
+ (project root) team — callers must normalize environment team ids first.
+ """
+
+ # db_constraint=False: adding an FK constraint to the hot posthog_team table takes a
+ # SHARE ROW EXCLUSIVE lock on it; app-level integrity is enough here.
+ team = models.OneToOneField(Team, on_delete=models.CASCADE, primary_key=True, related_name="+", db_constraint=False)
+ # {"runtime_adapter": str, "model": str, "reasoning_effort": str} — keys absent when unset.
+ # Same shape as SlackSettings.ai_preferences; validated as a whole triple on write
+ # (see logic/services/ai_run_defaults.py).
+ ai_run_preferences = models.JSONField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ def __str__(self):
+ return f"TeamTasksConfig(team={self.team_id})"
+
+
+register_team_extension_signal(TeamTasksConfig)
+
+
+class UserTasksConfig(TeamScopedRootMixin):
+ """Per-(user, team) tasks settings; overrides `TeamTasksConfig` wholesale where set."""
+
+ # nosemgrep: prefer-uuid7-django-pk -- mirrors sibling task models in this app
+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
+ # db_constraint=False on the team/user FKs: adding an FK constraint to those hot tables
+ # takes a SHARE ROW EXCLUSIVE lock on them; app-level integrity is enough here.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ # Same shape and validation as TeamTasksConfig.ai_run_preferences.
+ ai_run_preferences = models.JSONField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(fields=["team", "user"], name="user_tasks_config_team_user_unique"),
+ ]
+
+ def __str__(self):
+ return f"UserTasksConfig(team={self.team_id}, user={self.user_id})"
+
+
@receiver(post_save, sender=TaskRun)
def track_task_run_completion(sender, instance: TaskRun, created: bool, **kwargs):
try:
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index ae72bb1c07ae..cf3382cf4b2d 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -12,7 +12,7 @@ from django.utils import timezone as django_timezone
import posthoganalytics
from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field
+from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field, extend_schema_serializer
from rest_framework import serializers
from rest_framework_dataclasses.serializers import DataclassSerializer
@@ -349,8 +349,11 @@ def get_initial_permission_mode_error(initial_permission_mode: str | None, runti
"""
if initial_permission_mode is None:
return None
+ # With no runtime pinned the mode rides along and is clamped to whichever runtime the
+ # stored defaults resolve to at run creation — requiring the adapter here would force
+ # composers to pin the model just to state a mode, blocking server-side default resolution.
if runtime_adapter is None:
- return "This field requires runtime_adapter to be set."
+ return None
allowed_permission_modes = (
list(CODEX_INITIAL_PERMISSION_MODE_CHOICES)
if runtime_adapter == RuntimeAdapter.CODEX.value
@@ -4315,3 +4318,85 @@ class AgentProxyCallbackResponseSerializer(serializers.Serializer):
dispatched = serializers.BooleanField(
help_text="True when the requested side effect was dispatched; false when skipped (e.g. run not found)."
)
+
+
+class TasksAIRunPreferencesSerializer(serializers.Serializer):
+ """The default AI run triple stored at team or user level.
+
+ Write payload for the tasks config endpoints and the `ai_run_preferences` block of
+ their responses. `runtime_adapter` and `model` must be set together; send all three
+ as null to clear a stored preference.
+ """
+
+ RUNTIME_ADAPTER_CHOICES = [adapter.value for adapter in RuntimeAdapter]
+ REASONING_EFFORT_CHOICES = [effort.value for effort in PUBLIC_REASONING_EFFORTS]
+
+ runtime_adapter = serializers.ChoiceField(
+ choices=RUNTIME_ADAPTER_CHOICES,
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text=(
+ "Default agent runtime adapter for new task runs. Use 'claude' for the Claude "
+ "runtime or 'codex' for the Codex runtime. Must be set together with `model`."
+ ),
+ )
+ model = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=False,
+ default=None,
+ help_text="Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`.",
+ )
+ reasoning_effort = serializers.ChoiceField(
+ choices=REASONING_EFFORT_CHOICES,
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text="Default reasoning effort for models that expose an effort control.",
+ )
+
+
+class TasksResolvedAIRunDefaultsSerializer(serializers.Serializer):
+ """The AI run triple a new run will effectively use when the caller pins nothing,
+ plus which preference level supplied it."""
+
+ # Not bound to `ResolvedAIRunConfig` via DataclassSerializer: that dataclass also carries the
+ # internal `explicit` resolution state this endpoint never returns, and its per-field defaults
+ # would mark every field optional when the response always sends all four.
+ runtime_adapter = serializers.CharField(
+ allow_null=True, help_text="Effective default runtime adapter, or null when no preference is stored."
+ )
+ model = serializers.CharField(
+ allow_null=True, help_text="Effective default model identifier, or null when no preference is stored."
+ )
+ reasoning_effort = serializers.CharField(
+ allow_null=True, help_text="Effective default reasoning effort, or null when unset or unsupported."
+ )
+ # `Field.source` exists on the base class, but the serializer metaclass pops declared fields off the
+ # class body before it ever binds, so there is no shadowing at runtime — only mypy sees a clash.
+ source = serializers.ChoiceField( # type: ignore[assignment]
+ choices=["user", "team", "none"],
+ help_text="Preference level that supplied the default: the caller's own per-project preference ('user'), the project default ('team'), or 'none'.",
+ )
+
+
+@extend_schema_serializer(many=False)
+class TasksTeamConfigResponseSerializer(serializers.Serializer):
+ """Team-level tasks configuration."""
+
+ ai_run_preferences = TasksAIRunPreferencesSerializer(
+ help_text="Project-wide default AI run triple; all fields null when unset."
+ )
+
+
+@extend_schema_serializer(many=False)
+class TasksUserConfigResponseSerializer(serializers.Serializer):
+ """The requesting user's per-project tasks configuration."""
+
+ ai_run_preferences = TasksAIRunPreferencesSerializer(
+ help_text="The requesting user's per-project default AI run triple; all fields null when unset."
+ )
+ resolved_ai_run_defaults = TasksResolvedAIRunDefaultsSerializer(
+ help_text="The defaults a new run will use when no explicit runtime selection is sent."
+ )
diff --git a/products/tasks/backend/presentation/views/config_api.py b/products/tasks/backend/presentation/views/config_api.py
new file mode 100644
index 000000000000..ea5eb99feb5c
--- /dev/null
+++ b/products/tasks/backend/presentation/views/config_api.py
@@ -0,0 +1,138 @@
+from dataclasses import asdict
+from typing import cast
+
+from django.core.exceptions import ValidationError as DjangoValidationError
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import viewsets
+from rest_framework.authentication import SessionAuthentication
+from rest_framework.exceptions import ValidationError
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
+from posthog.models.user import User
+from posthog.permissions import APIScopePermission, TeamMemberStrictManagementPermission
+
+from products.tasks.backend.facade import ai_run_defaults
+from products.tasks.backend.facade.run_config import get_model_access_error
+from products.tasks.backend.presentation.serializers import (
+ TasksAIRunPreferencesSerializer,
+ TasksTeamConfigResponseSerializer,
+ TasksUserConfigResponseSerializer,
+)
+
+_AUTH_CLASSES = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+
+
+def _user_id(request: Request) -> int:
+ """The requesting user's id; `IsAuthenticated` guarantees a real user on these views."""
+ return cast(User, request.user).id
+
+
+def _validated_triple(request: Request) -> dict:
+ serializer = TasksAIRunPreferencesSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ triple = serializer.validated_data
+ # Storing a flag-gated model the writer isn't entitled to would only ever
+ # produce runs the resolver skips or the run paths refuse — reject it here
+ # so the settings page says so immediately. Resolution re-checks per acting
+ # user, which also covers entitlements that change after the write.
+ error = get_model_access_error(triple.get("model"), distinct_id=cast(User, request.user).distinct_id)
+ if error is not None:
+ raise ValidationError({"model": error})
+ return triple
+
+
+class TasksTeamConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """Team-level tasks configuration (singleton per project).
+
+ GET /tasks/config/ → retrieve
+ POST /tasks/config/ → update
+ """
+
+ scope_object = "task"
+ authentication_classes = _AUTH_CLASSES
+ # One value that decides what every unpinned run on the project launches with, so writing it is
+ # admin-only; reading stays open to members, who need it to see what they're inheriting.
+ permission_classes = [IsAuthenticated, APIScopePermission, TeamMemberStrictManagementPermission]
+ serializer_class = TasksTeamConfigResponseSerializer
+
+ @extend_schema(
+ responses={200: TasksTeamConfigResponseSerializer},
+ description="Retrieve the project-wide default AI run preferences for task runs.",
+ )
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ preferences = ai_run_defaults.get_team_ai_run_preferences(self.team_id)
+ return Response(TasksTeamConfigResponseSerializer({"ai_run_preferences": preferences}).data)
+
+ @extend_schema(
+ request=TasksAIRunPreferencesSerializer,
+ responses={200: TasksTeamConfigResponseSerializer},
+ description=(
+ "Set the project-wide default AI run preferences applied to task runs created "
+ "without an explicit runtime selection. Send all fields as null to clear."
+ ),
+ )
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ triple = _validated_triple(request)
+ try:
+ payload = ai_run_defaults.update_team_ai_run_preferences(self.team_id, **triple)
+ except DjangoValidationError as e:
+ raise ValidationError(e.messages)
+ return Response(TasksTeamConfigResponseSerializer({"ai_run_preferences": payload}).data)
+
+
+class TasksUserConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """The requesting user's per-project tasks configuration.
+
+ GET /tasks/my_config/ → retrieve (includes the resolved effective defaults)
+ POST /tasks/my_config/ → update
+ """
+
+ scope_object = "task"
+ authentication_classes = _AUTH_CLASSES
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ serializer_class = TasksUserConfigResponseSerializer
+
+ def _response(self, request: Request, preferences: dict) -> Response:
+ resolved = ai_run_defaults.resolve_ai_run_defaults(
+ self.team_id, _user_id(request), user_preferences=preferences
+ )
+ return Response(
+ TasksUserConfigResponseSerializer(
+ {"ai_run_preferences": preferences, "resolved_ai_run_defaults": asdict(resolved)}
+ ).data
+ )
+
+ @extend_schema(
+ # `@me` is not identifier-safe, so the URL-derived default operationId is rejected.
+ operation_id="tasks_me_config_list",
+ responses={200: TasksUserConfigResponseSerializer},
+ description=(
+ "Retrieve your per-project default AI run preferences, plus the resolved defaults "
+ "a new run will use when no explicit runtime selection is sent (your preference "
+ "over the project default)."
+ ),
+ )
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ return self._response(request, ai_run_defaults.get_user_ai_run_preferences(self.team_id, _user_id(request)))
+
+ @extend_schema(
+ operation_id="tasks_me_config_create",
+ request=TasksAIRunPreferencesSerializer,
+ responses={200: TasksUserConfigResponseSerializer},
+ description=(
+ "Set your per-project default AI run preferences; they override the project default "
+ "wholesale. Send all fields as null to clear and inherit the project default."
+ ),
+ )
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ triple = _validated_triple(request)
+ try:
+ payload = ai_run_defaults.update_user_ai_run_preferences(self.team_id, _user_id(request), **triple)
+ except DjangoValidationError as e:
+ raise ValidationError(e.messages)
+ return self._response(request, payload)
diff --git a/products/tasks/backend/routes.py b/products/tasks/backend/routes.py
index 0ceb2e1059c0..8e961a470a10 100644
--- a/products/tasks/backend/routes.py
+++ b/products/tasks/backend/routes.py
@@ -4,6 +4,7 @@ import products.tasks.backend.presentation.views.api as tasks
import products.tasks.backend.presentation.views.loops as loops
import products.tasks.backend.presentation.views.desktop as desktop
import products.tasks.backend.presentation.views.seat_api as seats
+import products.tasks.backend.presentation.views.config_api as config
import products.tasks.backend.presentation.views.channels_api as channels
import products.tasks.backend.presentation.views.desktop_access as desktop_access
import products.tasks.backend.presentation.views.task_usage_api as task_usage
@@ -11,6 +12,8 @@ import products.tasks.backend.presentation.views.sandbox_pricing_api as sandbox_
def register_routes(routers: RouterRegistry) -> None:
+ # Static `tasks/...` prefixes are registered before the `tasks` viewset so they can't be
+ # swallowed by its `tasks/{pk}` detail pattern.
routers.organizations.register(
r"desktop_beta_terms",
desktop.DesktopBetaTermsViewSet,
@@ -18,6 +21,10 @@ def register_routes(routers: RouterRegistry) -> None:
["organization_id"],
)
routers.projects.register(r"desktop", desktop_access.DesktopAccessViewSet, "project_desktop", ["team_id"])
+ routers.projects.register(r"tasks/config", config.TasksTeamConfigViewSet, "project_tasks_config", ["team_id"])
+ routers.projects.register(
+ r"tasks/@me/config", config.TasksUserConfigViewSet, "project_tasks_me_config", ["team_id"]
+ )
project_tasks_router = routers.projects.register(r"tasks", tasks.TaskViewSet, "project_tasks", ["team_id"])
project_task_runs_router = project_tasks_router.register(
r"runs", tasks.TaskRunViewSet, "project_task_runs", ["team_id", "task_id"]
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 9aad7aea528b..108d11d13261 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -20,7 +20,9 @@ from posthog.temporal.oauth import TOKEN_EXPIRATION_SECONDS, PosthogMcpScopes, h
from products.mcp_store.backend.facade.api import get_installations_for_sandbox
from products.tasks.backend.constants import (
ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS,
+ CODEX_INITIAL_PERMISSION_MODE_CHOICES,
DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,
+ INITIAL_PERMISSION_MODE_CHOICES,
SNAPSHOT_KIND_DIRECTORY,
SNAPSHOT_KIND_FILESYSTEM,
InitialPermissionMode,
@@ -271,6 +273,53 @@ def get_provider_for_runtime_adapter(
return None
+def clamp_initial_permission_mode(
+ runtime_adapter: str | None,
+ initial_permission_mode: str | None,
+) -> str | None:
+ """The permission mode this adapter can launch with.
+
+ A mode the caller already chose is kept when this adapter's vocabulary offers it;
+ one named in the other runtime's terms — the caller may not know which runtime the
+ run resolves to — falls to the adapter's baseline (`auto` for Codex, so a headless
+ run doesn't stall on a prompt; `default` for Claude) rather than failing the run
+ downstream.
+ """
+ if runtime_adapter == RuntimeAdapter.CODEX.value:
+ if initial_permission_mode in CODEX_INITIAL_PERMISSION_MODE_CHOICES:
+ return initial_permission_mode
+ return "auto"
+ if (
+ runtime_adapter == RuntimeAdapter.CLAUDE.value
+ and initial_permission_mode is not None
+ and initial_permission_mode not in INITIAL_PERMISSION_MODE_CHOICES
+ ):
+ return "default"
+ return initial_permission_mode
+
+
+def apply_runtime_adapter_run_state(
+ state: dict,
+ runtime_adapter: str | None,
+ *,
+ initial_permission_mode: str | None,
+) -> str | None:
+ """Write the run-state keys a runtime adapter implies, returning the permission mode
+ to launch with.
+
+ The agent server derives the provider from the adapter, and the mode is clamped to
+ the adapter's vocabulary (see ``clamp_initial_permission_mode``). Shared so the
+ explicitly-pinned and resolved-default paths can't drift on what an adapter implies.
+ """
+ if not runtime_adapter:
+ return initial_permission_mode
+
+ provider = get_provider_for_runtime_adapter(runtime_adapter)
+ if provider is not None:
+ state["provider"] = provider.value
+ return clamp_initial_permission_mode(runtime_adapter, initial_permission_mode)
+
+
def get_supported_reasoning_efforts(
runtime_adapter: RuntimeAdapter | str | None,
model: str | None,
diff --git a/products/tasks/backend/tests/test_ai_run_defaults.py b/products/tasks/backend/tests/test_ai_run_defaults.py
new file mode 100644
index 000000000000..3f06a97e0499
--- /dev/null
+++ b/products/tasks/backend/tests/test_ai_run_defaults.py
@@ -0,0 +1,469 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.models import Integration, Organization, Team, User
+from posthog.models.organization import OrganizationMembership
+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
+from posthog.models.utils import generate_random_token_personal
+
+from products.tasks.backend.facade import api as facade
+from products.tasks.backend.logic.services.ai_run_defaults import (
+ get_team_ai_run_preferences,
+ resolve_ai_run_defaults,
+ resolve_ai_run_selection,
+ update_team_ai_run_preferences,
+ update_user_ai_run_preferences,
+)
+from products.tasks.backend.models import Task, TeamTasksConfig, UserTasksConfig
+from products.tasks.backend.presentation.serializers import TaskRunCreateRequestSerializer
+
+FACADE = "products.tasks.backend.facade.api"
+
+TEAM_TRIPLE = {"runtime_adapter": "claude", "model": "claude-opus-4-8", "reasoning_effort": "high"}
+USER_TRIPLE = {"runtime_adapter": "codex", "model": "gpt-5.5", "reasoning_effort": "medium"}
+
+
+class TestResolveAIRunDefaults(APIBaseTest):
+ def _set_team(self, prefs: dict[str, Any]) -> None:
+ TeamTasksConfig.objects.update_or_create(team=self.team, defaults={"ai_run_preferences": prefs})
+
+ def _set_user(self, prefs: dict[str, Any], user: User | None = None) -> None:
+ UserTasksConfig.objects.for_team(self.team.id).update_or_create(
+ team_id=self.team.id, user_id=(user or self.user).id, defaults={"ai_run_preferences": prefs}
+ )
+
+ def test_no_preferences_resolves_to_none(self):
+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)
+ assert resolved.source == "none"
+ assert resolved.model is None
+
+ def test_team_default_applies_when_user_has_none(self):
+ self._set_team(TEAM_TRIPLE)
+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)
+ assert resolved.source == "team"
+ assert (resolved.runtime_adapter, resolved.model, resolved.reasoning_effort) == (
+ "claude",
+ "claude-opus-4-8",
+ "high",
+ )
+
+ def test_user_triple_replaces_team_triple_wholesale(self):
+ self._set_team(TEAM_TRIPLE)
+ self._set_user({"runtime_adapter": "codex", "model": "gpt-5.5"})
+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)
+ assert resolved.source == "user"
+ # The team's reasoning_effort must not blend into the user's effort-less triple.
+ assert (resolved.runtime_adapter, resolved.model, resolved.reasoning_effort) == ("codex", "gpt-5.5", None)
+
+ @parameterized.expand(
+ [
+ ("empty_payload", {}),
+ ("model_without_adapter", {"model": "claude-opus-4-8"}),
+ ("unknown_adapter", {"runtime_adapter": "gemini", "model": "gemini-3"}),
+ ]
+ )
+ def test_unusable_user_row_falls_through_to_team(self, _name: str, user_prefs: dict[str, Any]):
+ self._set_team(TEAM_TRIPLE)
+ self._set_user(user_prefs)
+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)
+ assert resolved.source == "team"
+ assert resolved.model == "claude-opus-4-8"
+
+ def test_another_users_preference_does_not_leak(self):
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self._set_user(USER_TRIPLE, user=other)
+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)
+ assert resolved.source == "none"
+
+ def test_unsupported_effort_is_dropped_but_model_passes_through(self):
+ # claude-sonnet-4-6 caps at high; a stored max effort must not reach the run.
+ self._set_team({"runtime_adapter": "claude", "model": "claude-sonnet-4-6", "reasoning_effort": "max"})
+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)
+ assert resolved.model == "claude-sonnet-4-6"
+ assert resolved.reasoning_effort is None
+
+ def test_unknown_model_id_passes_through(self):
+ self._set_team({"runtime_adapter": "claude", "model": "claude-galaxy-9"})
+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)
+ assert resolved.source == "team"
+ assert resolved.model == "claude-galaxy-9"
+
+ # Config rows are keyed on the project root team, so an environment team must read and
+ # write the same row as the root — a CRUD path skipping the normalization would silently
+ # fork the project default per environment.
+ def test_environment_team_shares_the_project_root_config(self):
+ env_team = Team.objects.create(
+ organization=self.organization, project=self.project, parent_team=self.team, name="env"
+ )
+ update_team_ai_run_preferences(env_team.id, **TEAM_TRIPLE)
+ assert get_team_ai_run_preferences(self.team.id) == TEAM_TRIPLE
+ resolved = resolve_ai_run_defaults(env_team.id, self.user.id)
+ assert resolved.source == "team"
+ assert resolved.model == "claude-opus-4-8"
+
+ @parameterized.expand(
+ [
+ ("full_pair", "claude", "claude-opus-4-8", None),
+ ("model_only_partial_pin", None, "claude-opus-4-8", None),
+ ("adapter_only_partial_pin", "claude", None, "low"),
+ ]
+ )
+ def test_selection_treats_any_pin_as_explicit(
+ self, _name: str, runtime_adapter: str | None, model: str | None, reasoning_effort: str | None
+ ):
+ self._set_team(TEAM_TRIPLE)
+ selection = resolve_ai_run_selection(
+ self.team.id,
+ self.user.id,
+ runtime_adapter=runtime_adapter,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ )
+ assert selection.source == "explicit"
+ assert (selection.runtime_adapter, selection.model, selection.reasoning_effort) == (
+ runtime_adapter,
+ model,
+ reasoning_effort,
+ )
+
+ def test_selection_preserves_explicit_effort_over_default_triples_effort(self):
+ self._set_team(TEAM_TRIPLE)
+ selection = resolve_ai_run_selection(self.team.id, self.user.id, reasoning_effort="low")
+ assert selection.source == "team"
+ assert (selection.runtime_adapter, selection.model, selection.reasoning_effort) == (
+ "claude",
+ "claude-opus-4-8",
+ "low",
+ )
+
+
+class TestRunCreateSerializerModeWithoutAdapter(APIBaseTest):
+ # A composer that pins nothing must still be able to state the launch mode — the
+ # server resolves the runtime from the stored default and clamps the mode to it.
+ def test_mode_without_adapter_is_accepted(self):
+ serializer = TaskRunCreateRequestSerializer(data={"initial_permission_mode": "plan"})
+ assert serializer.is_valid(), serializer.errors
+
+ def test_mode_outside_the_pinned_adapters_vocabulary_is_still_rejected(self):
+ serializer = TaskRunCreateRequestSerializer(
+ data={"runtime_adapter": "codex", "model": "gpt-5.5", "initial_permission_mode": "acceptEdits"}
+ )
+ assert not serializer.is_valid()
+ assert "initial_permission_mode" in serializer.errors
+
+
+class TestModelAccessGating(APIBaseTest):
+ GATED = "claude-opus-4-8"
+
+ def _set_team(self, prefs: dict[str, Any]) -> None:
+ TeamTasksConfig.objects.update_or_create(team=self.team, defaults={"ai_run_preferences": prefs})
+
+ def _set_user(self, prefs: dict[str, Any]) -> None:
+ UserTasksConfig.objects.for_team(self.team.id).update_or_create(
+ team_id=self.team.id, user_id=self.user.id, defaults={"ai_run_preferences": prefs}
+ )
+
+ def _gate(self, module: str):
+ gated = self.GATED
+ return (
+ patch(
+ f"{module}.get_required_model_flag",
+ side_effect=lambda model: "gated-model-flag" if model == gated else None,
+ ),
+ patch(
+ f"{module}.get_model_access_error",
+ side_effect=lambda model, *, distinct_id: (
+ f"'{model}' is not available for your account." if model == gated else None
+ ),
+ ),
+ )
+
+ RESOLVER = "products.tasks.backend.logic.services.ai_run_defaults"
+
+ def test_gated_user_default_falls_through_to_team(self):
+ self._set_user(TEAM_TRIPLE) # names the gated model
+ self._set_team(USER_TRIPLE)
+ flag_patch, access_patch = self._gate(self.RESOLVER)
+ with flag_patch, access_patch as access_mock:
+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)
+ assert resolved.source == "team"
+ assert resolved.model == "gpt-5.5"
+ access_mock.assert_called_once_with(self.GATED, distinct_id=self.user.distinct_id)
+
+ def test_gated_team_default_resolves_to_none(self):
+ self._set_team(TEAM_TRIPLE)
+ flag_patch, access_patch = self._gate(self.RESOLVER)
+ with flag_patch, access_patch:
+ resolved = resolve_ai_run_defaults(self.team.id, self.user.id)
+ assert resolved.source == "none"
+ assert resolved.model is None
+
+ def test_storing_a_gated_model_as_a_default_is_rejected(self):
+ # The API check calls get_model_access_error directly; no flag patch needed.
+ _, access_patch = self._gate("products.tasks.backend.presentation.views.config_api")
+ with access_patch:
+ response = self.client.post(f"/api/projects/{self.team.id}/tasks/@me/config/", TEAM_TRIPLE)
+ assert response.status_code == 400
+ assert "not available" in str(response.json())
+ response = self.client.post(f"/api/projects/{self.team.id}/tasks/@me/config/", USER_TRIPLE)
+ assert response.status_code == 200
+
+
+class TestCreateRunAppliesDefaults(APIBaseTest):
+ def _task(self, **overrides) -> Task:
+ params: dict[str, Any] = {
+ "team": self.team,
+ "title": "t",
+ "description": "d",
+ "origin_product": Task.OriginProduct.USER_CREATED,
+ "created_by": self.user,
+ }
+ params.update(overrides)
+ return Task.objects.create(**params)
+
+ def test_run_state_carries_default_triple_provider_and_source(self):
+ update_team_ai_run_preferences(self.team.id, **TEAM_TRIPLE)
+ run = self._task().create_run()
+ assert run.state["runtime_adapter"] == "claude"
+ assert run.state["model"] == "claude-opus-4-8"
+ assert run.state["reasoning_effort"] == "high"
+ assert run.state["provider"] == "anthropic"
+ assert run.state["ai_defaults_source"] == "team"
+
+ def test_codex_default_sets_auto_permission_mode(self):
+ update_team_ai_run_preferences(self.team.id, **USER_TRIPLE)
+ run = self._task().create_run()
+ assert run.state["runtime_adapter"] == "codex"
+ assert run.state["initial_permission_mode"] == "auto"
+
+ def test_explicit_selection_is_untouched(self):
+ update_team_ai_run_preferences(self.team.id, **TEAM_TRIPLE)
+ run = self._task().create_run(extra_state={"runtime_adapter": "codex", "model": "gpt-5", "provider": "openai"})
+ assert run.state["model"] == "gpt-5"
+ assert "ai_defaults_source" not in run.state
+
+ def test_internal_task_never_inherits_defaults(self):
+ update_team_ai_run_preferences(self.team.id, **TEAM_TRIPLE)
+ run = self._task(internal=True).create_run()
+ assert "model" not in run.state
+
+ def test_pi_runtime_task_never_inherits_defaults(self):
+ update_team_ai_run_preferences(self.team.id, **TEAM_TRIPLE)
+ run = self._task(runtime=Task.Runtime.PI).create_run()
+ assert "model" not in run.state
+ assert "ai_defaults_source" not in run.state
+
+ # The composer states the launch mode even when it pins no runtime, deferring the
+ # model to the stored default — the mode must then be clamped to whichever
+ # runtime's vocabulary the default resolves to, not fail the run downstream.
+ @parameterized.expand(
+ [
+ ("claude_mode_on_codex_default", USER_TRIPLE, "acceptEdits", "auto"),
+ ("codex_mode_on_claude_default", TEAM_TRIPLE, "read-only", "default"),
+ ("shared_mode_survives", TEAM_TRIPLE, "plan", "plan"),
+ ]
+ )
+ def test_permission_mode_clamps_to_the_resolved_runtime(
+ self, _name: str, default_triple: dict[str, Any], sent_mode: str, expected_mode: str
+ ):
+ update_team_ai_run_preferences(self.team.id, **default_triple)
+ run = self._task().create_run(extra_state={"initial_permission_mode": sent_mode})
+ assert run.state["initial_permission_mode"] == expected_mode
+
+ def test_acting_user_preference_wins_over_task_creators(self):
+ update_user_ai_run_preferences(self.team.id, self.user.id, **TEAM_TRIPLE)
+ actor = User.objects.create_and_join(self.organization, "[email protected]", None)
+ update_user_ai_run_preferences(self.team.id, actor.id, **USER_TRIPLE)
+ run = self._task().create_run(acting_user_id=actor.id)
+ assert run.state["model"] == "gpt-5.5"
+ assert run.state["ai_defaults_source"] == "user"
+
+
+class TestRunTaskWarmMatchingUnderDefaults(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.integration = Integration.objects.create(team=self.team, kind="github", config={})
+
+ def test_default_carrying_warm_run_is_activated_by_a_pinless_submit(self):
+ update_team_ai_run_preferences(self.team.id, **TEAM_TRIPLE)
+ task = Task.objects.create(
+ team=self.team,
+ title="",
+ description="",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ created_by=self.user,
+ repository="posthog/posthog",
+ github_integration=self.integration,
+ )
+ warm_run = task.create_run(
+ mode="interactive", extra_state={"await_user_message": True, "branch": "main"}, branch="main"
+ )
+ assert warm_run.state["model"] == "claude-opus-4-8"
+
+ with patch(f"{FACADE}.signal_task_run_user_message", return_value=True):
+ result = facade.run_task(
+ task.id,
+ self.team.id,
+ self.user.id,
+ validated_data={"mode": "interactive", "branch": "main", "pending_user_message": "go"},
+ )
+
+ assert result is not None and result.error is None
+ assert task.runs.count() == 1
+ warm_run.refresh_from_db()
+ assert "await_user_message" not in warm_run.state
+
+
+class TestTasksConfigAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ def test_team_config_round_trip(self):
+ response = self.client.get(f"/api/projects/{self.team.id}/tasks/config/")
+ assert response.status_code == 200
+ assert response.json() == {
+ "ai_run_preferences": {"runtime_adapter": None, "model": None, "reasoning_effort": None}
+ }
+
+ response = self.client.post(f"/api/projects/{self.team.id}/tasks/config/", TEAM_TRIPLE)
+ assert response.status_code == 200
+ assert response.json()["ai_run_preferences"] == TEAM_TRIPLE
+
+ response = self.client.get(f"/api/projects/{self.team.id}/tasks/config/")
+ assert response.json()["ai_run_preferences"] == TEAM_TRIPLE
+
+ @parameterized.expand(
+ [
+ ("model_without_adapter", {"model": "claude-opus-4-8"}),
+ ("unknown_effort", {"reasoning_effort": "extreme"}),
+ ("unknown_adapter", {"runtime_adapter": "gemini", "model": "gemini-3"}),
+ (
+ "unsupported_effort",
+ {"runtime_adapter": "claude", "model": "claude-sonnet-4-6", "reasoning_effort": "max"},
+ ),
+ ]
+ )
+ def test_invalid_triples_are_rejected(self, _name: str, payload: dict[str, Any]):
+ # Both endpoints share the validation path; asserting both keeps either from losing it.
+ for path in ("config", "@me/config"):
+ response = self.client.post(f"/api/projects/{self.team.id}/tasks/{path}/", payload)
+ assert response.status_code == 400, (path, response.content)
+
+ def test_clearing_the_team_default(self):
+ self.client.post(f"/api/projects/{self.team.id}/tasks/config/", TEAM_TRIPLE)
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tasks/config/",
+ {"runtime_adapter": None, "model": None, "reasoning_effort": None},
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "ai_run_preferences": {"runtime_adapter": None, "model": None, "reasoning_effort": None}
+ }
+ assert self.client.get(f"/api/projects/{self.team.id}/tasks/config/").json() == {
+ "ai_run_preferences": {"runtime_adapter": None, "model": None, "reasoning_effort": None}
+ }
+
+ def test_unauthenticated_requests_are_rejected(self):
+ self.client.logout()
+ for path in ("config", "@me/config"):
+ url = f"/api/projects/{self.team.id}/tasks/{path}/"
+ # 403, not 401: DRF's SessionAuthentication denies without a WWW-Authenticate challenge.
+ assert self.client.get(url).status_code == 403
+ assert self.client.post(url, TEAM_TRIPLE).status_code == 403
+
+ def test_an_outsider_cannot_reach_another_projects_config(self):
+ outsider = User.objects.create_and_join(Organization.objects.create(name="other"), "[email protected]", None)
+ self.client.force_login(outsider)
+ for path in ("config", "@me/config"):
+ url = f"/api/projects/{self.team.id}/tasks/{path}/"
+ assert self.client.get(url).status_code == 403, path
+ assert self.client.post(url, TEAM_TRIPLE).status_code == 403, path
+
+ def test_me_config_resolved_defaults_reflect_precedence(self):
+ self.client.post(f"/api/projects/{self.team.id}/tasks/config/", TEAM_TRIPLE)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/tasks/@me/config/")
+ assert response.status_code == 200
+ body = response.json()
+ assert body["ai_run_preferences"] == {"runtime_adapter": None, "model": None, "reasoning_effort": None}
+ assert body["resolved_ai_run_defaults"]["source"] == "team"
+ assert body["resolved_ai_run_defaults"]["model"] == "claude-opus-4-8"
+
+ response = self.client.post(f"/api/projects/{self.team.id}/tasks/@me/config/", USER_TRIPLE)
+ assert response.status_code == 200
+ body = response.json()
+ assert body["ai_run_preferences"] == USER_TRIPLE
+ assert body["resolved_ai_run_defaults"]["source"] == "user"
+ assert body["resolved_ai_run_defaults"]["model"] == "gpt-5.5"
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tasks/@me/config/",
+ {"runtime_adapter": None, "model": None, "reasoning_effort": None},
+ )
+ assert response.status_code == 200
+ body = response.json()
+ assert body["ai_run_preferences"] == {"runtime_adapter": None, "model": None, "reasoning_effort": None}
+ assert body["resolved_ai_run_defaults"]["source"] == "team"
+
+ # The project default decides what every unpinned run on the project launches with, so a member
+ # must not be able to move it for everyone — while still reading it, and owning their own.
+ def test_a_member_can_read_the_project_default_but_not_change_it(self):
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ assert self.client.get(f"/api/projects/{self.team.id}/tasks/config/").status_code == 200
+ assert self.client.post(f"/api/projects/{self.team.id}/tasks/config/", TEAM_TRIPLE).status_code == 403
+ assert self.client.post(f"/api/projects/{self.team.id}/tasks/@me/config/", USER_TRIPLE).status_code == 200
+
+ def test_me_config_is_scoped_to_the_requesting_user(self):
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ UserTasksConfig.objects.for_team(self.team.id).update_or_create(
+ team_id=self.team.id, user_id=other.id, defaults={"ai_run_preferences": USER_TRIPLE}
+ )
+ response = self.client.get(f"/api/projects/{self.team.id}/tasks/@me/config/")
+ assert response.json()["ai_run_preferences"] == {
+ "runtime_adapter": None,
+ "model": None,
+ "reasoning_effort": None,
+ }
+
+
+class TestConfigEndpointScopes(APIBaseTest):
+ # Both endpoints rely on `scope_object = "task"` to derive their scopes rather than
+ # declaring them. PostHog Desktop reads them with a personal API key, so a change to
+ # the scope object or the action sets would silently lock it out — or hand a
+ # read-only key write access.
+ def setUp(self) -> None:
+ super().setUp()
+ # Scopes are what's under test here, so keep the project-admin requirement on the team
+ # endpoint from being what fails the write.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ def _bearer(self, scopes: list[str]) -> str:
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(label="t", user=self.user, secure_value=hash_key_value(value), scopes=scopes)
+ self.client.logout()
+ return f"Bearer {value}"
+
+ @parameterized.expand(["config", "@me/config"])
+ def test_read_scope_reads_but_cannot_write(self, path: str):
+ bearer = self._bearer(["task:read"])
+ url = f"/api/projects/{self.team.id}/tasks/{path}/"
+ assert self.client.get(url, HTTP_AUTHORIZATION=bearer).status_code == 200
+ assert self.client.post(url, {}, HTTP_AUTHORIZATION=bearer).status_code == 403
+
+ @parameterized.expand(["config", "@me/config"])
+ def test_write_scope_writes(self, path: str):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tasks/{path}/",
+ {"runtime_adapter": "claude", "model": "claude-opus-4-8", "reasoning_effort": "high"},
+ HTTP_AUTHORIZATION=self._bearer(["task:read", "task:write"]),
+ )
+ assert response.status_code == 200, response.content
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index ee7ad40cf4cf..e120c2939184 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -93,6 +93,7 @@ class TestTaskHandoffConcurrency(TransactionTestCase):
mode: str = "background",
extra_state: dict | None = None,
branch: str | None = None,
+ acting_user_id: int | None = None,
) -> TaskRun:
create_reached.set()
if not handoff_finished.wait(timeout=10):
@@ -103,6 +104,7 @@ class TestTaskHandoffConcurrency(TransactionTestCase):
mode=mode,
extra_state=extra_state,
branch=branch,
+ acting_user_id=acting_user_id,
)
def bootstrap() -> None:
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
index 6516d77758b0..c07f5cfb0c82 100644
--- a/products/tasks/backend/tests/test_warm_facade.py
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -265,7 +265,6 @@ class TestWarmTaskSandbox(APIBaseTest):
"gpt-5.4",
"bypassPermissions",
),
- ("mode_without_a_runtime", None, None, "plan"),
]
)
@patch("products.tasks.backend.presentation.views.api.TaskViewSet._warm_enabled", return_value=True)
@@ -298,6 +297,29 @@ class TestWarmTaskSandbox(APIBaseTest):
assert response.json()["attr"] == "initial_permission_mode"
mock_warm.assert_not_called()
+ @patch("products.tasks.backend.presentation.views.api.TaskViewSet._warm_enabled", return_value=True)
+ @patch("products.tasks.backend.facade.api.warm_task_sandbox")
+ def test_warm_endpoint_accepts_a_mode_without_a_runtime(self, mock_warm, _mock_warm_enabled):
+ # A composer whose selection is untouched states the launch mode but pins no runtime, leaving
+ # the triple to the stored default. Requiring the adapter alongside the mode would 400 every
+ # one of those warms, so no default-selection submit could ever land on a warm sandbox.
+ mock_warm.return_value = None
+
+ response = self.client.post(
+ "/api/projects/@current/tasks/warm/",
+ {
+ "repository": "posthog/posthog",
+ "github_integration": self.integration.id,
+ "branch": "main",
+ "initial_permission_mode": "plan",
+ },
+ format="json",
+ )
+
+ assert response.status_code == 200, response.content
+ assert mock_warm.call_args.kwargs["initial_permission_mode"] == "plan"
+ assert mock_warm.call_args.kwargs["runtime_adapter"] is None
+
def test_provisions_selected_sandbox_environment_and_custom_image(self):
sandbox_environment = SandboxEnvironment.objects.create(
team=self.team,
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 6562ab7939d3..15b0e0e749f7 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -4275,6 +4275,87 @@ export interface TaskThreadMessageWriteApi {
content: string
}
+/**
+ * The default AI run triple stored at team or user level.
+ *
+ * Write payload for the tasks config endpoints and the `ai_run_preferences` block of
+ * their responses. `runtime_adapter` and `model` must be set together; send all three
+ * as null to clear a stored preference.
+ */
+export interface TasksAIRunPreferencesApi {
+ /** Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`.
+ *
+ * * `claude` - claude
+ * * `codex` - codex */
+ runtime_adapter?: RuntimeAdapterEnumApi | null
+ /**
+ * Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`.
+ * @nullable
+ */
+ model?: string | null
+ /** Default reasoning effort for models that expose an effort control.
+ *
+ * * `low` - low
+ * * `medium` - medium
+ * * `high` - high
+ * * `xhigh` - xhigh
+ * * `max` - max
+ * * `ultracode` - ultracode */
+ reasoning_effort?: ReasoningEffortEnumApi | null
+}
+
+/**
+ * * `user` - user
+ * * `team` - team
+ * * `none` - none
+ */
+export type TasksResolvedAIRunDefaultsSourceEnumApi =
+ (typeof TasksResolvedAIRunDefaultsSourceEnumApi)[keyof typeof TasksResolvedAIRunDefaultsSourceEnumApi]
+
+export const TasksResolvedAIRunDefaultsSourceEnumApi = {
+ User: 'user',
+ Team: 'team',
+ None: 'none',
+} as const
+
+/**
+ * The AI run triple a new run will effectively use when the caller pins nothing,
+ * plus which preference level supplied it.
+ */
+export interface TasksResolvedAIRunDefaultsApi {
+ /**
+ * Effective default runtime adapter, or null when no preference is stored.
+ * @nullable
+ */
+ runtime_adapter: string | null
+ /**
+ * Effective default model identifier, or null when no preference is stored.
+ * @nullable
+ */
+ model: string | null
+ /**
+ * Effective default reasoning effort, or null when unset or unsupported.
+ * @nullable
+ */
+ reasoning_effort: string | null
+ /** Preference level that supplied the default: the caller's own per-project preference ('user'), the project default ('team'), or 'none'.
+ *
+ * * `user` - user
+ * * `team` - team
+ * * `none` - none */
+ source: TasksResolvedAIRunDefaultsSourceEnumApi
+}
+
+/**
+ * The requesting user's per-project tasks configuration.
+ */
+export interface TasksUserConfigResponseApi {
+ /** The requesting user's per-project default AI run triple; all fields null when unset. */
+ ai_run_preferences: TasksAIRunPreferencesApi
+ /** The defaults a new run will use when no explicit runtime selection is sent. */
+ resolved_ai_run_defaults: TasksResolvedAIRunDefaultsApi
+}
+
/**
* The team's active onboarding wizard cloud run, used to rehydrate
* the setup-progress FAB when the run was started server-side (drop flow).
@@ -4293,6 +4374,14 @@ export interface WizardCloudRunDTOApi {
started_at?: string | null
}
+/**
+ * Team-level tasks configuration.
+ */
+export interface TasksTeamConfigResponseApi {
+ /** Project-wide default AI run triple; all fields null when unset. */
+ ai_run_preferences: TasksAIRunPreferencesApi
+}
+
/**
* One model a run may use. Reads a `ModelChoice` straight off the catalogue facade.
*
@@ -5245,6 +5334,28 @@ export type TasksThreadMessagesListParams = {
offset?: number
}
+export type TasksMeConfigListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type TasksConfigListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type TasksRepositoryReadinessRetrieveParams = {
refresh?: boolean
/**
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 359c100cd266..c47dd3defbe0 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -133,9 +133,12 @@ import type {
TaskThreadMessageWriteApi,
TaskUsageResponseApi,
TaskWriteApi,
+ TasksAIRunPreferencesApi,
TasksCommentsListParams,
TasksCommentsRetrieveParams,
+ TasksConfigListParams,
TasksListParams,
+ TasksMeConfigListParams,
TasksRepositoryReadinessRetrieveParams,
TasksRunsListParams,
TasksRunsSessionLogsRetrieveParams,
@@ -143,7 +146,9 @@ import type {
TasksSearchRetrieveParams,
TasksSlackThreadContextRetrieveParams,
TasksSummariesCreateParams,
+ TasksTeamConfigResponseApi,
TasksThreadMessagesListParams,
+ TasksUserConfigResponseApi,
TeachingCanvasApi,
WarmTaskRequestApi,
WarmTaskResponseApi,
@@ -2616,6 +2621,56 @@ export const tasksThreadMessagesSendToAgentCreate = async (
})
}
+export const getTasksMeConfigListUrl = (projectId: string, params?: TasksMeConfigListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/tasks/@me/config/?${stringifiedParams}`
+ : `/api/projects/${projectId}/tasks/@me/config/`
+}
+
+/**
+ * Retrieve your per-project default AI run preferences, plus the resolved defaults a new run will use when no explicit runtime selection is sent (your preference over the project default).
+ */
+export const tasksMeConfigList = async (
+ projectId: string,
+ params?: TasksMeConfigListParams,
+ options?: RequestInit
+): Promise<TasksUserConfigResponseApi> => {
+ return apiMutator<TasksUserConfigResponseApi>(getTasksMeConfigListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getTasksMeConfigCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/tasks/@me/config/`
+}
+
+/**
+ * Set your per-project default AI run preferences; they override the project default wholesale. Send all fields as null to clear and inherit the project default.
+ */
+export const tasksMeConfigCreate = async (
+ projectId: string,
+ tasksAIRunPreferencesApi?: TasksAIRunPreferencesApi,
+ options?: RequestInit
+): Promise<TasksUserConfigResponseApi> => {
+ return apiMutator<TasksUserConfigResponseApi>(getTasksMeConfigCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(tasksAIRunPreferencesApi),
+ })
+}
+
export const getTasksActiveWizardRunRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/tasks/active_wizard_run/`
}
@@ -2634,6 +2689,56 @@ export const tasksActiveWizardRunRetrieve = async (
})
}
+export const getTasksConfigListUrl = (projectId: string, params?: TasksConfigListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/tasks/config/?${stringifiedParams}`
+ : `/api/projects/${projectId}/tasks/config/`
+}
+
+/**
+ * Retrieve the project-wide default AI run preferences for task runs.
+ */
+export const tasksConfigList = async (
+ projectId: string,
+ params?: TasksConfigListParams,
+ options?: RequestInit
+): Promise<TasksTeamConfigResponseApi> => {
+ return apiMutator<TasksTeamConfigResponseApi>(getTasksConfigListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getTasksConfigCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/tasks/config/`
+}
+
+/**
+ * Set the project-wide default AI run preferences applied to task runs created without an explicit runtime selection. Send all fields as null to clear.
+ */
+export const tasksConfigCreate = async (
+ projectId: string,
+ tasksAIRunPreferencesApi?: TasksAIRunPreferencesApi,
+ options?: RequestInit
+): Promise<TasksTeamConfigResponseApi> => {
+ return apiMutator<TasksTeamConfigResponseApi>(getTasksConfigCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(tasksAIRunPreferencesApi),
+ })
+}
+
export const getTasksModelsRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/tasks/models/`
}
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 26cd9a0e3e26..beddea7ef82c 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -3392,6 +3392,72 @@ export const TasksThreadMessagesSendToAgentCreateBody = /* @__PURE__ */ zod
})
.describe("Response shape for one message in a task's thread.")
+/**
+ * Set your per-project default AI run preferences; they override the project default wholesale. Send all fields as null to clear and inherit the project default.
+ */
+export const TasksMeConfigCreateBody = /* @__PURE__ */ zod
+ .object({
+ runtime_adapter: zod
+ .union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])
+ .optional()
+ .describe(
+ "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`.\n\n\* `claude` - claude\n\* `codex` - codex"
+ ),
+ model: zod
+ .string()
+ .nullish()
+ .describe('Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`.'),
+ reasoning_effort: zod
+ .union([
+ zod
+ .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])
+ .describe(
+ '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Default reasoning effort for models that expose an effort control.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
+ ),
+ })
+ .describe(
+ 'The default AI run triple stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. `runtime_adapter` and `model` must be set together; send all three\nas null to clear a stored preference.'
+ )
+
+/**
+ * Set the project-wide default AI run preferences applied to task runs created without an explicit runtime selection. Send all fields as null to clear.
+ */
+export const TasksConfigCreateBody = /* @__PURE__ */ zod
+ .object({
+ runtime_adapter: zod
+ .union([zod.enum(['claude', 'codex']).describe('\* `claude` - claude\n\* `codex` - codex'), zod.null()])
+ .optional()
+ .describe(
+ "Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`.\n\n\* `claude` - claude\n\* `codex` - codex"
+ ),
+ model: zod
+ .string()
+ .nullish()
+ .describe('Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`.'),
+ reasoning_effort: zod
+ .union([
+ zod
+ .enum(['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])
+ .describe(
+ '\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Default reasoning effort for models that expose an effort control.\n\n\* `low` - low\n\* `medium` - medium\n\* `high` - high\n\* `xhigh` - xhigh\n\* `max` - max\n\* `ultracode` - ultracode'
+ ),
+ })
+ .describe(
+ 'The default AI run triple stored at team or user level.\n\nWrite payload for the tasks config endpoints and the `ai_run_preferences` block of\ntheir responses. `runtime_adapter` and `model` must be set together; send all three\nas null to clear a stored preference.'
+ )
+
/**
* Returns summary for the requested tasks: `id`, `title`, `repository`, `created_at`, `updated_at`, and the latest run's `status` and `environment`.
* @summary Fetch task summaries by ID
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index 0e1a90c72004..5f3948791574 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -379,6 +379,12 @@ tools:
tasks-comments-retrieve:
operation: tasks_comments_retrieve
enabled: false
+ tasks-config-create:
+ operation: tasks_config_create
+ enabled: false
+ tasks-config-list:
+ operation: tasks_config_list
+ enabled: false
tasks-create:
operation: tasks_create
enabled: true
@@ -460,6 +466,12 @@ tools:
- latest_run.status
- created_at
- updated_at
+ tasks-me-config-create:
+ operation: tasks_me_config_create
+ enabled: false
+ tasks-me-config-list:
+ operation: tasks_me_config_list
+ enabled: false
tasks-models-retrieve:
operation: tasks_models_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8d7a5ec1e166..66e6d6bef694 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -85247,6 +85247,95 @@ export namespace Schemas {
channel?: string | null;
}
+ /**
+ * The default AI run triple stored at team or user level.
+ *
+ * Write payload for the tasks config endpoints and the `ai_run_preferences` block of
+ * their responses. `runtime_adapter` and `model` must be set together; send all three
+ * as null to clear a stored preference.
+ */
+ export interface TasksAIRunPreferences {
+ /** Default agent runtime adapter for new task runs. Use 'claude' for the Claude runtime or 'codex' for the Codex runtime. Must be set together with `model`.
+ *
+ * * `claude` - claude
+ * * `codex` - codex */
+ runtime_adapter?: RuntimeAdapterEnum | null;
+ /**
+ * Default LLM model identifier for new task runs. Must be set together with `runtime_adapter`.
+ * @nullable
+ */
+ model?: string | null;
+ /** Default reasoning effort for models that expose an effort control.
+ *
+ * * `low` - low
+ * * `medium` - medium
+ * * `high` - high
+ * * `xhigh` - xhigh
+ * * `max` - max
+ * * `ultracode` - ultracode */
+ reasoning_effort?: ReasoningEffortEnum | null;
+ }
+
+ /**
+ * * `user` - user
+ * * `team` - team
+ * * `none` - none
+ */
+ export type TasksResolvedAIRunDefaultsSourceEnum = typeof TasksResolvedAIRunDefaultsSourceEnum[keyof typeof TasksResolvedAIRunDefaultsSourceEnum];
+
+
+ export const TasksResolvedAIRunDefaultsSourceEnum = {
+ User: 'user',
+ Team: 'team',
+ None: 'none',
+ } as const;
+
+ /**
+ * The AI run triple a new run will effectively use when the caller pins nothing,
+ * plus which preference level supplied it.
+ */
+ export interface TasksResolvedAIRunDefaults {
+ /**
+ * Effective default runtime adapter, or null when no preference is stored.
+ * @nullable
+ */
+ runtime_adapter: string | null;
+ /**
+ * Effective default model identifier, or null when no preference is stored.
+ * @nullable
+ */
+ model: string | null;
+ /**
+ * Effective default reasoning effort, or null when unset or unsupported.
+ * @nullable
+ */
+ reasoning_effort: string | null;
+ /** Preference level that supplied the default: the caller's own per-project preference ('user'), the project default ('team'), or 'none'.
+ *
+ * * `user` - user
+ * * `team` - team
+ * * `none` - none */
+ source: TasksResolvedAIRunDefaultsSourceEnum;
+ }
+
+ /**
+ * Team-level tasks configuration.
+ */
+ export interface TasksTeamConfigResponse {
+ /** Project-wide default AI run triple; all fields null when unset. */
+ ai_run_preferences: TasksAIRunPreferences;
+ }
+
+ /**
+ * The requesting user's per-project tasks configuration.
+ */
+ export interface TasksUserConfigResponse {
+ /** The requesting user's per-project default AI run triple; all fields null when unset. */
+ ai_run_preferences: TasksAIRunPreferences;
+ /** The defaults a new run will use when no explicit runtime selection is sent. */
+ resolved_ai_run_defaults: TasksResolvedAIRunDefaults;
+ }
+
export interface TeachingCanvas {
/** The teaching canvas that was resolved or created. */
canvas_id: string;
@@ -99579,6 +99668,28 @@ export namespace Schemas {
offset?: number;
};
+ export type TasksMeConfigListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type TasksConfigListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type TasksRepositoryReadinessRetrieveParams = {
refresh?: boolean;
/**