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(signals): let a team label its self-driving pull requests (#104506)

posthog[bot]d80e0fd123aa
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d05d5355468c..8bcd4fcb888d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9065,9 +9065,9 @@ snapshots:
scenes-app-inbox-scene--self-driving-verdict-pending--light:
hash: v1.k794b7964.96cdbec6c78e8daedb06be4a0134093efcd5838af69e6e7d1722a3892cf561b5.iJ2K0zNhOVgGAPY6JvduyhDBODMwk-CN7_mAdB8scOg
scenes-app-inbox-scene--settings--dark:
- hash: v1.k794b7964.dbc67b137d29e2640e1c9d7e87d0bb2dbb143e71697cf19baeac4293d9526fca.CpnlyG5rgG4kjSxgv27Sdt6i7OWxkkO_YT8eUfoXu-E
+ hash: v1.k794b7964.45842d1bb16d1d971632b9097e17ec9cbac22946ee46508599f97685857af3fb.mOuqWtWVnLdPDLGecC3GxeNk6pnmMXr4UvaSjUIg8VI
scenes-app-inbox-scene--settings--light:
- hash: v1.k794b7964.7188c4058337baba350ae79845be3130992319fb259fb0cf5206c3d1d4c95ba8.eLzK8VGpzLgMkcryFCZBBTgomfWdfOb9SFua02Vi2ts
+ hash: v1.k794b7964.bd41ab17202dcbca6ddff01d47dad365c8cb22ac6ef8989a9afebdbf5b76080c.KAmw2VUnqagBz_eOS7fVwAAO0Cz-Gvl0Jzb8R6FkZ0k
scenes-app-inbox-scene--triage--dark:
hash: v1.k794b7964.77e43b36fdcd81befecf4de80e489050f525840924ec6ddef37c23a9179dbe8a.B3qkZFYBncFaPn2EBg4cBoYu_LIwW29imNwBdLXF5eo
scenes-app-inbox-scene--triage--light:
@@ -9257,69 +9257,73 @@ snapshots:
scenes-app-inbox-scoutwritescopespicker--with-granted-scopes--light:
hash: v1.k794b7964.2dd74fab813b22724a00074e4b564fd131f976add8144d620670da70600b6511.ICZgVzVzMD7rdvIGfRR7HoKsMbp8uvKav294uYJlzuU
scenes-app-inbox-selfdrivingsection--daily-limit-reached--dark:
- hash: v1.k794b7964.027abdb918ea8b3e641afc489d0460febed2c8d926d03792d4ea2f978b5c341f.3b75XL4cuMhIgRwUMJzL4FN9jhVHQWsk_F-WvF39Xdc
+ hash: v1.k794b7964.4a44499b80e3b4929fae54d29924187253c3d56de5d4931e048e2d40f2a8fdbf._pm2YuKeybVX5dJoTbJTx9020tKZ9pl-Ygpdj5qX8jY
scenes-app-inbox-selfdrivingsection--daily-limit-reached--light:
- hash: v1.k794b7964.96066f8faf0a5515db83dbea4fca1923335d0f85ca06b0c894f6648736e86ad2.zkYrBt2LECU_2MzXTySxMzlVJuXZZrwHGvyRSKw9zqk
+ hash: v1.k794b7964.2552b9edb796ce8377be1e0732cf1a22b55337a87d337774ac15ba65ebafb719.nBjEZNigZaXr9oCbWV4FAxP4Afa_b4sSnT1y0QDj4Nk
scenes-app-inbox-selfdrivingsection--daily-limit-set--dark:
hash: v1.k794b7964.803eeb6171699607f0f6495e01c5af8c0737e7252867e18d2f3e216ee2790bcf.1p9j1RBouTKVUsmIoKn5iAiFdOh8oWZLsPv3Spxuz9Q
scenes-app-inbox-selfdrivingsection--daily-limit-set--light:
hash: v1.k794b7964.9f016e5416877dd49a4d0379e071cc6cb85d665dbc12e4129117fc1aa5c2a3de.q6WLIwBhBamXRehGTAPxy8vWbEAL5jo_Oa_frd1sMOs
scenes-app-inbox-selfdrivingsection--disabled--dark:
- hash: v1.k794b7964.1c3b6d06e8b7cda2826f1dbed75c4302180b09e0ce10decb4a9165019db62266.3Z57xV-AXwoqOo3dwGg2ZnSIYcf2akzlGyVs3tN6eYw
+ hash: v1.k794b7964.67c52a409773b5aa738f4b428db3f0963d0f108e3898aa3b8488b93a5109f7e9.vxcpMUOLsJNUSWOTb5jgl6F5GFDZbn2TKBVyagdc7Wg
scenes-app-inbox-selfdrivingsection--disabled--light:
- hash: v1.k794b7964.f26838ffbf5e310aca1591bc211ccd5aaf4c933c475eb40db24cba3b03546ab7.t5J-3dJfsGl6XzX6bf63x8TmFvidmJoAQV8CqWx2SE0
+ hash: v1.k794b7964.9d45ad19b3e57de007fd7267514b02d3d75905309cacfe802a02401e032d9142.scHTYMs1ht7uVcRdS66vUV8oif3bbpmH3VErvEEWXLQ
scenes-app-inbox-selfdrivingsection--git-hub-assignment-on--dark:
- hash: v1.k794b7964.524c26488a77e4759db4d6e9783a3c3028c38d514e87fdfb321cef7a75410542.KRAp5JtNs-ir8F1Ds7QLfAkG03WCtdjFAkRaHWJZb5w
+ hash: v1.k794b7964.2048d8af33dd1b7bdab7954f4f74cf69610e2ecd449d734b5dbb917a228a70e2.43SHYSmyRZTWRth2UKhusbdGQxTRIu7m8FLfUhv-xEc
scenes-app-inbox-selfdrivingsection--git-hub-assignment-on--light:
- hash: v1.k794b7964.57af56f19994255413673d8fc12ec148ff9b033eb123e66e240635a23718cb46.LLSxjyWoQftRO_OMQoiI8Ks0T6S8ZuLWK6b9pWALJ7E
+ hash: v1.k794b7964.0c87bc2bf8016881a8da21e17a391706bcdd1dab28591625ec52ad7252c6fda9.iMTiX71OrPQnFlNdHYXIPMjGVn0jkw6cEC4sfimtHT0
scenes-app-inbox-selfdrivingsection--issue-tracker-configured--dark:
- hash: v1.k794b7964.0956d0f012b6da9877448cd1afd59bffec92f23fe568c76bbbb63ccd7f778da0.j1RolAIx5vnIu-hTCBxc-_sNok53fyvTFakq1kqWeOk
+ hash: v1.k794b7964.607b264792b74aa4eb84cd81cc88523dbc68c67b8b70c58f166bbd29a85ea552.NTBtiUUds9_UydNtWJjBTueBo8hlXyJnRNBaEvzQLDk
scenes-app-inbox-selfdrivingsection--issue-tracker-configured--light:
- hash: v1.k794b7964.1a9038f9d2377dc4ceb76e7d132156e808d5af750bc8d9df1ec714bd6eb76ac0.oo-Os2qSOshYrCqT1P6KaM__RMUU4JNfQGj8tV96qaI
+ hash: v1.k794b7964.130d64df000f7f250617ee7559681396e265dc5439f23f416c3b3489267d0cb7.xijSum1KIg5Lg2POz6YUqEF-np9r1EhOk__LzH3bflk
scenes-app-inbox-selfdrivingsection--issue-tracker-unavailable--dark:
- hash: v1.k794b7964.6bfc4c4bf6e0dd7990584e903704b5f44f073a62e5c9ac8328a7cbef659f894b.X4le-xk7srup5exu5Pc5_Si2qfegExY70NvNhunda5Q
+ hash: v1.k794b7964.ce5ebca0d7238acbaca6648c8d187e18949d1a0743c9947a6aee94f7565b4745.e6FgfFWM0JAbSQpXDU73zhQomAV9QIfUIC7ZuCFQqOY
scenes-app-inbox-selfdrivingsection--issue-tracker-unavailable--light:
- hash: v1.k794b7964.e6f7bb7efdb33b8d946315868e4fc665367e81f6358968df6fe0b2fd816b7f43.-RWkNykvwjmxBO1N0IJkZCypT-XX_4MgBR1GpsfuCQk
+ hash: v1.k794b7964.a40ce2bea2137f38dbc1be15138904319e657d645323d0bea0c368a3bddbac9c.-OqHP5x00JhIo2zm8O0xX3Q82uGR_DNdm_QpQdl-cnU
scenes-app-inbox-selfdrivingsection--no-daily-limit--dark:
hash: v1.k794b7964.6bfc4c4bf6e0dd7990584e903704b5f44f073a62e5c9ac8328a7cbef659f894b.Zs4HmlPiQAY7AcGHJVh2OPWqQJNKXk3BuZmHkiKdbDs
scenes-app-inbox-selfdrivingsection--no-daily-limit--light:
hash: v1.k794b7964.e6f7bb7efdb33b8d946315868e4fc665367e81f6358968df6fe0b2fd816b7f43.Tbsop2bzrMmW_XDaJZaS8LkSJFrgzhcs_-GNlHpeEUE
scenes-app-inbox-selfdrivingsection--personal-default--dark:
- hash: v1.k794b7964.6bfc4c4bf6e0dd7990584e903704b5f44f073a62e5c9ac8328a7cbef659f894b.mqG4VjYYqTJPbk7ZxvOgrMuzYO5hitL82lKfbxlTQhw
+ hash: v1.k794b7964.ce5ebca0d7238acbaca6648c8d187e18949d1a0743c9947a6aee94f7565b4745.t_zBEU56wdgvozh7MjKGyjJefOfR3elvu9OLwQ2eeKw
scenes-app-inbox-selfdrivingsection--personal-default--light:
- hash: v1.k794b7964.e6f7bb7efdb33b8d946315868e4fc665367e81f6358968df6fe0b2fd816b7f43.de-M1MiqSnjIleeHY7YwmVFJMZQeEHrgjXKJcCnJwRg
+ hash: v1.k794b7964.a40ce2bea2137f38dbc1be15138904319e657d645323d0bea0c368a3bddbac9c.dzCdwDl1FI8g5v0wt4dbBX66rk5b74S3DdrQ5GqyANc
scenes-app-inbox-selfdrivingsection--personal-override--dark:
hash: v1.k794b7964.69ff637570dd0c4552ce79381e95c93a6baffe1128073aa26dcb83b46f9f18b3.QQxjqXI6_7BizM74pQraLJtBZeYSE_DyzVEvD4WYEeM
scenes-app-inbox-selfdrivingsection--personal-override--light:
hash: v1.k794b7964.99dcf76885f00937728bc09909c37e6b19f65dd87c23a1e727b37d0bc62889b2.waMhfFGGYjyAX8SZUF5oMmeh5QzMSfBnT0wc5icCgeo
scenes-app-inbox-selfdrivingsection--pull-request-ready-for-review--dark:
- hash: v1.k794b7964.5c7016fb60829b29c82e9bf3f07d963d1e00eac9a629acca351639e8dfa4eee7.PK60jC-eLVVJyLASnginr-jH-kW4XeJ0kXcaHuhWHoE
+ hash: v1.k794b7964.1a0e040104e8f46ccc9f26d865f2bfdb76cf6018000b3cf1af23e8656e94ec4b.yl0PvNcatqNQBK6oTIRVO98bHg38keelqIAnSwczBr4
scenes-app-inbox-selfdrivingsection--pull-request-ready-for-review--light:
- hash: v1.k794b7964.4413b7625076a075f7885a916773fcf57eaf431ab4022ddba2fad92fed45a8a5.S9dGHX6YN9sKL3WrxkT5rMtlc5ZN2IQDcFCWew1o1NE
+ hash: v1.k794b7964.0cc4df3d0c5f340bdb4d144eaecafe175a940e632c3c4cfbb966463381732653.0Lit1qJKj43L-25kqIQCmpDtahioNark9LhcgeVheHA
scenes-app-inbox-selfdrivingsection--settings-tab--dark:
- hash: v1.k794b7964.044e15a7e573425f0c482378b04343142fa8fe6bcaf2df3d35492b17861524b5.GpGngARPmeN9NYvgNs7PUw69AB_NZi8OZ_CPWOWlltw
+ hash: v1.k794b7964.73d54d684491b967580f16c8f040f7dc0672d1d47eea733dfd72515353f3a283.jsJn6NIkxuO4kW60JT5MNq2jqjhwywYIasG-hnKtgmE
scenes-app-inbox-selfdrivingsection--settings-tab--light:
- hash: v1.k794b7964.88ac658607ec63989aa8d3354212f68ab053974296882d4e515d7bca5e100322.UgALD2SDOAEEffeuf8rwsR60RTGiA4VBDRIp2bqAis0
+ hash: v1.k794b7964.f939e35b6372f295f13403c926cfe0e3fae65c31fce353d0d9f1ece4f8062c8e.OCcSSCffkbrErjrhS03gNtz9JtfeEzgsVt6Wj3uurKQ
scenes-app-inbox-selfdrivingsection--settings-tab-base-branches--dark:
- hash: v1.k794b7964.ca88af903008fea09ee8b8c1d354c148797006250b948da9043499b21c2272d4.zcdK-Ds3Kic7Q4WtleLQG1hWXxxOpwB_SoQH-mCSrq8
+ hash: v1.k794b7964.037702be4e4749b04341ba60377272d3dbd80c9a57f68bef328e2c6c8c3c4da2.FX2I6HqOxd2ga3DyvWu4CmvrLnI2rXuGJy4OTlwNGcA
scenes-app-inbox-selfdrivingsection--settings-tab-base-branches--light:
- hash: v1.k794b7964.2059311feb93424cf8acb48cacb174a5ab422213f972bfcf4395ac2292acc743.5cWpKb2yzNnfHv8fyusBvyR9m7JfPa6xJzT6iGtWAlU
+ hash: v1.k794b7964.38a73ca6a69e7696f4c8ea7444857fc452f1404d1826416247f439a009945484.zVoYfS-GKAwtDPgz_vApSJHKeUL0ltV0_R0fh3_eFiM
scenes-app-inbox-selfdrivingsection--settings-tab-base-branches-without-git-hub--dark:
- hash: v1.k794b7964.ec42adbf666a5d1c1e01359ef99fe30bb0ac15a440c868e39271f1c6cc5bc0a9.iR202ex1FvPA8l_vx2zZVMFi2dKKUFStDnzskUkunLQ
+ hash: v1.k794b7964.ffa8896ff2257c8e716c1f69ff4e44ce9ab02282e79958ade0207d04386aa0d4.1CwFTqs7SXZiR5ZvXBkvBATOh1J7w89SbmtXlaeNEEI
scenes-app-inbox-selfdrivingsection--settings-tab-base-branches-without-git-hub--light:
- hash: v1.k794b7964.a3c4202c5a498c006f1ff88e755604e38574b4658a6539c0d5efa2fc87fad0e0.K2g-9o2erlGEfhbgAVP4oqDogZFCfrxqa8F1FAiiehA
+ hash: v1.k794b7964.11e08c171bf353ccfee2db70c57ea3ccaa6b12e8b0a03d02c83119e3a4e16cdc.a7G9bxu9jDd0qadX7F4U_OwhtIO57VLnLLZjb64Huq8
scenes-app-inbox-selfdrivingsection--settings-tab-disabled--dark:
- hash: v1.k794b7964.1ecf216757ce2db57fe852a49aac8e3285eddcffc533bb6d4d4bd64a893bf03a.BNXn4jfro34u7tfGlpvKw_BDJB3CWldR9ccgZ1ieFK4
+ hash: v1.k794b7964.77c441704273d76b7dfeadf555f9e20d6521591218183e4aa724914260459d36.HJb6E6tHZgI-yeIrgpb4TVGgiwcQqhYnN7fTiLws_k8
scenes-app-inbox-selfdrivingsection--settings-tab-disabled--light:
- hash: v1.k794b7964.965985d456fd402f5d56535a2c7b648c4fe489781520325dbb3a7fbad377d1ee.1zFknWFsS9hOaZV9CHfeK2FSWwXIcXaR18SdKn_suXc
+ hash: v1.k794b7964.af88839aa3b693934557a8c56e5b64abecad7ca3bc9a4d84b7a338376fd8d52c.uTBJPAOtZkMoCzF37Td3guXFmRe-jSMpd1w8uk2NTEA
scenes-app-inbox-selfdrivingsection--settings-tab-issue-tracker-jira--dark:
- hash: v1.k794b7964.08bda87bf4c2a3a1bf6232f395b74d879fe3a025174a60e058e693cc25b085fe.SX7eUSB6gow5Oar38Pn-8EfIk4aTja9XvS937Zn54t8
+ hash: v1.k794b7964.41f8cb0d40cdfe1f30fdebcf68042f24ee33367da507a368b7dd975021b430ac.H420utrLer2NAkgVYqihR6I28K9j3nVT_XDcfIMLD7E
scenes-app-inbox-selfdrivingsection--settings-tab-issue-tracker-jira--light:
- hash: v1.k794b7964.799b981717d3ccd8c33a7b6dfdc15e8bfddf18f8fa957ab2702e6b440bac5c34.BcVp6QtB-QWj_Sp2fdEUlHxokd0SPlCU_d_oyq4S9Ss
+ hash: v1.k794b7964.aaaabd1b81adf2925d41b6f1669df2fd51b40a51ca45136d7b957497aa4eec7f.H79XAtJQOt39ysPpGobM1UfSra_wvUi9AfngAxkg-xk
scenes-app-inbox-selfdrivingsection--settings-tab-narrow--dark:
- hash: v1.k794b7964.9aca38b1236ed16a464f94102f9474904f14937adcd17d419ccd6c6748498025.KorTthkm-gqbl1oile51fljznkrj4jr-Bc0D9neiQOg
+ hash: v1.k794b7964.dc72ce7f6450d86f61aabe9aec6f346325fc6fad9d2d9168931ea43cac770a6a.-0dRG3TQXxaPJ27QdpYWymIxoqW_mrjqVw-Naw7NqhU
scenes-app-inbox-selfdrivingsection--settings-tab-narrow--light:
- hash: v1.k794b7964.bc690ec63fc78a5be3c81b9d3fff83716f69d0ffecaa7ec5b20318983808bc4e.S8Pbf4Hj1-mIxKF7R6_7lVDwWT5GpUE7zObcG1aMe5M
+ hash: v1.k794b7964.3c8a7580a33ef3e0b58a39c9248a92898a290568d5f78d13a7ae719eb188258a.yV89Z-Q64XKnpeh_sezuDUVpVRwZrHSRzTerZyWpHHU
+ scenes-app-inbox-selfdrivingsection--settings-tab-pull-request-label--dark:
+ hash: v1.k794b7964.4d62e7926695f50bd7b02ea4092752e7965713dbc423c76d08e1d3298243ed73.IOWkj7p1fx5_V80m_ox9tMjLPbGfSeoiccWRtK2_psA
+ scenes-app-inbox-selfdrivingsection--settings-tab-pull-request-label--light:
+ hash: v1.k794b7964.8e029066ec5eff3a0860a1f497fd5b5e436b707b927ba291b3bc9ab41003df9e.2_Thr1X2vS4SYU8ahO2fZMAf9DKuKnusmCm-MqqYl6Y
scenes-app-inbox-signal-cards--all-sources--dark:
hash: v1.k794b7964.c23ba49824c663d604c2fb7b3a9f1e619538a8467f84f8ef83db26c2e585ab1b.Sxd64grePFgHAwyuax_T65ns2I4GkYa0Do6P8rVwFII
scenes-app-inbox-signal-cards--all-sources--light:
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index cd2f47dc4021..b738b69c508a 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -392,6 +392,8 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {
"issue_tracking_config": "issue tracker target",
"default_open_pull_request_ready": "PRs open as",
"github_issue_writeback_enabled": "comment back on GitHub issues",
+ "pull_request_label_enabled": "label self-driving PRs",
+ "pull_request_label": "self-driving PR label",
},
"OAuthApplication": {
"_provisioning_config": "provisioning config",
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 722b2d82a88d..dc9868d2b4e1 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -61,6 +61,11 @@ GITHUB_ACCOUNT_NAME_HEAL_CLAIM_TTL_SECONDS = 60
# GitHub's add-assignees endpoint caps a single call at 10 logins and silently drops the rest.
MAX_PR_ASSIGNEES = 10
+# GitHub label names cap at 50 characters, and a self-driving pull request only ever carries the one
+# label its team configured, so a longer list is a caller mistake rather than a use we support.
+MAX_PR_LABELS = 10
+MAX_LABEL_NAME_LENGTH = 50
+
# Reactions cost one extra round trip per reacted comment, and GitHub offers no way to fetch them in
# bulk, so bound the fan-out. Set high enough that a real pull request never reaches it: past this
# point a comment renders without its pills, which is worse than the extra requests.
@@ -1325,6 +1330,62 @@ class GitHubIntegrationBase:
]
return {"success": True, "assignees": assigned}
+ def add_pull_request_labels(self, repository: str, pr_number: int, labels: Iterable[str]) -> dict[str, Any]:
+ """Add labels to a pull request. ``repository`` is ``owner/repo`` or a bare repo.
+
+ Additive only. GitHub's add-labels endpoint never removes a label, so a caller cannot clear
+ one by leaving it out of ``labels``, and adding a label the pull request already carries
+ changes nothing. A name the repository does not define yet is created first, because GitHub
+ refuses the whole call otherwise.
+
+ Labels use the issues endpoint (a PR is an issue for labelling purposes).
+ """
+ wanted = list(dict.fromkeys(name.strip() for name in labels if name and name.strip()))[:MAX_PR_LABELS]
+ if not wanted or any(len(name) > MAX_LABEL_NAME_LENGTH for name in wanted):
+ return {"success": True, "labels": []}
+
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+ url = f"https://api.github.com/repos/{repo_path}/issues/{pr_number}/labels"
+ endpoint = "/repos/{owner}/{repo}/issues/{issue_number}/labels"
+
+ response = self._installation_authenticated_post(url, endpoint=endpoint, json_body={"labels": wanted})
+ if response is not None and response.status_code == 422:
+ # 422 is what an undefined label name reads as, so create the names and try once more.
+ # A name that already exists costs one refused create, never a lost label.
+ for name in wanted:
+ self._create_repository_label(repo_path, name)
+ response = self._installation_authenticated_post(url, endpoint=endpoint, json_body={"labels": wanted})
+ if response is None:
+ return {"success": False, "error": "Network error labelling pull request"}
+ if response.status_code != 200:
+ return {
+ "success": False,
+ "error": f"Failed to label pull request: {response.text}",
+ "status_code": response.status_code,
+ }
+ try:
+ body = response.json()
+ except Exception:
+ body = []
+ applied = [entry["name"] for entry in body if isinstance(entry, dict) and entry.get("name")]
+ return {"success": True, "labels": applied}
+
+ def _create_repository_label(self, repo_path: str, name: str) -> bool:
+ """Define ``name`` as a label in the repository. Returns whether it exists afterwards.
+
+ No color is chosen, so GitHub picks one and the team can restyle the label without this
+ ever writing over their choice. A label somebody created in between answers 422, which
+ counts as existing.
+ """
+ response = self._installation_authenticated_post(
+ f"https://api.github.com/repos/{repo_path}/labels",
+ endpoint="/repos/{owner}/{repo}/labels",
+ json_body={"name": name},
+ )
+ if response is None:
+ return False
+ return response.status_code in (201, 422)
+
def is_assignable(self, repository: str, login: str) -> dict[str, Any]:
"""Whether ``login`` can be assigned to issues and pull requests in ``repository``.
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index 37834439c974..1c96c6d269dc 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -1009,6 +1009,58 @@ class TestGitHubIntegrationModel(BaseTest):
assert result["success"] is False
assert result["status_code"] == 422
+ def test_add_pull_request_labels_posts_to_issues_endpoint(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=200)
+ mock_response.json.return_value = [{"name": "self-driving"}]
+ with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:
+ result = github.add_pull_request_labels("PostHog/posthog", 123, ["self-driving"])
+ assert result == {"success": True, "labels": ["self-driving"]}
+ # Labels go through the issues endpoint, not /pulls.
+ assert mock_post.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/123/labels"
+ assert mock_post.call_args.kwargs["json_body"] == {"labels": ["self-driving"]}
+
+ def test_add_pull_request_labels_creates_a_label_the_repository_lacks(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ refused = MagicMock(status_code=422, text="Validation Failed")
+ created = MagicMock(status_code=201)
+ applied = MagicMock(status_code=200)
+ applied.json.return_value = [{"name": "self-driving"}]
+ with patch.object(
+ github, "_installation_authenticated_post", side_effect=[refused, created, applied]
+ ) as mock_post:
+ result = github.add_pull_request_labels("PostHog/posthog", 123, ["self-driving"])
+ assert result == {"success": True, "labels": ["self-driving"]}
+ assert mock_post.call_args_list[1].args[0] == "https://api.github.com/repos/PostHog/posthog/labels"
+ assert mock_post.call_args_list[1].kwargs["json_body"] == {"name": "self-driving"}
+
+ @parameterized.expand(
+ [
+ ("empty", []),
+ ("all_blank", ["", None, " "]),
+ # GitHub caps a label name at 50 characters, so a longer one is a caller mistake.
+ ("too_long", ["l" * 51]),
+ ]
+ )
+ def test_add_pull_request_labels_skips_github_when_there_is_nothing_to_apply(self, _name: str, labels: list):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ with patch.object(github, "_installation_authenticated_post") as mock_post:
+ result = github.add_pull_request_labels("PostHog/posthog", 123, labels)
+ assert result == {"success": True, "labels": []}
+ mock_post.assert_not_called()
+
+ def test_add_pull_request_labels_reports_a_github_error(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=403, text="Forbidden")
+ with patch.object(github, "_installation_authenticated_post", return_value=mock_response):
+ result = github.add_pull_request_labels("PostHog/posthog", 123, ["self-driving"])
+ assert result["success"] is False
+ assert result["status_code"] == 403
+
@parameterized.expand(
[
("assignable", 204, {"success": True, "assignable": True}),
diff --git a/products/signals/backend/migrations/0149_signalteamconfig_pull_request_label_and_more.py b/products/signals/backend/migrations/0149_signalteamconfig_pull_request_label_and_more.py
new file mode 100644
index 000000000000..973d2bf62d39
--- /dev/null
+++ b/products/signals/backend/migrations/0149_signalteamconfig_pull_request_label_and_more.py
@@ -0,0 +1,20 @@
+# Generated by Django 5.2.17 on 2026-09-22 13:47
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("signals", "0148_signalreportpullrequest_review_details")]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalteamconfig",
+ name="pull_request_label",
+ field=models.CharField(blank=True, max_length=50, null=True),
+ ),
+ migrations.AddField(
+ model_name="signalteamconfig",
+ name="pull_request_label_enabled",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 6c98711e5aa7..6ba6ae4976f5 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0148_signalreportpullrequest_review_details
+0149_signalteamconfig_pull_request_label_and_more
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 4cba872d6fbf..3d51f8c8d025 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -156,6 +156,11 @@ class AutonomyPriority(models.TextChoices):
P4 = "P4", "P4"
+# What GitHub accepts as a label name. Duplicated from the GitHub client rather than imported,
+# because that module pulls the HTTP stack in and this one is loaded on every Django start.
+GITHUB_LABEL_NAME_MAX_LENGTH = 50
+
+
class SignalTeamConfig(ModelActivityMixin, UUIDModel):
team = models.OneToOneField(
"posthog.Team",
@@ -192,6 +197,12 @@ class SignalTeamConfig(ModelActivityMixin, UUIDModel):
# github_writeback.py). Off by default, because the comment is public on the issue thread and
# tells everybody watching it that we are working on it, which is a team's call to make.
github_issue_writeback_enabled = models.BooleanField(default=False, db_default=False)
+ # Label every self-driving pull request, so GitHub search, saved searches, and notification
+ # rules can separate them from the rest of the shared bot identity's pull requests (see
+ # pull_request_label.py). Off by default, because the label lands on a repository the team
+ # shares with everybody. A null or blank name falls back to DEFAULT_PULL_REQUEST_LABEL.
+ pull_request_label_enabled = models.BooleanField(default=False, db_default=False)
+ pull_request_label = models.CharField(max_length=GITHUB_LABEL_NAME_MAX_LENGTH, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/products/signals/backend/pull_request_label.py b/products/signals/backend/pull_request_label.py
new file mode 100644
index 000000000000..d1bc451fc515
--- /dev/null
+++ b/products/signals/backend/pull_request_label.py
@@ -0,0 +1,124 @@
+"""Label a report's implementation pull request, so GitHub can tell it apart from other bot work.
+
+A self-driving pull request opens under the shared bot identity every other piece of automation
+pushes under, and its `posthog-self-driving/` head branch is not something GitHub search can match
+on. So a team that wants a saved search, a notification rule, or an exclusion has nothing to build
+one from. One label solves all three at once.
+
+Opt-in through `SignalTeamConfig.pull_request_label_enabled`, because the label lands on a
+repository the team shares with everybody. Best effort throughout: a GitHub failure must never
+break the pull request link or the report write that triggered it.
+"""
+
+from __future__ import annotations
+
+from django.db import transaction
+
+import structlog
+
+from posthog.models.integration import GitHubIntegration
+
+from products.signals.backend.models import SignalReport, SignalReportAssignment, SignalTeamConfig
+
+logger = structlog.get_logger(__name__)
+
+# What a team gets when it turns the label on without naming one. Reads the same way in a GitHub
+# search as it does in the inbox settings, so nobody has to translate between the two.
+DEFAULT_PULL_REQUEST_LABEL = "self-driving"
+
+# Only a live pull request is worth a GitHub call. UNKNOWN is included because a row that never
+# recorded a state is far more often open than closed.
+LABELLABLE_PR_STATES = frozenset(
+ {
+ SignalReportAssignment.PrState.OPEN,
+ SignalReportAssignment.PrState.DRAFT,
+ SignalReportAssignment.PrState.UNKNOWN,
+ }
+)
+
+
+def schedule_pull_request_label(
+ *,
+ team_id: int,
+ report_id: str,
+ pr_url: str | None,
+ pr_state: str | None,
+) -> None:
+ """Queue the label for a report's pull request, after the current transaction commits.
+
+ Enqueued on commit so nothing is labelled if the write rolls back, and so the GitHub calls run
+ on a worker instead of holding up the claim, sync, or webhook that queued it. `robust=True`
+ keeps a broker outage from failing a write that already committed.
+ """
+ if not pr_url or (pr_state or SignalReportAssignment.PrState.UNKNOWN) not in LABELLABLE_PR_STATES:
+ return
+
+ # noqa: PLC0415 because `tasks` imports this module for the task body, so a module-level
+ # import here would be a cycle.
+ from products.signals.backend.tasks import label_implementation_pr # noqa: PLC0415
+
+ transaction.on_commit(
+ lambda: label_implementation_pr.delay(
+ team_id=team_id,
+ report_id=str(report_id),
+ pr_url=pr_url,
+ ),
+ robust=True,
+ )
+
+
+def configured_pull_request_label(team_id: int) -> str | None:
+ """The label this team wants on its self-driving pull requests, or None when it wants none."""
+ config = (
+ SignalTeamConfig.objects.filter(team_id=team_id)
+ .values("pull_request_label_enabled", "pull_request_label")
+ .first()
+ )
+ if config is None or not config["pull_request_label_enabled"]:
+ return None
+ return (config["pull_request_label"] or "").strip() or DEFAULT_PULL_REQUEST_LABEL
+
+
+def apply_pull_request_label(*, team_id: int, report_id: str, pr_url: str) -> str | None:
+ """Put the team's label on the report's pull request. Returns the label GitHub applied.
+
+ Returns None when there was nothing to do, which covers a team that never turned the label on
+ and a repository with no GitHub integration. A failed call also returns None, and this raises
+ nothing.
+ """
+ # The team's setting first: a team that never turned the label on is the common case, so it
+ # answers in one query rather than two.
+ label = configured_pull_request_label(team_id)
+ if label is None:
+ return None
+
+ if not SignalReport.objects.filter(id=report_id, team_id=team_id).exists():
+ return None
+
+ parsed = GitHubIntegration.parse_pull_request_url(pr_url)
+ if parsed is None:
+ return None
+
+ log = logger.bind(team_id=team_id, report_id=report_id, repository=parsed.repository, pr_number=parsed.number)
+ try:
+ github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
+ except Exception:
+ log.exception("signals.pull_request_label.integration_lookup_failed")
+ return None
+ if github is None:
+ return None
+
+ try:
+ result = github.add_pull_request_labels(parsed.repository, parsed.number, [label])
+ except Exception:
+ log.exception("signals.pull_request_label.label_failed")
+ return None
+ if not result.get("success"):
+ log.warning("signals.pull_request_label.label_failed", error=result.get("error"))
+ return None
+
+ if label not in (result.get("labels") or []):
+ log.warning("signals.pull_request_label.label_not_applied")
+ return None
+ log.info("signals.pull_request_label.labelled")
+ return label
diff --git a/products/signals/backend/pull_requests.py b/products/signals/backend/pull_requests.py
index 8dcf36922dde..b1cb16d7e935 100644
--- a/products/signals/backend/pull_requests.py
+++ b/products/signals/backend/pull_requests.py
@@ -107,6 +107,7 @@ def link_pull_request(
.exclude(id=link.id)
.exists()
):
+ from products.signals.backend.pull_request_label import schedule_pull_request_label
from products.signals.backend.reviewer_pr_assignment import schedule_reviewer_pr_assignment
from products.signals.backend.reviewer_pr_ready import schedule_open_pull_request_ready
@@ -116,6 +117,9 @@ def link_pull_request(
schedule_open_pull_request_ready(
team_id=report.team_id, report_id=str(report.id), pr_url=pr.url, pr_state=pr.state
)
+ schedule_pull_request_label(
+ team_id=report.team_id, report_id=str(report.id), pr_url=pr.url, pr_state=pr.state
+ )
return pr
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 926f416cf333..60d547b86b2b 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -45,6 +45,7 @@ if TYPE_CHECKING:
from .artefact_schemas import NON_WRITABLE_ARTEFACT_TYPES
from .daily_limit import reports_generated_today, team_day_start
from .models import (
+ GITHUB_LABEL_NAME_MAX_LENGTH,
MAX_SCOUT_REPORT_NOTES,
AutonomyPriority,
SignalActorKind,
@@ -60,6 +61,7 @@ from .models import (
SignalTeamConfig,
SignalUserAutonomyConfig,
)
+from .pull_request_label import DEFAULT_PULL_REQUEST_LABEL
from .report_charts import CHART_SIZES, MAX_CHART_CAPTION_LENGTH, MAX_CHART_ID_LENGTH, MAX_CHART_TITLE_LENGTH
from .report_generation.resolve_reviewers import enrich_reviewer_dicts_with_org_members
from .report_metric_access import ReportMetricAccessPolicy
@@ -355,6 +357,25 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):
"default. Needs a GitHub integration that can reach the issue's repository."
),
)
+ pull_request_label_enabled = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "Whether self-driving adds a label to every pull request it opens, so GitHub search, "
+ "saved searches, and notification rules can separate them from other automation on the "
+ "repository. False by default. Needs a GitHub integration that can reach the repository."
+ ),
+ )
+ pull_request_label = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ max_length=GITHUB_LABEL_NAME_MAX_LENGTH,
+ help_text=(
+ f"The label name self-driving applies, at most {GITHUB_LABEL_NAME_MAX_LENGTH} characters. "
+ f"Null or blank means '{DEFAULT_PULL_REQUEST_LABEL}'. The label is created in the repository "
+ "when it does not exist yet. Only used while pull_request_label_enabled is true."
+ ),
+ )
reports_generated_today = serializers.SerializerMethodField(
help_text=(
"How many reports first became visible in the inbox during the current project-timezone "
@@ -368,6 +389,11 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):
)
)
+ def validate_pull_request_label(self, value: str | None) -> str | None:
+ # One stored shape for "use the default", so a team that clears the box does not get a
+ # label GitHub would refuse.
+ return (value or "").strip() or None
+
# Memoized per serializer instance: both computed fields need the same count, and an
# instance only ever renders the team's one singleton row.
_reports_today: int | None = None
@@ -404,6 +430,8 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):
"max_reports_per_day",
"default_open_pull_request_ready",
"github_issue_writeback_enabled",
+ "pull_request_label_enabled",
+ "pull_request_label",
"reports_generated_today",
"daily_report_limit_reached",
"created_at",
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 3654e57d17ed..c616ee7fcddf 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -42,6 +42,7 @@ from products.signals.backend.models import (
)
from products.signals.backend.pr_origin import write_origin_section
from products.signals.backend.pull_request_body import BodyEditOutcome
+from products.signals.backend.pull_request_label import apply_pull_request_label
from products.signals.backend.pull_requests import update_pull_request_review_decision
from products.signals.backend.report_generation.repo_activity import (
ACTIVITY_KEEP_WARM_WINDOW,
@@ -729,6 +730,21 @@ def move_merged_report_signals(team_id: int, survivor_report_id: str, source_rep
)
+@shared_task(
+ name="products.signals.backend.tasks.label_implementation_pr",
+ ignore_result=True,
+ max_retries=0,
+)
+@with_team_scope()
+def label_implementation_pr(team_id: int, report_id: str, pr_url: str) -> None:
+ """Put the team's label on a report's implementation PR, so GitHub search can find it.
+
+ Runs on a worker for the same reason as reviewer assignment: the GitHub calls must not hold up
+ the claim, sync, or webhook that queued it. Best-effort end to end, so this never retries.
+ """
+ apply_pull_request_label(team_id=team_id, report_id=report_id, pr_url=pr_url)
+
+
def _capture_refund_sync_event(refund: SignalReportRefund, event: str, extra: dict[str, object]) -> None:
organization = refund.team.organization
with ph_scoped_capture() as capture:
diff --git a/products/signals/backend/test/test_pull_request_label.py b/products/signals/backend/test/test_pull_request_label.py
new file mode 100644
index 000000000000..a081691bd187
--- /dev/null
+++ b/products/signals/backend/test/test_pull_request_label.py
@@ -0,0 +1,196 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.models import Organization, Team, User
+
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.models import SignalReport, SignalReportAssignment, SignalTeamConfig
+from products.signals.backend.pull_request_label import (
+ DEFAULT_PULL_REQUEST_LABEL,
+ apply_pull_request_label,
+ configured_pull_request_label,
+ schedule_pull_request_label,
+)
+from products.signals.backend.report_assignments import claim_report
+
+PR_URL = "https://github.com/PostHog/posthog/pull/123"
+
+
+def org_and_team():
+ org = Organization.objects.create(name="pr-label-org")
+ team = Team.objects.create(organization=org, name="pr-label-team")
+ yield org, team
+ team.delete()
+ org.delete()
+
+
+def _make_report(team: Team) -> SignalReport:
+ return SignalReport.objects.create(
+ team=team, status=SignalReport.Status.READY, title="Report", summary="Summary", signal_count=1, total_weight=1.0
+ )
+
+
+def _labelling_github(label: str) -> MagicMock:
+ github = MagicMock()
+ github.add_pull_request_labels.return_value = {"success": True, "labels": [label]}
+ return github
+
+
+class TestConfiguredPullRequestLabel:
+ @pytest.mark.django_db
+ @pytest.mark.parametrize(
+ ("enabled", "name", "expected"),
+ [
+ (True, "self-driving-pr", "self-driving-pr"),
+ (True, " spaced ", "spaced"),
+ # A team that turns the label on without naming one still gets a label.
+ (True, None, DEFAULT_PULL_REQUEST_LABEL),
+ (True, "", DEFAULT_PULL_REQUEST_LABEL),
+ (True, " ", DEFAULT_PULL_REQUEST_LABEL),
+ # A name left behind by an earlier opt-in must not label anything once the switch is off.
+ (False, "self-driving-pr", None),
+ (False, None, None),
+ ],
+ ids=["named", "trimmed", "null_name", "blank_name", "whitespace_name", "off_with_name", "off"],
+ )
+ def test_the_switch_decides_and_a_blank_name_means_the_default(
+ self, org_and_team, enabled: bool, name: str | None, expected: str | None
+ ):
+ _, team = org_and_team
+ SignalTeamConfig.objects.update_or_create(
+ team=team, defaults={"pull_request_label_enabled": enabled, "pull_request_label": name}
+ )
+
+ assert configured_pull_request_label(team.id) == expected
+
+ @pytest.mark.django_db
+ def test_a_team_that_never_touched_the_setting_wants_no_label(self, org_and_team):
+ _, team = org_and_team
+ SignalTeamConfig.objects.filter(team=team).delete()
+
+ assert configured_pull_request_label(team.id) is None
+
+
+class TestApplyPullRequestLabel:
+ @pytest.mark.django_db
+ def test_the_configured_label_reaches_the_pull_request(self, org_and_team):
+ _, team = org_and_team
+ SignalTeamConfig.objects.update_or_create(
+ team=team, defaults={"pull_request_label_enabled": True, "pull_request_label": "ours"}
+ )
+ report = _make_report(team)
+ github = _labelling_github("ours")
+
+ with patch(
+ "products.signals.backend.pull_request_label.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ assert apply_pull_request_label(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) == "ours"
+
+ github.add_pull_request_labels.assert_called_once_with("PostHog/posthog", 123, ["ours"])
+
+ @pytest.mark.django_db
+ def test_a_team_that_did_not_opt_in_skips_github_entirely(self, org_and_team):
+ _, team = org_and_team
+ report = _make_report(team)
+
+ with patch(
+ "products.signals.backend.pull_request_label.GitHubIntegration.first_for_team_repository"
+ ) as mock_lookup:
+ assert apply_pull_request_label(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) is None
+ mock_lookup.assert_not_called()
+
+ @pytest.mark.django_db
+ @pytest.mark.parametrize(
+ "outcome",
+ [
+ Exception("boom"),
+ {"success": False, "error": "Failed to label pull request"},
+ {"success": True, "labels": []},
+ ],
+ ids=["raises", "reports_failure", "github_dropped_it"],
+ )
+ def test_a_github_failure_is_swallowed(self, org_and_team, outcome: object):
+ _, team = org_and_team
+ SignalTeamConfig.objects.update_or_create(team=team, defaults={"pull_request_label_enabled": True})
+ report = _make_report(team)
+ github = MagicMock()
+ if isinstance(outcome, Exception):
+ github.add_pull_request_labels.side_effect = outcome
+ else:
+ github.add_pull_request_labels.return_value = outcome
+
+ with patch(
+ "products.signals.backend.pull_request_label.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ assert apply_pull_request_label(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) is None
+
+ @pytest.mark.django_db
+ def test_a_report_from_another_team_is_not_touched(self, org_and_team):
+ org, team = org_and_team
+ other_team = Team.objects.create(organization=org, name="other-team")
+ SignalTeamConfig.objects.update_or_create(team=team, defaults={"pull_request_label_enabled": True})
+ report = _make_report(other_team)
+
+ with patch(
+ "products.signals.backend.pull_request_label.GitHubIntegration.first_for_team_repository"
+ ) as mock_lookup:
+ assert apply_pull_request_label(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) is None
+ mock_lookup.assert_not_called()
+
+
+class TestSchedulePullRequestLabel:
+ @pytest.mark.django_db(transaction=True)
+ @pytest.mark.parametrize(
+ ("pr_url", "pr_state", "expected"),
+ [
+ (PR_URL, SignalReportAssignment.PrState.OPEN, True),
+ (PR_URL, SignalReportAssignment.PrState.DRAFT, True),
+ (PR_URL, SignalReportAssignment.PrState.UNKNOWN, True),
+ (PR_URL, None, True),
+ # Nothing to find in a GitHub search, so the round trip is not worth queuing.
+ (PR_URL, SignalReportAssignment.PrState.CLOSED, False),
+ (PR_URL, SignalReportAssignment.PrState.MERGED, False),
+ (None, SignalReportAssignment.PrState.OPEN, False),
+ ],
+ ids=["open", "draft", "unknown", "null_state", "closed", "merged", "no_url"],
+ )
+ def test_only_a_live_pull_request_queues_work(
+ self, org_and_team, pr_url: str | None, pr_state: str | None, expected: bool
+ ):
+ _, team = org_and_team
+ report = _make_report(team)
+
+ with patch("products.signals.backend.tasks.label_implementation_pr.delay") as mock_delay:
+ schedule_pull_request_label(team_id=team.id, report_id=str(report.id), pr_url=pr_url, pr_state=pr_state)
+
+ assert mock_delay.called is expected
+
+ @pytest.mark.django_db(transaction=True)
+ def test_linking_a_pull_request_to_a_report_queues_the_label_once(self, org_and_team):
+ # The wiring guard: without it the whole feature can go dead with every unit test above
+ # still green, and a re-queue would label a pull request somebody unlabelled by hand.
+ _, team = org_and_team
+ report = _make_report(team)
+ user = User.objects.create(email="[email protected]")
+
+ with (
+ patch("products.signals.backend.tasks.label_implementation_pr.delay") as mock_delay,
+ patch(
+ "products.signals.backend.report_assignments.GitHubIntegration.first_for_team_repository",
+ return_value=None,
+ ),
+ ):
+ for _ in range(2):
+ claim_report(
+ report=report,
+ actor=ArtefactAttribution.from_user(user.id),
+ user=user,
+ was_impersonated=False,
+ pr_url=PR_URL,
+ release=False,
+ )
+
+ mock_delay.assert_called_once_with(team_id=team.id, report_id=str(report.id), pr_url=PR_URL)
diff --git a/products/signals/backend/test/test_signal_team_config_api.py b/products/signals/backend/test/test_signal_team_config_api.py
index a7877014116b..67479b073019 100644
--- a/products/signals/backend/test/test_signal_team_config_api.py
+++ b/products/signals/backend/test/test_signal_team_config_api.py
@@ -182,6 +182,22 @@ class TestSignalTeamConfigAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
assert response.json()["attr"] == "max_reports_per_day"
+ @parameterized.expand(
+ [
+ ("enable", {"pull_request_label_enabled": True, "pull_request_label": "ours"}, True, "ours"),
+ ("clear_name", {"pull_request_label": ""}, False, None),
+ ]
+ )
+ def test_update_pull_request_label(self, _name, sent, expected_enabled, expected_label):
+ response = self.client.post(self._url(), data=sent, format="json")
+ data = response.json()
+ assert response.status_code == status.HTTP_200_OK, data
+ assert data["pull_request_label_enabled"] is expected_enabled
+ assert data["pull_request_label"] == expected_label
+ self.config.refresh_from_db()
+ assert self.config.pull_request_label_enabled is expected_enabled
+ assert self.config.pull_request_label == expected_label
+
def test_reports_generated_today_is_zero_without_a_limit(self):
# No limit set: the count is never shown, so the serializer reports 0 without counting even
# when visible reports exist today.
@@ -325,3 +341,16 @@ class TestSignalTeamConfigSerializerValidation(SimpleTestCase):
serializer = SignalTeamConfigSerializer(data={"autostart_base_branches": value}, partial=True)
assert not serializer.is_valid()
assert "autostart_base_branches" in serializer.errors
+
+ @parameterized.expand([("blank", ""), ("whitespace", " "), ("null", None)])
+ def test_pull_request_label_normalizes_an_empty_name_to_null(self, _name, value):
+ # One stored shape for "use the default", so a team that clears the box does not save a
+ # name GitHub would refuse.
+ serializer = SignalTeamConfigSerializer(data={"pull_request_label": value}, partial=True)
+ assert serializer.is_valid(), serializer.errors
+ assert serializer.validated_data["pull_request_label"] is None
+
+ def test_pull_request_label_rejects_a_name_github_would_refuse(self):
+ serializer = SignalTeamConfigSerializer(data={"pull_request_label": "l" * 51}, partial=True)
+ assert not serializer.is_valid()
+ assert "pull_request_label" in serializer.errors
diff --git a/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx b/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx
index 01f51c783985..83cd0e252171 100644
--- a/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx
+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx
@@ -28,6 +28,9 @@ interface CardState {
projectPrReady?: boolean
/** Personal override for that, or null to follow the project ("Default"). */
myPrReady?: boolean | null
+ /** Whether the project labels self-driving PRs, and the name it labels them with. */
+ prLabelEnabled?: boolean
+ prLabel?: string | null
/** Connected integrations the issue tracker picker can choose from. */
integrations?: Record<string, unknown>[]
/** Integration id the project already tracks issues in, and where inside it they land. */
@@ -47,6 +50,8 @@ function useAutonomyMocks({
githubAssign = false,
projectPrReady = false,
myPrReady = null,
+ prLabelEnabled = false,
+ prLabel = null,
integrations = [],
issueTrackingIntegration = null,
issueTrackingConfig = {},
@@ -64,6 +69,8 @@ function useAutonomyMocks({
reports_generated_today: reportsToday,
daily_report_limit_reached: dailyLimit != null && reportsToday >= dailyLimit,
default_open_pull_request_ready: projectPrReady,
+ pull_request_label_enabled: prLabelEnabled,
+ pull_request_label: prLabel,
},
'/api/users/@me/signal_autonomy/': {
id: 'auto-1',
@@ -164,6 +171,12 @@ export const SettingsTabIssueTrackerJira: Story = {
),
}
+// The PR label turned on with a name of the team's own: the name input renders under the row.
+export const SettingsTabPullRequestLabel: Story = {
+ parameters: REDESIGN,
+ render: () => <SettingsCard width="wide" prLabelEnabled prLabel="agent-pr" />,
+}
+
// Master switch off in the Settings tab: the project threshold hides. Base branches and your own threshold stay.
export const SettingsTabDisabled: Story = {
parameters: REDESIGN,
diff --git a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
index 571c9b4e7d87..b9f2f6d13cbe 100644
--- a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
@@ -23,7 +23,12 @@ import { IntegrationType } from '~/types'
import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'
import { userAutonomyLogic } from '../../logics/userAutonomyLogic'
-import { PRIORITY_THRESHOLD_OPTIONS, SignalReportPriority } from '../../types'
+import {
+ DEFAULT_PULL_REQUEST_LABEL,
+ GITHUB_LABEL_NAME_MAX_LENGTH,
+ PRIORITY_THRESHOLD_OPTIONS,
+ SignalReportPriority,
+} from '../../types'
import { AutonomySettingGroup } from './AutonomySettingGroup'
import { AutonomySettingRow } from './AutonomySettingRow'
@@ -561,6 +566,58 @@ function GitHubIssueWritebackRow(): JSX.Element {
)
}
+/**
+ * Team-wide opt-in to labelling every self-driving pull request. Off by default, because the label
+ * lands on a repository the team shares with everybody. The name is only editable while the label
+ * is on, and a blank name saves as the default label rather than as no label.
+ */
+function PullRequestLabelRow(): JSX.Element {
+ const { pullRequestLabelEnabled, draftPullRequestLabel, savePullRequestLabelDisabledReason, teamConfigUpdating } =
+ useValues(signalTeamConfigLogic)
+ const { patchTeamConfig, setDraftPullRequestLabel, saveDraftPullRequestLabel } = useActions(signalTeamConfigLogic)
+
+ return (
+ <AutonomySettingRow
+ title="Label PRs on GitHub"
+ description="Add a label to every PR agents open, so you can find them in GitHub search and notification rules. PostHog creates the label if your repository does not have it."
+ control={
+ <LemonSwitch
+ checked={pullRequestLabelEnabled}
+ loading={teamConfigUpdating}
+ onChange={(enabled) => patchTeamConfig({ pull_request_label_enabled: enabled })}
+ aria-label="Label self-driving pull requests on GitHub"
+ data-attr="signals-pull-request-label-enabled"
+ />
+ }
+ >
+ {pullRequestLabelEnabled && (
+ <div className="flex items-center gap-2">
+ <LemonInput
+ size="small"
+ className="w-48"
+ placeholder={DEFAULT_PULL_REQUEST_LABEL}
+ maxLength={GITHUB_LABEL_NAME_MAX_LENGTH}
+ value={draftPullRequestLabel}
+ onChange={setDraftPullRequestLabel}
+ onPressEnter={saveDraftPullRequestLabel}
+ aria-label="Pull request label name"
+ />
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={saveDraftPullRequestLabel}
+ loading={teamConfigUpdating}
+ disabledReason={savePullRequestLabelDisabledReason ?? undefined}
+ data-attr="signals-pull-request-label-save"
+ >
+ Save
+ </LemonButton>
+ </div>
+ )}
+ </AutonomySettingRow>
+ )
+}
+
/**
* Per-user opt-in to being added as a GitHub assignee on the implementation PR for reports that
* suggest this user as reviewer. Off by default, because being assigned is visible to everybody on
@@ -766,6 +823,7 @@ export function SelfDrivingSection(): JSX.Element {
<BaseBranchesRow />
<ProjectPullRequestStateRow />
<GitHubIssueWritebackRow />
+ <PullRequestLabelRow />
<IssueTrackerRow />
</AutonomySettingGroup>
<AutonomySettingGroup
diff --git a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts
index 75ccc8787217..bd72d2d61d6d 100644
--- a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts
+++ b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts
@@ -36,14 +36,18 @@ export interface signalTeamConfigLogicValues {
draftBaseBranchRepo: string
draftIssueTrackerIntegrationId: number | null
draftMaxReportsPerDay: number | null
+ draftPullRequestLabel: string
githubIssueWritebackEnabled: boolean
issueTrackerConfig: Record<string, string>
issueTrackerIntegrationId: number | null
issueTrackerTargetPickerOpen: boolean
maxReportsPerDay: number | null
patchesInFlight: number
+ pullRequestLabel: string
+ pullRequestLabelEnabled: boolean
reportsGeneratedToday: number
saveMaxReportsPerDayDisabledReason: string | null
+ savePullRequestLabelDisabledReason: string | null
selectedIssueTrackerIntegrationId: number | null
teamConfig: SignalTeamConfig | null
teamConfigLoading: boolean
@@ -106,6 +110,9 @@ export interface signalTeamConfigLogicActions {
saveDraftMaxReportsPerDay: () => {
value: true
}
+ saveDraftPullRequestLabel: () => {
+ value: true
+ }
setBaseBranchPickerOpen: (open: boolean) => {
open: boolean
}
@@ -124,6 +131,9 @@ export interface signalTeamConfigLogicActions {
setDraftMaxReportsPerDay: (value: number | null) => {
value: number | null
}
+ setDraftPullRequestLabel: (value: string) => {
+ value: string
+ }
setIssueTrackerTargetPickerOpen: (open: boolean) => {
open: boolean
}
@@ -145,6 +155,8 @@ export interface signalTeamConfigLogicMeta {
maxReportsPerDay: (teamConfig: SignalTeamConfig | null) => number | null
defaultOpenPullRequestReady: (teamConfig: SignalTeamConfig | null) => boolean
githubIssueWritebackEnabled: (teamConfig: SignalTeamConfig | null) => boolean
+ pullRequestLabelEnabled: (teamConfig: SignalTeamConfig | null) => boolean
+ pullRequestLabel: (teamConfig: SignalTeamConfig | null) => string
issueTrackerIntegrationId: (teamConfig: SignalTeamConfig | null) => number | null
issueTrackerConfig: (teamConfig: SignalTeamConfig | null) => Record<string, string>
selectedIssueTrackerIntegrationId: (
@@ -158,6 +170,7 @@ export interface signalTeamConfigLogicMeta {
draftMaxReportsPerDay: number | null,
maxReportsPerDay: number | null
) => string | null
+ savePullRequestLabelDisabledReason: (draftPullRequestLabel: string, pullRequestLabel: string) => string | null
addBaseBranchOverrideDisabledReason: (
draftBaseBranchRepo: string,
draftBaseBranchBranch: string
@@ -200,6 +213,8 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
removeBaseBranchOverride: (repo: string) => ({ repo }),
setDraftMaxReportsPerDay: (value: number | null) => ({ value }),
saveDraftMaxReportsPerDay: true,
+ setDraftPullRequestLabel: (value: string) => ({ value }),
+ saveDraftPullRequestLabel: true,
setDraftIssueTrackerIntegrationId: (integrationId: number | null) => ({ integrationId }),
setBaseBranchPickerOpen: (open: boolean) => ({ open }),
setIssueTrackerTargetPickerOpen: (open: boolean) => ({ open }),
@@ -321,6 +336,18 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
: state,
},
],
+ // The label input's draft, anchored the same way as the daily limit above: seeded once on
+ // first load, and re-read from the server only when its own save settles.
+ draftPullRequestLabel: [
+ '',
+ {
+ setDraftPullRequestLabel: (_, { value }) => value,
+ patchTeamConfigSuccess: (state: string, { teamConfig, payload }) =>
+ payload?.patch && 'pull_request_label' in payload.patch
+ ? (teamConfig?.pull_request_label ?? '')
+ : state,
+ },
+ ],
}),
selectors({
// Master switch for autonomous inbox PRs: only an explicit false disables
@@ -353,6 +380,14 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
(s) => [s.teamConfig],
(teamConfig: SignalTeamConfig | null): boolean => teamConfig?.github_issue_writeback_enabled ?? false,
],
+ pullRequestLabelEnabled: [
+ (s) => [s.teamConfig],
+ (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.pull_request_label_enabled ?? false,
+ ],
+ pullRequestLabel: [
+ (s) => [s.teamConfig],
+ (teamConfig: SignalTeamConfig | null): string => teamConfig?.pull_request_label ?? '',
+ ],
issueTrackerIntegrationId: [
(s) => [s.teamConfig],
(teamConfig: SignalTeamConfig | null): number | null => teamConfig?.issue_tracking_integration ?? null,
@@ -392,6 +427,13 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
return draftMaxReportsPerDay === maxReportsPerDay ? 'No changes to save' : null
},
],
+ // Doubles as the save button's tooltip, in the same shape as the daily limit above. A blank
+ // name is a valid save: it means "use the default label".
+ savePullRequestLabelDisabledReason: [
+ (s) => [s.draftPullRequestLabel, s.pullRequestLabel],
+ (draftPullRequestLabel: string, pullRequestLabel: string): string | null =>
+ draftPullRequestLabel.trim() === pullRequestLabel.trim() ? 'No changes to save' : null,
+ ],
// Doubles as the add button's tooltip, so what blocks the add is stated once rather than
// derived separately for the guard and for the copy.
addBaseBranchOverrideDisabledReason: [
@@ -457,12 +499,21 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
}
actions.patchTeamConfig({ max_reports_per_day: values.draftMaxReportsPerDay })
},
+ saveDraftPullRequestLabel: () => {
+ // Same double-submission guard as the daily limit above: Enter bypasses the button's
+ // own disabled state, and a save must not race a concurrent GET or PATCH.
+ if (values.savePullRequestLabelDisabledReason || values.teamConfigLoading) {
+ return
+ }
+ actions.patchTeamConfig({ pull_request_label: values.draftPullRequestLabel.trim() || null })
+ },
loadTeamConfigSuccess: ({ teamConfig }) => {
- // Seed the draft from the server only on the first load, so a later reload (e.g. the
+ // Seed the drafts from the server only on the first load, so a later reload (e.g. the
// one triggered when an unrelated setting's save fails) can't wipe an unsaved edit.
- if (!cache.maxReportsDraftSeeded) {
- cache.maxReportsDraftSeeded = true
+ if (!cache.draftsSeeded) {
+ cache.draftsSeeded = true
actions.setDraftMaxReportsPerDay(teamConfig?.max_reports_per_day ?? null)
+ actions.setDraftPullRequestLabel(teamConfig?.pull_request_label ?? '')
}
},
patchTeamConfigSuccess: ({ payload }) => {
diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.ts
index bc600339fcc3..a61d3d543ab7 100644
--- a/products/signals/frontend/inbox/types.ts
+++ b/products/signals/frontend/inbox/types.ts
@@ -53,6 +53,12 @@ export interface EnrichedReviewer {
explanation?: string | null
}
+/** What the backend labels a self-driving PR with when the team turns the label on without naming one. */
+export const DEFAULT_PULL_REQUEST_LABEL = 'self-driving'
+
+/** GitHub's own cap on a label name, mirrored so the input stops where the API would reject. */
+export const GITHUB_LABEL_NAME_MAX_LENGTH = 50
+
/** P0 (highest) – P4 (lowest). Mirrors desktop `SignalReportPriority`. */
export type SignalReportPriority = 'P0' | 'P1' | 'P2' | 'P3' | 'P4'
@@ -413,6 +419,10 @@ export interface SignalTeamConfig {
default_open_pull_request_ready?: boolean
/** Whether self-driving comments a link to the report back on a GitHub issue that raised it. */
github_issue_writeback_enabled?: boolean
+ /** Whether self-driving labels every PR it opens, so GitHub search can separate them from other bot work. */
+ pull_request_label_enabled?: boolean
+ /** The label name to apply, at most 50 characters. Null or blank means the default label. */
+ pull_request_label?: string | null
/** Read-only: reports that first became visible today (project timezone). Never send in a patch. */
reports_generated_today?: number
/** Read-only: whether the daily report limit is reached, pausing new report generation until local midnight. Never send in a patch. */