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(self-driving): pause report generation at a per-team daily limit (#80527)

Alex Lebedev597575fa30f1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b30140cfbebd..8193cce8eb97 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1900,18 +1900,6 @@ snapshots:
hash: v1.k794b7964.50a5102fcd24dd52bb07a41a78e6685486895d9ed86923b857de67a2bf0cfa25.yhotsOneF2mgB_iFToEVdcMfHQf58lr7yldfNN-ZYbU
components-sharing--recording-sharing-licensed--light:
hash: v1.k794b7964.887ed3d23b03515cab22e56f2258a1f1f7be9b7b69c1b5f3e17db17b6c05b4db.XWPlz4WofkRpUrTptzJ_y3K-quE1bDXIBkc2F5gq2wk
- components-skillpicker--default--dark:
- hash: v1.k794b7964.42e480d1854fa4e855c514aa6cb4e0adebde88d01cccd1b802b6a2acba0ccfd3.zWHBN45jGiaWgIUoC6ZoTFd9RLQ9LxAZ5x5szvvO2aE
- components-skillpicker--default--light:
- hash: v1.k794b7964.cbbe33adfd71b1c432b64dfd92a343c2d562c2e64910d07fff58ff5a4cd926e7.utWGHbQe8EqWV_0Kb54dtyiG1QM_W4-HgVcJ8m6Sys4
- components-skillpicker--empty--dark:
- hash: v1.k794b7964.4502f6dbefd7848a18c884a205d5da9ccd1cc1b5ee65717fbbbb8fb07a7202bf.-IXKQW55ul9arMOKU0fHgh1-ppUfSpvYTJLOKg5rwxM
- components-skillpicker--empty--light:
- hash: v1.k794b7964.834f1daaa1c90c821674ed0d47d6a8cfe3fe2d92b8c5ba68f2a600383ec439ab.QEFmzIl_TfqoJYnNbyst2sFrixFceJNgdiEDxg3o0v8
- components-skillpicker--loading--dark:
- hash: v1.k794b7964.a6c03e74d88d7915ee632eb41078032b6a0ed2b7d2076e3824843ee0504c5184.sPVYxnzC5p8USLUKFktTDgFn9IKoZAr3p8LQ9q2HT1Q
- components-skillpicker--loading--light:
- hash: v1.k794b7964.1f11b533447e94851d7036d383a6c200445f7da972d711558cc3f7dba15819ea.hwvMJBLynPWX3xaxY8wXIxncAKZm74pJ_0khYfYWbes
components-slack-channel-picker--alphabetical--dark:
hash: v1.k794b7964.c5f45d681dad559cdf8bed1c8e9d31c5dca4d0973e1fbf5d1515ab30c393b554.SYg7auYBsl2kTK9lzMylWzKKRJ9Bf3sT0lwtvlfXx24
components-slack-channel-picker--alphabetical--light:
@@ -5100,10 +5088,6 @@ snapshots:
hash: v1.k794b7964.4344045fc1bada8b4f2067de9f83cdb38b5dbe14719e7b4d332c2a7689a5d8cd.NvfJs1mb9VLArjiQdsrspse5hcopmjfyz4HXvwD_MZA
products-data-modeling-lineage-graph--single-node--light:
hash: v1.k794b7964.965d630c09110769bac58d2fc162856dc5303d9a98e97995aec4cc48098581da.Gi_VbiOcJVaHaHybXL8911KOWXwBMAGtbHwCIA2HO0E
- products-mcp-analytics-routingbar--all-variants--dark:
- hash: v1.k794b7964.769a69526cf676447319f587f24ed0d2670a137098867f8d3ee87ebda3415a70.3FGS0pbxxcrZUSto8SNCNHEkxaFXH6T8shqpdg5zzlQ
- products-mcp-analytics-routingbar--all-variants--light:
- hash: v1.k794b7964.7f57dacddb48fbad29a8614127d42d54425501b1f7755423d84316e1e937720e.thYPF2z3eMW5QvSe5SnvYtn35l6UCvUtsyx9EBLeqxk
products-posthog-ai-composer--default--dark:
hash: v1.k794b7964.4ccf5eb666de2b3315dc3f142ded80b445748d58ce8ae2d7d154272d7b194b3b.E61uR16UwC5qC1XkQquxMh1z3bonN6IYLdYDyzcorTA
products-posthog-ai-composer--default--light:
@@ -6601,25 +6585,25 @@ snapshots:
scenes-app-inbox-pullrequestdiffview--truncated--light:
hash: v1.k794b7964.58a507666519d2ad2f2a5247605b2c903180639eae9e43580992de250bc8f258._lKwsnOWccjuN6S_pd8IgOfKLzqnIvVqmTh1uETW-TY
scenes-app-inbox-scene--empty--dark:
- hash: v1.k794b7964.37705b8ab767e1c52a18fa3759cdde234d8dedd7a57bb03c7ad0396c7531f602.D2jNHc3iW6nIAvhAO5XuVCNAgCpk-URO2YKfROisz3Q
+ hash: v1.k794b7964.0ad2f75ebedc624b22f133e6a0f13029f38f852c9b9352097ab30f0bf0579c12.mib-SmbJSkBFXJ9nfN2ioPlAMzIM_hBLyIYqSA-HEGg
scenes-app-inbox-scene--empty--light:
- hash: v1.k794b7964.f7edb21a2afcad5f2af8e440b0dbe23ac55be93c4d5166f1f225c1e6f41e365c.5r4NDhjB9-Np5FEplm9lHFLUTAnF6dgZFDaANsKPfzs
+ hash: v1.k794b7964.9820d78cb1c295df66614ab1541c2dda1eddf1fd17342a3fdc1fd7c68ae61e8e.JkchAuApudEhTPKLZSvWDf7EUajC9OW-qALMqvSGqhY
scenes-app-inbox-scene--empty-control--dark:
- hash: v1.k794b7964.99ffca71975a423bd8ef679c361fd0bf4b9a1f6be6d4f4dfe82b69a9637184af.NwEat2sZEU9_PcNSbsxCt1SZBzTzyQJbewP-ZpJZOM4
+ hash: v1.k794b7964.7026f82719bece1b73fff37eda954ed63a06b6c20cd4c3a3604d3b84e139899a.qr3ivSeEUaCyuy7w5o98RMEV6BDZNwrSxjSoPOnp0kQ
scenes-app-inbox-scene--empty-control--light:
- hash: v1.k794b7964.897cfada57cb1060860335179b5f5d10d33399f095e30ffa6a5902e188905977.VxZJrOI1PpjGafyt7ExIH6RjhtapLZ36twmDzUMFcts
+ hash: v1.k794b7964.8451c68df29f044c70ce1ec34492c1bf4b7a80e89a89cf798aa8f1dbf01cd668.gkZKg3PbA9fHJCWKngizcUdKaFh-LcN6zBNt_hSxI7Q
scenes-app-inbox-scene--empty-with-many-scouts--dark:
- hash: v1.k794b7964.32ea8aa91e71baa9a72b403c44731aa97bff8282b6bd9d5041b4537a50825060.G9RYZ-ZdAGxc4hcvryNgiAmH5xsqtHIj8mjKeXCZpJI
+ hash: v1.k794b7964.a4bff8ba221af57f4f49de836d7ed1aab25cb687b7e7e24cbcb544d7511b786d.ghRFWu5WTdS_1kUQyEomrkOmy_2k2RwgwcVr6z-a28M
scenes-app-inbox-scene--empty-with-many-scouts--light:
- hash: v1.k794b7964.57cc628441b89eaebc408c9c0103615965dcfd9ba4c8b8e62b6de53763f3343c.3OXdEJ2GFbqX23EOaks1SZLNZJzdXhhysDckPTnKqF4
+ hash: v1.k794b7964.e3936882749d02b16ed1a9be7d7e1045b788683ebd69a720021ea5e8038a3bef.l6QVKp-YBTtOvqFO-5nvFC6k00tHbkHPQF7PY24n0sc
scenes-app-inbox-scene--inbox--dark:
- hash: v1.k794b7964.0beabde23d6c1b441381441eae381cc3b75c1c87e7511dbdbf27579284dc8458.frvNIv5YQ_5dLqKjcABKe8thfDL5r7zAg9EB2zIg6Tg
+ hash: v1.k794b7964.f87779561e781fdd856d1de278526379745f4b7bb7edeb6cdc213f610cb90fc2.e9uWuxp8WGvpZg6O7hNOpBRCSlHT_l-i53KHQEdg1so
scenes-app-inbox-scene--inbox--light:
- hash: v1.k794b7964.169f79bb4a23b7d0fcfbf2ac628f260f14d3eac0c2c9b8d2b7755e3a128cbc9a.mUcDXxMkiNpj6eX6kFsunHypIwvAbDEXl4G7TwjyEKQ
+ hash: v1.k794b7964.dac3137c969a923620cc7e50fd0da59106fbbb5ea3c704b990951c5838460e7c.otkoPWxN1w8vy_iQJzY7TyTLtlHWqnC7IFOY-jJRxIg
scenes-app-inbox-scene--installing-self-driving--dark:
- hash: v1.k794b7964.d2c648fd6ea8079c6746f4b5e979cac53dbd928dd06990c3bac2031eeaba12be.rCs94UBn0krUWBSp28BM_f7Jo4Smc85JTXR_iWzDjoY
+ hash: v1.k794b7964.c915d26296f861e966bb7bd499770b3884cf209aa3aee33ad7d69a1f52c4f83e.Jb_jQKLNaVLxZzFvmZHASF3ZLPc2g3u3x3yWo0Ma9jQ
scenes-app-inbox-scene--installing-self-driving--light:
- hash: v1.k794b7964.86ee9cce8a3aae137acfc651445d7f777b7f98b3e74cc2c446acfcd516d36650.RZNC9GzqeEgKiAyww54tPExJ_N2htL9xhS5SZN-pqb4
+ hash: v1.k794b7964.2736e1045394621b6ec414c1d3e3be6110761d0384342b163e8b96f9fa09906f.8vselD6-BxJmaDUkmmW5NZLhBHwDfbscy4s7foAaLw0
scenes-app-inbox-scene--self-driving-onboarding--dark:
hash: v1.k794b7964.7602d02fad26586f0a4773abe0fbe76ad39c625403c7648ec58ff711aa38d3a0.9ssGMF2bvYFiK299rvJqLc9mbtZk4SeJHRoWnZP3Ed8
scenes-app-inbox-scene--self-driving-onboarding--light:
@@ -6629,9 +6613,9 @@ snapshots:
scenes-app-inbox-scene--self-driving-onboarding-redesign--light:
hash: v1.k794b7964.c2f7366b673e20e85513c454effae314d643958a3d2424e7902d572909f024fe.edek45zj8tVjVDjsqgddUJUnPKAHanQkzZwR5Ylr93Q
scenes-app-inbox-scene--self-driving-paused--dark:
- hash: v1.k794b7964.eeca301ecb9187530927aaffe528d39c6c2d253c731874becf8b263403b48f5f.dhsAVx9cMh9aRd6gpLIfLdcoirP4Gm2dxnVKTXMGNa8
+ hash: v1.k794b7964.415a715fef6f3896f413b020f4ca02e88b39a735e37bd885fc4db01812ebc6ba.hFi9pA_9sgxJHtaQJZ42TKHd9F1VwNcdH1Dt--5iXlk
scenes-app-inbox-scene--self-driving-paused--light:
- hash: v1.k794b7964.1964d5a373f26307958762d2d52d74593208ca9ec11730504196965e80e406ac.KNUTy0x2lHem99RNyYXCEurDjrhpRLzNb8MN4TyaazE
+ hash: v1.k794b7964.01d24a36e380fcc693f1177be16250e41758dda6a563430951e8797eadc4d16b.aOpiy6Xt1It_d_IWoBvD-Gj4o6OcS7uj5c9AGAPyZ80
scenes-app-inbox-scene--self-driving-verdict-pending--dark:
hash: v1.k794b7964.570e5dddd645996b94ff94b2c563b32ced3793db3ab5ccf360d16126af3b9a0b.WC_VEZ1N_iX-o4r11w15QWfD8Nzo1gFerTznKiaIX84
scenes-app-inbox-scene--self-driving-verdict-pending--light:
@@ -6644,6 +6628,18 @@ snapshots:
hash: v1.k794b7964.cb0a021303b103cdcd037db93be44c2c5eae3e59494ab8a726ac8e430f631dfd.n4BzfjRbtrkqXUS8HZwDAYrPQHYDeqCHuny9Z4Oz134
scenes-app-inbox-scoutmcpserverspicker--scout-settings-variant--light:
hash: v1.k794b7964.2f1013abc412adb4544bca6a00209d3051c46969db69d4242ab201ecf5d189f3.YVfbrzpaRzPwuCbeFXmaVOLla0fvhHmAm1CkuaKWCLI
+ scenes-app-inbox-selfdrivingsection--daily-limit-reached--dark:
+ hash: v1.k794b7964.1c66805b017d17b972c7f2087c5dd5ff8c3786b6f3fb8de392be7dd104d6ff08.QA9Y-ugEGeof2DmhSKh-8_XIhHNs8zDop5mxpvAw3MQ
+ scenes-app-inbox-selfdrivingsection--daily-limit-reached--light:
+ hash: v1.k794b7964.0a9662258b26de858adf892fb57d448708c3c109d95397fd9b8b43e149beedfb.RCtt2_oTo8Dl6_DvoVI5a6DX3oZAl_I_FLuR6rrdGPs
+ scenes-app-inbox-selfdrivingsection--daily-limit-set--dark:
+ hash: v1.k794b7964.5e8720c385b5d6b26c29b5bff1e1408341b305ab836fb377f1ad239d7e01da23.BAc99v0vHySowl6lt-pzy-pz9jH7YCJg8K2dLAujmAE
+ scenes-app-inbox-selfdrivingsection--daily-limit-set--light:
+ hash: v1.k794b7964.da6d44c3f4d9145ddde963782dff324dbaffcc75733a3fe36788edc933209113.JjBq85JA3bQXn-pcxWrBjSuWXWg1i_JMI7Jv_8sQRMI
+ scenes-app-inbox-selfdrivingsection--no-daily-limit--dark:
+ hash: v1.k794b7964.28ebf053aeb32195bed7e807ce392421e4d868aa15b586adff4bb3e87ba8dd4d.kNonsXQTUtmjUENAkILZ6GxiNYSzbrwsGVUO1JsT4LQ
+ scenes-app-inbox-selfdrivingsection--no-daily-limit--light:
+ hash: v1.k794b7964.43ea36c62cc52aee144962728c9f2154abdba60ef2bf4fbe27af3354b5d9e453.3C0_jNnQcJDu5OyXOA94-wmooR0wSAoqZ4nTMYO1FrQ
scenes-app-inbox-signalsourcespanel--armed-but-tools-off--dark:
hash: v1.k794b7964.ece1c0e16e4970e264f483296aaee56c6e8f271ffd8149c414ae314b1a72c866.kfMXUu0-mbkWvrPMsm0GPuPwIdcSt9t7DfNYHby-X0I
scenes-app-inbox-signalsourcespanel--armed-but-tools-off--light:
@@ -8104,18 +8100,6 @@ snapshots:
hash: v1.k794b7964.924843ea467d84943495cc8a3056c6f469da31ea69ed097cb485f6348410f77e.qyTPRNCs1NnpxcMQ3t1SthuCpSr4_HIXQXDtWL-QdwQ
scenes-other-billing-billinglinegraph--with-marker-at-range-start--light:
hash: v1.k794b7964.5948fea6ef855d327f6d59f1ed10eb3fd55808540eda078bee5fed552523a4c0.FTXekbDFuL1YE5ad9VyyBtq5lOBiNalah41lHdISQOE
- scenes-other-billing-desktopusagebreakdown--no-usage--dark:
- hash: v1.k794b7964.c4a269e9294e2a91457f55f61c92fd7a2be76bd01697be8110a6a521ffe4e259.zVql89Qrf4TpYEZLsF8P0YBEmeSWfjWu3ug_Vn05TNE
- scenes-other-billing-desktopusagebreakdown--no-usage--light:
- hash: v1.k794b7964.52c84b283c7c7a66a3dff631676a4f38f2638ae40797d521b026c0af162ae865.EtK9KPsvnlS8w6lGGNaBV5xFWxySGm5viXNk9JWHegA
- scenes-other-billing-desktopusagebreakdown--resources-unavailable--dark:
- hash: v1.k794b7964.8dffd1fbfec28d0acf7f1cfacac16498ccefbea6cf0a36fe95b3bff9298a38f9.8OOExOg6aw4wbIPCEB25pSMwoMC4eqFt1KIZiyDD2zE
- scenes-other-billing-desktopusagebreakdown--resources-unavailable--light:
- hash: v1.k794b7964.cee76c88340ad14f6123d80e03faa8b0fa30cd8229a8a1f3f882bfdd2f5fbe4a.HoHDeKm6rYX-Sl3uPkZo1mstXYtwF-bMWHMMbcUSAoM
- scenes-other-billing-desktopusagebreakdown--usage-mix--dark:
- hash: v1.k794b7964.2c28449c679f7e5e89ec05fd6d681ddebbf9b031102a88ab08cd975e555b919f.YK_K1fOZZ8wYf8qvJlLRXZuKd31GnNaEhiKJOm0hci0
- scenes-other-billing-desktopusagebreakdown--usage-mix--light:
- hash: v1.k794b7964.a78b7addf891aa84f730a810d99c8e34c048b49fd8a489e755ed064cb64ebe68.ssx9pdKw8PVqxdqpUcP7LZ-9gNLa11vNHRoy6Uzg94Q
scenes-other-billing-product--billing-product-inclusion-only-with-addon--dark:
hash: v1.k794b7964.ce05ab37980f7fc148ea8681fee7b0eeb1f046266e8a7df22fbfc5cc8cefb8e7.hjk8pf9SicO_kBVjVXooUrPaBUj_76AzOPVXuwydGkE
scenes-other-billing-product--billing-product-inclusion-only-with-addon--light:
diff --git a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt
index 75e50e0c798d..e68a15b7e624 100644
--- a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt
+++ b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt
@@ -18,6 +18,7 @@ replay_vision.0073_rebackfill_usage_scanner_id
replay_vision.0070_backfill_usage_scanner_id
tasks.0088_backfill_task_search_documents
tasks.0092_backfill_task_last_activity_at
+signals.0099_backfill_first_visible_at
# Does run CONCURRENTLY, one index per sourcebatch partition, but from RunPython
# (the partition list is only known at runtime), which the type-based check can't see.
warehouse_sources_queue.0008_sourcebatch_superseded
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 3aa98bbcc350..feaa686d2001 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -1593,7 +1593,7 @@
5 products/customer_analytics/backend/temporal/calendar_sync.py
5 products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.py
5 products/notebooks/backend/kernel_runtime.py
-5 products/signals/backend/temporal/buffer.py
+4 products/signals/backend/temporal/buffer.py
5 products/tasks/backend/temporal/execute_sandbox/workflow.py
6 posthog/dags/deletes.py
6 posthog/hogql/base.py
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index f0dfbaadad13..2f5accf5b1aa 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -394,23 +394,24 @@ any (except deleted) → deleted
any (except deleted) → suppressed
```
-| Field | Type | Description |
-| ----------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `team` | FK → Team | Owning team |
-| `status` | CharField | One of: `potential`, `candidate`, `in_progress`, `pending_input`, `ready`, `failed`, `deleted`, `suppressed` |
-| `total_weight` | Float | Sum of all assigned signal weights (reset to 0 if deemed not actionable) |
-| `signal_count` | Int | Number of signals assigned |
-| `title` | Text (nullable) | LLM-generated title (set during matching or summarization) |
-| `summary` | Text (nullable) | LLM-generated summary |
-| `error` | Text (nullable) | Error message if failed, or reason if pending input / reset to potential |
-| `signals_at_run` | Int | **Forward-looking promotion threshold.** A `potential` or `ready` report will not be (re-)promoted to `candidate` until `signal_count >= signals_at_run`. Defaults to 0, so fresh reports always pass immediately. Advanced by 3 each time a summary run starts, preventing the report from immediately re-promoting. Snoozing sets this to `signal_count + N`, pushing the threshold forward by an additional N signals. |
-| `run_count` | Int | How many times the summary workflow has run for this report. Incremented on each `candidate → in_progress` transition. Used in the Temporal workflow ID to give re-promoted reports a unique execution ID. |
-| `promoted_at` | DateTime (nullable) | When report was promoted to `candidate` (cleared on reset to potential) |
-| `last_run_at` | DateTime (nullable) | When summary workflow last ran |
-| `conversation` | **DEPRECATED** | Was: FK → Conversation. Wrapped in `deprecate_field()` |
-| `relevant_user_count` | **DEPRECATED** | Was: Int for relevant user count. Wrapped in `deprecate_field()` |
-| `cluster_centroid` | **DEPRECATED** | Was: ArrayField(Float) for video segment clustering. Wrapped in `deprecate_field()` |
-| `cluster_centroid_updated_at` | **DEPRECATED** | Was: DateTime for centroid freshness. Wrapped in `deprecate_field()` |
+| Field | Type | Description |
+| ----------------------------- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `team` | FK → Team | Owning team |
+| `status` | CharField | One of: `potential`, `candidate`, `in_progress`, `pending_input`, `ready`, `failed`, `deleted`, `suppressed` |
+| `total_weight` | Float | Sum of all assigned signal weights (reset to 0 if deemed not actionable) |
+| `signal_count` | Int | Number of signals assigned |
+| `title` | Text (nullable) | LLM-generated title (set during matching or summarization) |
+| `summary` | Text (nullable) | LLM-generated summary |
+| `error` | Text (nullable) | Error message if failed, or reason if pending input / reset to potential |
+| `signals_at_run` | Int | **Forward-looking promotion threshold.** A `potential` or `ready` report will not be (re-)promoted to `candidate` until `signal_count >= signals_at_run`. Defaults to 0, so fresh reports always pass immediately. Advanced by 3 each time a summary run starts, preventing the report from immediately re-promoting. Snoozing sets this to `signal_count + N`, pushing the threshold forward by an additional N signals. |
+| `run_count` | Int | How many times the summary workflow has run for this report. Incremented on each `candidate → in_progress` transition. Used in the Temporal workflow ID to give re-promoted reports a unique execution ID. |
+| `promoted_at` | DateTime (nullable) | When report was promoted to `candidate` (cleared on reset to potential) |
+| `last_run_at` | DateTime (nullable) | When summary workflow last ran |
+| `first_visible_at` | DateTime (nullable) | **Set-once**: when the report first became user-visible (entered `ready` or `pending_input`, the statuses the inbox lists). Stamped by `transition_to()` for pipeline reports and by `create_scout_report` for scout reports born visible; never cleared, so re-research and suppress/restore cycles don't recount it against `SignalTeamConfig.max_reports_per_day`. Null for reports that predate the field or never surfaced. |
+| `conversation` | **DEPRECATED** | Was: FK → Conversation. Wrapped in `deprecate_field()` |
+| `relevant_user_count` | **DEPRECATED** | Was: Int for relevant user count. Wrapped in `deprecate_field()` |
+| `cluster_centroid` | **DEPRECATED** | Was: ArrayField(Float) for video segment clustering. Wrapped in `deprecate_field()` |
+| `cluster_centroid_updated_at` | **DEPRECATED** | Was: DateTime for centroid freshness. Wrapped in `deprecate_field()` |
**Indexes:** `(team, status, promoted_at)`, `(team, created_at)`
@@ -970,6 +971,7 @@ All events use `distinct_id = team.uuid` and `groups(organization, team)`. Per-s
- `signal_assigned_to_report` — grouping assigned the signal (+ `report_id`, `is_new_report`, `promoted`)
- `signal_report_reresearch_skipped` — signal hit an already-researched report past the re-research cap, so no new run spawned (+ `report_id`, `signal_count`, `status`, `threshold`). Fires per suppressed signal
- `signal_report_quota_paused` — a quota gate observed the team's org over its self-driving credits limit (+ `stage`: `promotion` | `summary_entry` | `pre_repo_selection` | `pre_research` | `autostart` | `manual_create` | `task_create` | `implementation_run`, `enforced`, `report_id`). See Billing limit enforcement
+- `signal_report_daily_limit_paused` — a gate paused work because the team hit its `max_reports_per_day` (+ `stage`: `ingestion` | `scout_run` | `promotion` | `summary_entry` | `pre_repo_selection` | `pre_research`, `limit`, `reports_today`, `report_id` nullable). See Per-team daily report limit
- `signal_report_started` — report run began (+ `report_id`, `signal_count`, `run_count`, `source_products`)
- `signals_repo_research_started` / `signals_repo_research_completed` — repo selection stage (+ `report_id`, `result`: `reused` | `selected` | `no_repo` | `failed`, optional `failure_reason`: `no_github_integration` | `agentic_activity_error`)
- `signal_report_completed` — terminal per run (+ `result`: `ready` | `failed` | `pending_input` | `not_actionable`, optional `failure_reason`)
@@ -1226,6 +1228,40 @@ and a `ready` report's implementation starts only when a later research cycle re
**Telemetry:** every gate observation emits `signal_report_quota_paused` with `stage`, `enforced`, `report_id` (null at stages without one), `team_id`, and `organization_id`.
Promotion-stage events are emitted only when the signal would actually have promoted the report, so the volume measures withheld summary runs.
+### Per-team daily report limit
+
+A second, independent pause with the same shape as the billing gates: `SignalTeamConfig.max_reports_per_day` caps how many reports may surface to a team's inbox per day.
+Users who get more reports than they can read stop reading them, so once the cap is reached the whole generation pipeline stops — as early as ingestion, so no money is spent on work nobody will see — until the day resets.
+Implemented in `backend/daily_limit.py`, a sibling of `quota.py` that may import the signals models (it is not on the `billing.py` ← `usage_report` ← `quota_limiting` early-import path that keeps `quota.py` model-free).
+
+- **Count basis:** a report counts when it **first becomes user-visible** — its first transition into `ready` or `pending_input`, the statuses the inbox lists — recorded by the set-once `SignalReport.first_visible_at` timestamp.
+ Re-research of an already-visible report never recounts; failed and not-actionable runs never count.
+ `transition_to()` stamps pipeline reports; `create_scout_report` stamps scout report-channel reports born directly in a visible status.
+- **Day boundary:** midnight in the **project timezone** (`team.timezone_info`, via `team_day_start()`), unlike the billing quota's UTC `get_current_day()`.
+ This is a user-experience cap, so the day follows how the team perceives "today's reports".
+- **Scope and default:** per team, `null` = unlimited.
+ There is no enforcement flag: setting the field (via `signals/config/` or the inbox usage rail) is the opt-in, so `DailyReportLimitGate` has no `enforced` split — `limited` alone blocks.
+
+Gate table (the same sites as the billing gates; each activity body resolves `daily_report_limit_gate(team)` next to the billing check, so no workflow command sequences changed and no new `workflow.patched` markers exist):
+
+| Stage | Where | Behavior when the limit is reached |
+| ------------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------- |
+| ingestion | `check_signals_quota_limited_activity` (buffer flush) | Batch dropped before safety filter / flush; drop metric reason `daily_report_limit` |
+| scout runs | `run_signals_scout_activity` + manual-trigger API | Run skipped (`skip_reason="daily_report_limit"`) / trigger returns 429 |
+| `promotion` | `assign_and_emit_signal_activity` | Signal still assigned, weighted, and emitted, but no summary run spawns; status untouched |
+| `summary_entry` / `pre_repo_selection` / `pre_research` | `check_report_quota_gate_activity` | Same pause + revert semantics as the billing gates above |
+
+The implementation-side gates (`autostart`, `manual_create`, `task_create`, `implementation_run`) deliberately stay billing-only: implementing an already-generated report adds nothing new to read.
+Research runs already in flight when the cap is hit finish and surface — money already spent should show results — so a day can overshoot the cap by the handful of concurrent runs; the gate is a pre-check, never a serialized reservation.
+Billing-exempt reports count toward and are paused by the limit, matching the billing gates' blanket posture.
+Resume is organic, exactly like the billing pause: after local midnight (or when the field is raised/cleared) the gates simply start passing again — dropped signals are gone, suppressed candidates re-promote on their next matching signal, and scouts run on their next coordinator tick.
+Every check fails open (metric `signals_daily_limit_check_failed_open_total`).
+
+**Telemetry:** each gate emits `signal_report_daily_limit_paused` with `stage` (`ingestion` | `scout_run` | `promotion` | `summary_entry` | `pre_repo_selection` | `pre_research`), `limit`, `reports_today`, `report_id` (null at pre-report stages), `team_id`, and `organization_id`.
+No `enforced` property: every event is a real block.
+Unlike the billing gates, the ingestion and scout stages do emit (with `report_id=null`) — the limit is user-set and the volume is bounded by the team's own signal flow, and the events answer "why did nothing arrive today".
+Promotion-stage events keep the billing discipline of firing only when the signal would have promoted; both events fire independently when both limits bind.
+
---
## Data Types (`backend/temporal/types.py`)
@@ -1312,6 +1348,7 @@ products/signals/
├── backend/
│ ├── admin.py # Django admin for SignalReport + SignalReportArtefact
│ ├── api.py # emit_signal() entry point + source/org guards
+│ ├── daily_limit.py # Per-team daily report limit gate (max_reports_per_day)
│ ├── apps.py # Django app config
│ ├── models.py # SignalReport, SignalReportArtefact, SignalTeamConfig, SignalUserAutonomyConfig, SignalReportTask, SignalSourceConfig, SignalScoutConfig, SignalScoutRun, SignalScratchpad, SignalProjectProfile, SignalEmissionRecord
│ ├── serializers.py # DRF serializers for source configs, reports, artefacts, team config, user autonomy config
diff --git a/products/signals/backend/custom_agent/persistence.py b/products/signals/backend/custom_agent/persistence.py
index 9fc1ae6d4e83..e7da703da36f 100644
--- a/products/signals/backend/custom_agent/persistence.py
+++ b/products/signals/backend/custom_agent/persistence.py
@@ -4,6 +4,7 @@ from collections.abc import Sequence
from dataclasses import dataclass
from django.db import transaction
+from django.utils import timezone
from products.signals.backend.artefact_schemas import ArtefactContent, SuggestedReviewers
from products.signals.backend.custom_agent.schemas import CustomAgentFinalReport
@@ -43,6 +44,9 @@ def create_custom_agent_ready_report(
summary=final_report.description,
signal_count=0,
total_weight=0.0,
+ # Born directly READY without passing through transition_to (which stamps this for
+ # pipeline reports), so the daily report limit counts it from creation.
+ first_visible_at=timezone.now(),
)
# Written through the model helpers (the single artefact write path). Auto-start is
diff --git a/products/signals/backend/daily_limit.py b/products/signals/backend/daily_limit.py
new file mode 100644
index 000000000000..f0483a4db0e7
--- /dev/null
+++ b/products/signals/backend/daily_limit.py
@@ -0,0 +1,124 @@
+"""Per-team daily report limit enforcement.
+
+Sibling of `quota.py` (the org-level billing quota gate) with the same fail-open posture, but a
+separate module because this gate needs the signals models: `quota.py` sits on the
+`billing.py` <- `posthog.tasks.usage_report` <- `ee.billing.quota_limiting` early-import path and
+must stay model-free, while nothing on that path imports this module.
+
+The limit is `SignalTeamConfig.max_reports_per_day` (null = unlimited). A report consumes the
+limit when it first becomes user-visible, which `SignalReport.first_visible_at` records; "today"
+is the project-timezone calendar day. There is no enforcement flag: setting the field is the
+opt-in.
+"""
+
+from dataclasses import dataclass
+from datetime import datetime
+from typing import TYPE_CHECKING
+
+from django.utils import timezone
+
+import structlog
+import posthoganalytics
+from temporalio import activity
+
+from posthog.event_usage import groups
+from posthog.temporal.common.metrics import get_metric_meter
+
+from products.signals.backend.models import SignalReport, SignalTeamConfig
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
+logger = structlog.get_logger(__name__)
+
+
+@dataclass(frozen=True, kw_only=True)
+class DailyReportLimitGate:
+ """One pipeline gate decision: `limited` is whether the gate should block; `limit` and
+ `reports_today` carry the numbers for telemetry (both meaningless when no limit is set)."""
+
+ limited: bool
+ limit: int | None
+ reports_today: int
+
+
+def record_daily_limit_check_failed_open() -> None:
+ """Count a daily-limit check that errored and failed open (no-op outside a Temporal
+ activity). Keeps the bypass alertable, mirroring the billing quota's fail-open counter."""
+ # Emit the meter directly rather than via products.signals.backend.temporal.metrics: importing
+ # that package runs its __init__, which imports buffer.py, which imports this module (cycle).
+ if not activity.in_activity():
+ return
+ get_metric_meter().create_counter(
+ "signals_daily_limit_check_failed_open_total",
+ "Signals daily report limit checks that errored and failed open, bypassing enforcement",
+ ).add(1)
+
+
+def team_day_start(team: "Team", at: datetime | None = None) -> datetime:
+ """Midnight of the current calendar day in the project's timezone, as an aware datetime.
+
+ The billing quota's `posthog.utils.get_current_day` is hardcoded to UTC; this limit is a
+ user-experience cap ("reports I got today"), so the day follows `team.timezone_info` instead.
+ On a spring-forward day where local midnight doesn't exist, ZoneInfo resolves the nonexistent
+ time deterministically, so the boundary shifts by at most the DST gap.
+ """
+ local = (at or timezone.now()).astimezone(team.timezone_info)
+ return local.replace(hour=0, minute=0, second=0, microsecond=0)
+
+
+def reports_generated_today(team: "Team", *, day_start: datetime) -> int:
+ """How many reports first became user-visible since `day_start`.
+
+ Counts `first_visible_at` stamps (set once, on the first transition into READY or
+ PENDING_INPUT), so re-research of an already-visible report never recounts.
+ """
+ return SignalReport.objects.filter(team_id=team.id, first_visible_at__gte=day_start).count()
+
+
+def daily_report_limit_gate(team: "Team") -> DailyReportLimitGate:
+ """Resolve the daily report limit gate for one team.
+
+ Teams without a configured limit return immediately without running the count query, so the
+ fleet-wide hot paths (every buffer flush, every gate check) pay a single indexed limit read.
+ Fails open on any error: an infra blip lets work through rather than stalling the pipeline.
+ Blocking database I/O; wrap in `sync_to_async`/`database_sync_to_async` from async code.
+ """
+ try:
+ limit = SignalTeamConfig.objects.filter(team_id=team.id).values_list("max_reports_per_day", flat=True).first()
+ if limit is None:
+ return DailyReportLimitGate(limited=False, limit=None, reports_today=0)
+ reports_today = reports_generated_today(team, day_start=team_day_start(team))
+ return DailyReportLimitGate(limited=reports_today >= limit, limit=limit, reports_today=reports_today)
+ except Exception:
+ logger.warning("signals_daily_limit_check_failed_open", team_id=team.id, exc_info=True)
+ record_daily_limit_check_failed_open()
+ return DailyReportLimitGate(limited=False, limit=None, reports_today=0)
+
+
+def capture_signal_report_daily_limit_paused(
+ team: "Team", *, report_id: str | None, stage: str, gate: DailyReportLimitGate
+) -> None:
+ """`signal_report_daily_limit_paused`: a pipeline gate paused work because the team hit its
+ daily report limit at `stage`. No `enforced` property, unlike the billing event: the field
+ being set is the enforcement switch, so every event is a real block. Best-effort: telemetry
+ must never fail the pipeline step that emitted it. Requires `team.organization` to be loaded.
+ """
+ try:
+ posthoganalytics.capture(
+ event="signal_report_daily_limit_paused",
+ distinct_id=str(team.uuid),
+ properties={
+ "team_id": team.id,
+ "organization_id": str(team.organization_id),
+ "report_id": report_id,
+ "stage": stage,
+ "limit": gate.limit,
+ "reports_today": gate.reports_today,
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.exception(
+ "Failed to capture signal_report_daily_limit_paused", report_id=report_id, team_id=team.id, stage=stage
+ )
diff --git a/products/signals/backend/migrations/0097_signalreport_first_visible_at_and_more.py b/products/signals/backend/migrations/0097_signalreport_first_visible_at_and_more.py
new file mode 100644
index 000000000000..bc2901a4d4ed
--- /dev/null
+++ b/products/signals/backend/migrations/0097_signalreport_first_visible_at_and_more.py
@@ -0,0 +1,29 @@
+# Generated by Django 5.2.17 on 2026-08-10 12:15
+
+import django.core.validators
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1296_backfill_cimd_verification_token_url"),
+ ("posthog_ai", "0004_conversation_agent_runtime_conversation_task_and_more"),
+ ("signals", "0096_signal_report_canvas_generation"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalreport",
+ name="first_visible_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="signalteamconfig",
+ name="max_reports_per_day",
+ field=models.PositiveIntegerField(
+ blank=True,
+ null=True,
+ validators=[django.core.validators.MinValueValidator(1)],
+ ),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/0098_signalreport_first_visible_index.py b/products/signals/backend/migrations/0098_signalreport_first_visible_index.py
new file mode 100644
index 000000000000..c477406c61ce
--- /dev/null
+++ b/products/signals/backend/migrations/0098_signalreport_first_visible_index.py
@@ -0,0 +1,20 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False # Required for concurrent index creation
+
+ dependencies = [("signals", "0097_signalreport_first_visible_at_and_more")]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="signalreport",
+ index=models.Index(
+ condition=models.Q(("first_visible_at__isnull", False)),
+ fields=["team", "first_visible_at"],
+ name="signals_report_first_visible",
+ ),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/0099_backfill_first_visible_at.py b/products/signals/backend/migrations/0099_backfill_first_visible_at.py
new file mode 100644
index 000000000000..cbdb4b1abf80
--- /dev/null
+++ b/products/signals/backend/migrations/0099_backfill_first_visible_at.py
@@ -0,0 +1,46 @@
+from django.db import migrations
+from django.db.models import F, Q
+
+
+def backfill_first_visible_at(apps, schema_editor):
+ """Stamp reports that were already user-visible before first_visible_at existed.
+
+ The set-once guard in transition_to treats NULL as "never seen", so an unstamped pre-existing
+ report re-entering ready/pending_input (reopen on new signals, restore from archive) would be
+ stamped with the current time and wrongly consume a max_reports_per_day slot that day. Rows
+ that provably surfaced before — currently visible, resolved (only reachable from a visible
+ status), or suppressed away from one of those — get their created_at, which on every day after
+ this migration precedes the day boundary, so a backfilled report never counts. The lone
+ exception is a report created earlier on the migration day whose team also enables the limit
+ that same local day: created_at then falls inside the current day and the report counts against
+ it, a bounded overshoot that clears at the next local midnight, matching the in-flight overshoot
+ the limit already tolerates. Updated in batches so the whole backlog isn't row-locked in one
+ statement.
+ """
+ SignalReport = apps.get_model("signals", "SignalReport")
+ visible = ["ready", "pending_input", "resolved"]
+ unstamped = SignalReport.objects.filter(first_visible_at__isnull=True).filter(
+ Q(status__in=visible) | Q(status="suppressed", status_before_suppression__in=visible)
+ )
+ while True:
+ batch = list(unstamped.values_list("id", flat=True)[:500])
+ if not batch:
+ break
+ SignalReport.objects.filter(id__in=batch).update(first_visible_at=F("created_at"))
+
+
+class Migration(migrations.Migration):
+ # Non-atomic so each batch's UPDATE commits and releases its row locks as it goes. The default
+ # wrapping transaction would instead hold every updated row locked until the whole backfill
+ # committed, which is the lock buildup the batching is meant to avoid. Safe to resume after a
+ # partial run because each pass only ever selects rows that are still unstamped.
+ atomic = False
+
+ dependencies = [
+ ("signals", "0098_signalreport_first_visible_index"),
+ ]
+
+ # Reverse is a noop: clearing the stamps would recreate the miscount this backfill closes.
+ operations = [
+ migrations.RunPython(backfill_first_visible_at, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 6e9eab3fb84d..00bff8ffd2a9 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0096_signal_report_canvas_generation
+0099_backfill_first_visible_at
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 7ae6ddc58c7a..e546feb79403 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -138,6 +138,10 @@ class SignalTeamConfig(UUIDModel):
default_autostart_priority = models.CharField(max_length=2, choices=AutonomyPriority, default=AutonomyPriority.P4)
default_slack_notification_channel = models.CharField(max_length=255, null=True, blank=True)
autostart_base_branches = models.JSONField(default=dict, blank=True)
+ # Daily cap on reports surfacing to the inbox, counted against SignalReport.first_visible_at
+ # within the project-timezone day. Once reached, the whole generation pipeline pauses until
+ # local midnight (see daily_limit.py). Null means unlimited.
+ max_reports_per_day = models.PositiveIntegerField(null=True, blank=True, validators=[MinValueValidator(1)])
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@@ -249,6 +253,11 @@ class SignalReport(UUIDModel):
updated_at = models.DateTimeField(auto_now=True)
promoted_at = models.DateTimeField(null=True, blank=True)
last_run_at = models.DateTimeField(null=True, blank=True)
+ # When the report first became user-visible (entered READY or PENDING_INPUT, the statuses the
+ # inbox lists). Set once and never cleared, so re-research and suppress/restore cycles don't
+ # recount it against SignalTeamConfig.max_reports_per_day. Null for reports that predate the
+ # field or never surfaced.
+ first_visible_at = models.DateTimeField(null=True, blank=True)
# Video segment clustering fields
cluster_centroid = deprecate_field(
@@ -270,6 +279,12 @@ class SignalReport(UUIDModel):
indexes = [
models.Index(fields=["team", "status", "promoted_at"]),
models.Index(fields=["team", "created_at"]),
+ # Partial: the daily-limit gate only ever counts stamped rows for one team and day.
+ models.Index(
+ fields=["team", "first_visible_at"],
+ condition=models.Q(first_visible_at__isnull=False),
+ name="signals_report_first_visible",
+ ),
]
def transition_to(
@@ -401,6 +416,13 @@ class SignalReport(UUIDModel):
case _:
raise InvalidStatusTransition(self.status, new_status)
+ # First arrival into a user-visible status (the inbox lists READY and PENDING_INPUT).
+ # Set-once: re-research and suppress/restore cycles keep the original timestamp, so a
+ # report only ever counts once toward SignalTeamConfig.max_reports_per_day.
+ if new_status in (S.READY, S.PENDING_INPUT) and self.first_visible_at is None:
+ self.first_visible_at = timezone.now()
+ updated_fields.add("first_visible_at")
+
self.status = new_status
updated_fields.update(["status", "updated_at"])
return list(updated_fields)
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 3c0dd0b6e02f..67c4d9618368 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -53,6 +53,7 @@ from posthog.permissions import AccessControlPermission, APIScopePermission, get
from posthog.rbac.user_access_control import UserAccessControl
from posthog.temporal.common.client import sync_connect
+from products.signals.backend.daily_limit import daily_report_limit_gate
from products.signals.backend.models import (
SignalProjectProfile,
SignalReport,
@@ -2123,7 +2124,7 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
404: OpenApiResponse(description="Config not found for this project (or the scout is withheld)."),
409: OpenApiResponse(description="A run for this scout is already in progress."),
429: OpenApiResponse(
- description="The project is over its Signals credits quota or daily scout run budget; try again later."
+ description="The project is over its Signals credits quota, its daily report limit, or its daily scout run budget; try again later."
),
},
summary="Run a scout now",
@@ -2132,8 +2133,9 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"Useful to test a scout right after authoring it, or to refresh its findings on demand. "
"The run executes asynchronously on the worker and inherits every guard the scheduled "
"path has: it is forbidden if scouts are not enabled for the project (403), and skipped "
- "if the project is over its Signals credits quota or daily run budget (429) or a run for "
- "this scout is already in progress (409). A manual run counts against the same daily run "
+ "if the project is over its Signals credits quota, daily report limit, or daily run "
+ "budget (429) or a run for this scout is already in progress (409). A manual run counts "
+ "against the same daily run "
"budget as scheduled runs, so repeated manual runs of the same scout can exhaust the "
"project's daily allowance. A manual run does not change the scout's schedule or "
"`last_run_at`. A disabled scout can still be run this way (to test before enabling). "
@@ -2176,13 +2178,16 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# exceed the daily cap the scheduled path respects.
_reject_if_manual_run_suppressed(team_id)
- # Fail-fast guards so the trigger can't be gamed into churning workflows or spend. Both are
- # re-checked authoritatively downstream (quota in the run activity, single-flight in the
- # runner and at the Temporal server), but rejecting here avoids dispatching a workflow that
- # would only be skipped, and turns the common cases into clean 429/409 responses.
- api_token = Team.objects.only("api_token").get(pk=team_id).api_token
- if is_team_signals_quota_limited(api_token):
+ # Fail-fast guards so the trigger can't be gamed into churning workflows or spend. All are
+ # re-checked authoritatively downstream (quota and daily report limit in the run activity,
+ # single-flight in the runner and at the Temporal server), but rejecting here avoids
+ # dispatching a workflow that would only be skipped, and turns the common cases into clean
+ # 429/409 responses.
+ team = Team.objects.get(pk=team_id)
+ if is_team_signals_quota_limited(team.api_token):
raise exceptions.Throttled(detail="This project is over its Signals credits quota. Try again later.")
+ if daily_report_limit_gate(team).limited:
+ raise exceptions.Throttled(detail="This project reached its daily report limit. Try again tomorrow.")
if _scout_run_in_flight(team_id, skill_name):
raise Conflict()
diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.py
index 21ebe9ea408d..5a39139b4457 100644
--- a/products/signals/backend/scout_report/persistence.py
+++ b/products/signals/backend/scout_report/persistence.py
@@ -175,6 +175,11 @@ def create_scout_report(
signal_count=len(signals),
total_weight=total_weight,
charts=[chart.model_dump(mode="json") for chart in charts],
+ # Born directly in a user-visible status without passing through transition_to (which
+ # stamps this for pipeline reports), so the daily report limit counts it from creation.
+ first_visible_at=(
+ timezone.now() if status in (SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT) else None
+ ),
)
report_id = str(report.id)
# Provenance: every authored report carries a note marking it scout-authored, attributed to
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index af13a228a138..3a362dc86e6b 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -16,6 +16,7 @@ from products.signals.backend.contracts import DEFAULT_NOT_ACTIONABLE_KEY, STEER
from products.signals.backend.enums import SignalSourceProduct, SignalSourceType
from .artefact_schemas import NON_WRITABLE_ARTEFACT_TYPES
+from .daily_limit import reports_generated_today, team_day_start
from .models import (
AutonomyPriority,
SignalReport,
@@ -182,6 +183,53 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):
"(or send {}) to keep targeting the repo default branch."
),
)
+ max_reports_per_day = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=1,
+ # Ceiling at the int4 column max so an out-of-range value returns 400, not a DB write error.
+ max_value=2147483647,
+ help_text=(
+ "Daily cap on new reports surfacing to the inbox, counted per calendar day in the "
+ "project's timezone. Once reached, signal ingestion, scout runs, and report research "
+ "pause until local midnight. Null means unlimited."
+ ),
+ )
+ reports_generated_today = serializers.SerializerMethodField(
+ help_text=(
+ "How many reports first became visible in the inbox during the current project-timezone "
+ "day. This is the count the daily report limit compares against."
+ )
+ )
+ daily_report_limit_reached = serializers.SerializerMethodField(
+ help_text=(
+ "Whether the team hit its daily report limit, pausing new report generation until "
+ "local midnight. Always false when max_reports_per_day is null."
+ )
+ )
+
+ # 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
+
+ def _reports_today_count(self, obj: SignalTeamConfig) -> int:
+ if self._reports_today is None:
+ self._reports_today = reports_generated_today(obj.team, day_start=team_day_start(obj.team))
+ return self._reports_today
+
+ @extend_schema_field(serializers.IntegerField(min_value=0))
+ def get_reports_generated_today(self, obj: SignalTeamConfig) -> int:
+ # No limit means the count is never shown, so skip the query — mirroring the sibling field
+ # and daily_report_limit_gate, which both short-circuit unlimited teams.
+ if obj.max_reports_per_day is None:
+ return 0
+ return self._reports_today_count(obj)
+
+ @extend_schema_field(serializers.BooleanField())
+ def get_daily_report_limit_reached(self, obj: SignalTeamConfig) -> bool:
+ if obj.max_reports_per_day is None:
+ return False
+ return self._reports_today_count(obj) >= obj.max_reports_per_day
class Meta:
model = SignalTeamConfig
@@ -191,10 +239,13 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):
"default_autostart_priority",
"default_slack_notification_channel",
"autostart_base_branches",
+ "max_reports_per_day",
+ "reports_generated_today",
+ "daily_report_limit_reached",
"created_at",
"updated_at",
]
- read_only_fields = ["id", "created_at", "updated_at"]
+ read_only_fields = ["id", "reports_generated_today", "daily_report_limit_reached", "created_at", "updated_at"]
extra_kwargs = {
"autostart_enabled": {
"help_text": (
diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.py
index 954733998a00..f6ea0fbadb6a 100644
--- a/products/signals/backend/temporal/agentic/scout_scheduler.py
+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py
@@ -19,6 +19,7 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.utils import close_db_connections
+from products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gate
from products.signals.backend.quota import is_team_signals_quota_limited
from products.signals.backend.scout_harness.limits import WORKFLOW_HARD_CEILING_S
from products.signals.backend.temporal import metrics
@@ -54,11 +55,6 @@ class RunSignalsScoutOutput:
skip_reason: str | None = None
-def _is_team_over_signals_quota(team_id: int) -> bool:
- api_token = Team.objects.only("api_token").get(pk=team_id).api_token
- return is_team_signals_quota_limited(api_token)
-
-
def _to_output(result: RunResult) -> RunSignalsScoutOutput:
return RunSignalsScoutOutput(
run_id=result.run_id,
@@ -88,8 +84,17 @@ async def run_signals_scout_activity(input: RunSignalsScoutInput) -> RunSignalsS
which run outside the run-row try/except — so a transient drop is reported as a failed
run rather than escaping the activity and breaching the "never raises" contract.
"""
- # Skip the run when the team is over its Signals credits quota, before any LLM work.
- if await database_sync_to_async(_is_team_over_signals_quota, thread_sensitive=False)(input.team_id):
+ # Skip the run when the team is over its Signals credits quota or its daily report limit,
+ # before any LLM work: a scout run exists to feed signals into the pipeline, and ingestion
+ # drops them while either limit binds.
+ team = await Team.objects.select_related("organization").aget(pk=input.team_id)
+ quota_limited = await database_sync_to_async(is_team_signals_quota_limited, thread_sensitive=False)(team.api_token)
+ daily_gate = await database_sync_to_async(daily_report_limit_gate, thread_sensitive=False)(team)
+ # Captured whenever the daily gate binds — even when the quota skip below wins the
+ # single-status run counter — so the daily-limit event stream stays complete on co-bound days.
+ if daily_gate.limited:
+ capture_signal_report_daily_limit_paused(team, report_id=None, stage="scout_run", gate=daily_gate)
+ if quota_limited:
logger.info(
"signals_scout: skipping run, team over signals_credits quota",
team_id=input.team_id,
@@ -105,6 +110,22 @@ async def run_signals_scout_activity(input: RunSignalsScoutInput) -> RunSignalsS
skill_version=input.skill_version or 0,
skip_reason="quota_limited",
)
+ if daily_gate.limited:
+ logger.info(
+ "signals_scout: skipping run, team over daily report limit",
+ team_id=input.team_id,
+ skill_name=input.skill_name,
+ )
+ metrics.increment_scout_run("daily_report_limit")
+ return RunSignalsScoutOutput(
+ run_id=None,
+ task_run_id=None,
+ status=None,
+ runtime_s=0.0,
+ skill_name=input.skill_name,
+ skill_version=input.skill_version or 0,
+ skip_reason="daily_report_limit",
+ )
# Deferred to break the runner <-> temporal import cycle (see the TYPE_CHECKING note
# above): importing the runner at module load leaves RunResult undefined when runner
diff --git a/products/signals/backend/temporal/buffer.py b/products/signals/backend/temporal/buffer.py
index 50b02fe166c8..353d3615873f 100644
--- a/products/signals/backend/temporal/buffer.py
+++ b/products/signals/backend/temporal/buffer.py
@@ -14,12 +14,15 @@ from asgiref.sync import sync_to_async
from temporalio import activity, workflow
from temporalio.common import MetricCounter, RetryPolicy
+from posthog.dataclasses import frozen
from posthog.models import Team
from posthog.storage import object_storage
+from posthog.sync import database_sync_to_async
from posthog.temporal.common.client import async_connect
from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import close_db_connections
+from products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gate
from products.signals.backend.quota import is_team_signals_quota_limited
from products.signals.backend.temporal import metrics
from products.signals.backend.temporal.grouping_v2 import TeamSignalGroupingV2Workflow
@@ -70,18 +73,45 @@ async def flush_signals_to_s3_activity(input: FlushBufferInput) -> FlushBufferOu
return FlushBufferOutput(object_key=object_key, signal_count=len(input.signals))
-@dataclass
+@frozen
class CheckSignalsQuotaInput:
team_id: int
+ # Defaults so activity inputs recorded before the field existed still decode on replay.
+ signal_count: int = 0
@activity.defn
@scoped_temporal()
@close_db_connections
async def check_signals_quota_limited_activity(input: CheckSignalsQuotaInput) -> bool:
- """Whether the team is over its Signals credits quota."""
- team = await Team.objects.only("api_token").aget(pk=input.team_id)
- return await sync_to_async(is_team_signals_quota_limited)(team.api_token)
+ """Whether the batch must be dropped: the team is over its Signals credits quota, or over its
+ daily report limit. Owns the drop logging and metric so the reason label names the exact limit
+ that fired; the workflow only acts on the boolean.
+ """
+ team = await Team.objects.select_related("organization").aget(pk=input.team_id)
+ quota_limited = await sync_to_async(is_team_signals_quota_limited, thread_sensitive=False)(team.api_token)
+ daily_gate = await database_sync_to_async(daily_report_limit_gate, thread_sensitive=False)(team)
+ # Captured whenever the daily gate binds — even when the quota drop below wins the
+ # single-reason drop metric — so the daily-limit event stream stays complete on co-bound days.
+ if daily_gate.limited:
+ capture_signal_report_daily_limit_paused(team, report_id=None, stage="ingestion", gate=daily_gate)
+ if quota_limited:
+ logger.info(
+ "signals_buffer.dropped_batch_quota_limited",
+ team_id=input.team_id,
+ signal_count=input.signal_count,
+ )
+ metrics.increment_dropped(stage="ingestion", reason="quota_limited", count=input.signal_count)
+ return True
+ if daily_gate.limited:
+ logger.info(
+ "signals_buffer.dropped_batch_daily_limit",
+ team_id=input.team_id,
+ signal_count=input.signal_count,
+ )
+ metrics.increment_dropped(stage="ingestion", reason="daily_report_limit", count=input.signal_count)
+ return True
+ return False
@dataclass
@@ -204,22 +234,18 @@ class BufferSignalsWorkflow:
batch = list(self._signal_buffer)
self._signal_buffer.clear()
- # Drop the batch when the team is over its Signals credits quota, before any downstream work.
+ # Drop the batch when the team is over its Signals credits quota or its daily report
+ # limit, before any downstream work. The activity logs the drop and owns the dropped
+ # metric, attributed to the exact limit that fired.
if workflow.patched(_PATCH_QUOTA_INGESTION_GATE):
- over_quota = await workflow.execute_activity(
+ over_limit = await workflow.execute_activity(
check_signals_quota_limited_activity,
- CheckSignalsQuotaInput(team_id=input.team_id),
+ CheckSignalsQuotaInput(team_id=input.team_id, signal_count=len(batch)),
start_to_close_timeout=timedelta(seconds=30),
retry_policy=RetryPolicy(maximum_attempts=3),
)
- if over_quota:
- logger.info(
- "signals_buffer.dropped_batch_quota_limited",
- team_id=input.team_id,
- signal_count=len(batch),
- )
- metrics.increment_dropped(stage="ingestion", reason="quota_limited", count=len(batch))
- # Compact history like the empty-batch path so a sustained over-quota stream
+ if over_limit:
+ # Compact history like the empty-batch path so a sustained over-limit stream
# doesn't grow Temporal history unboundedly.
if len(self._signal_buffer) < BUFFER_MAX_SIZE:
workflow.continue_as_new(
diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.py
index df358917db9a..dea0c3042d6c 100644
--- a/products/signals/backend/temporal/grouping.py
+++ b/products/signals/backend/temporal/grouping.py
@@ -33,6 +33,7 @@ from posthog.temporal.common.utils import close_db_connections
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import RelatedTo
from products.signals.backend.billing import BILLING_EXEMPT_SOURCE_PRODUCTS
+from products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gate
from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.signals.backend.quota import capture_signal_report_quota_paused, self_driving_quota_gate
from products.signals.backend.signal_metadata import EMBEDDING_MODEL
@@ -802,10 +803,11 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As
)
):
if suppress_promotion:
- # The team's org is over its self-driving credits quota with enforcement on: the signal is still
- # assigned, weighted, and emitted, but no summary run spawns. The status is left
- # untouched, so the first matching signal after the quota lifts re-evaluates
- # promotion under the same rules.
+ # The team's org is over its self-driving credits quota with enforcement on, or
+ # the team hit its daily report limit: the signal is still assigned, weighted,
+ # and emitted, but no summary run spawns. The status is left untouched, so the
+ # first matching signal after the limit lifts re-evaluates promotion under the
+ # same rules.
promotion_suppressed = True
# If candidate got here - it usually means CH issue down the way
# (e.g. CH wait raised before start_child_workflow)
@@ -857,11 +859,14 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As
try:
team = await Team.objects.select_related("organization").aget(pk=input.team_id)
- # Resolved before the assign transaction: the quota gate is Redis + flag network I/O that
- # must not run while holding the report row lock.
+ # Resolved before the assign transaction: the gates are Redis/Postgres + flag network I/O
+ # that must not run while holding the report row lock.
quota_gate = await database_sync_to_async(self_driving_quota_gate, thread_sensitive=False)(team)
+ daily_gate = await database_sync_to_async(daily_report_limit_gate, thread_sensitive=False)(team)
- db_result = await database_sync_to_async(do_assign_and_emit, thread_sensitive=False)(quota_gate.enforced)
+ db_result = await database_sync_to_async(do_assign_and_emit, thread_sensitive=False)(
+ quota_gate.enforced or daily_gate.limited
+ )
# If we matched a deleted report, soft-delete all its stale signals in ClickHouse.
# This prevents data corruption where non-deleted signals for a deleted report
@@ -950,11 +955,16 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As
source_id=input.source_id,
)
# Emitted only when the signal would have promoted the report, so the event volume
- # measures withheld summary runs rather than every assignment on a limited team.
+ # measures withheld summary runs rather than every assignment on a limited team. Both
+ # events fire when both limits are hit, keeping each stream complete for its own gate.
if quota_gate.limited and (db_result.promoted or db_result.promotion_suppressed):
capture_signal_report_quota_paused(
team, report_id=db_result.report_id, stage="promotion", enforced=quota_gate.enforced
)
+ if daily_gate.limited and (db_result.promoted or db_result.promotion_suppressed):
+ capture_signal_report_daily_limit_paused(
+ team, report_id=db_result.report_id, stage="promotion", gate=daily_gate
+ )
if not db_result.matched_deleted_report:
metrics.increment_funnel(metrics.FUNNEL_STAGE_GROUPED, input.source_product)
diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.py
index e2c9a4180393..0415ba978730 100644
--- a/products/signals/backend/temporal/summary.py
+++ b/products/signals/backend/temporal/summary.py
@@ -26,6 +26,7 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import close_db_connections
+from products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gate
from products.signals.backend.models import SignalReport
from products.signals.backend.quota import (
capture_signal_report_quota_paused,
@@ -556,9 +557,12 @@ class CheckReportQuotaGateInput:
@close_db_connections
async def check_report_quota_gate_activity(input: CheckReportQuotaGateInput) -> bool:
"""Whether the summary workflow must pause at `stage`: the team's org is over its self-driving
- credits quota and enforcement is on. Emits `signal_report_quota_paused` whenever the team is limited,
- enforced or not, so the dark-launch would-block volume is measurable. Never raises: any
- failure resolves to False (run proceeds), matching the quota module's fail-open policy.
+ credits quota with enforcement on, or the team hit its daily report limit. Emits
+ `signal_report_quota_paused` whenever the team is quota-limited, enforced or not, so the
+ dark-launch would-block volume is measurable, and `signal_report_daily_limit_paused` when the
+ daily limit binds; both fire when both limits are hit, keeping each event stream complete for
+ its own gate. Never raises: any failure resolves to False (run proceeds), matching both
+ modules' fail-open policy.
"""
try:
team = await Team.objects.select_related("organization").aget(pk=input.team_id)
@@ -567,7 +571,12 @@ async def check_report_quota_gate_activity(input: CheckReportQuotaGateInput) ->
capture_signal_report_quota_paused(
team, report_id=input.report_id, stage=input.stage, enforced=gate.enforced
)
- return gate.enforced
+ daily_gate = await database_sync_to_async(daily_report_limit_gate, thread_sensitive=False)(team)
+ if daily_gate.limited:
+ capture_signal_report_daily_limit_paused(
+ team, report_id=input.report_id, stage=input.stage, gate=daily_gate
+ )
+ return gate.enforced or daily_gate.limited
except Exception:
record_quota_check_failed_open()
logger.exception(
diff --git a/products/signals/backend/test/test_assign_and_emit_signal.py b/products/signals/backend/test/test_assign_and_emit_signal.py
index 3ef5d0d811ed..6f65826321bc 100644
--- a/products/signals/backend/test/test_assign_and_emit_signal.py
+++ b/products/signals/backend/test/test_assign_and_emit_signal.py
@@ -14,6 +14,7 @@ from posthog.models import Organization, Team
from posthog.sync import database_sync_to_async
from products.signals.backend.artefact_schemas import RelatedTo
+from products.signals.backend.daily_limit import DailyReportLimitGate
from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.signals.backend.quota import SelfDrivingQuotaGate
from products.signals.backend.temporal.grouping import (
@@ -700,3 +701,76 @@ async def test_quota_gate_emits_no_event_when_signal_would_not_promote(ateam, pa
events = [call.kwargs.get("event") for call in patch_side_effects["capture"].call_args_list]
assert "signal_report_quota_paused" not in events
+
+
+# ---------------------------------------------------------------------------
+# Daily report limit gate: promotion withheld once the team's day is spent
+# ---------------------------------------------------------------------------
+
+
+async def test_daily_limit_gate_withholds_promotion(ateam, patch_side_effects):
+ with patch(
+ f"{GROUPING_MODULE_PATH}.daily_report_limit_gate",
+ return_value=DailyReportLimitGate(limited=True, limit=2, reports_today=2),
+ ):
+ result = await assign_and_emit_signal_activity(_build_input(ateam.id, _new_match(), weight=WEIGHT_THRESHOLD))
+
+ # The signal is still assigned, weighted, and emitted; only the summary spawn is withheld,
+ # with the status untouched so the first post-limit signal re-evaluates promotion.
+ assert result.promoted is False
+ report = await database_sync_to_async(SignalReport.objects.get)(id=result.report_id)
+ assert report.status == SignalReport.Status.POTENTIAL
+ assert report.signal_count == 1
+ assert report.total_weight == pytest.approx(WEIGHT_THRESHOLD)
+
+ daily_events = [
+ call
+ for call in patch_side_effects["capture"].call_args_list
+ if call.kwargs.get("event") == "signal_report_daily_limit_paused"
+ ]
+ assert len(daily_events) == 1
+ properties = daily_events[0].kwargs["properties"]
+ assert properties["stage"] == "promotion"
+ assert properties["limit"] == 2
+ assert properties["reports_today"] == 2
+ # The org's billing quota is clear, so its event stream must stay silent.
+ events = [call.kwargs.get("event") for call in patch_side_effects["capture"].call_args_list]
+ assert "signal_report_quota_paused" not in events
+
+
+async def test_both_limits_emit_both_events(ateam, patch_side_effects):
+ # Each event stream must stay complete for its own gate's dashboards; neither suppresses
+ # the other when both limits are hit at once.
+ with (
+ patch(
+ f"{GROUPING_MODULE_PATH}.self_driving_quota_gate",
+ return_value=SelfDrivingQuotaGate(limited=True, enforced=True),
+ ),
+ patch(
+ f"{GROUPING_MODULE_PATH}.daily_report_limit_gate",
+ return_value=DailyReportLimitGate(limited=True, limit=2, reports_today=2),
+ ),
+ ):
+ result = await assign_and_emit_signal_activity(_build_input(ateam.id, _new_match(), weight=WEIGHT_THRESHOLD))
+
+ assert result.promoted is False
+ events = [call.kwargs.get("event") for call in patch_side_effects["capture"].call_args_list]
+ assert "signal_report_quota_paused" in events
+ assert "signal_report_daily_limit_paused" in events
+
+
+async def test_daily_limit_gate_emits_no_event_when_signal_would_not_promote(ateam, patch_side_effects):
+ with patch(
+ f"{GROUPING_MODULE_PATH}.daily_report_limit_gate",
+ return_value=DailyReportLimitGate(limited=True, limit=2, reports_today=2),
+ ):
+ await assign_and_emit_signal_activity(_build_input(ateam.id, _new_match(), weight=WEIGHT_THRESHOLD * 0.5))
+
+ events = [call.kwargs.get("event") for call in patch_side_effects["capture"].call_args_list]
+ assert "signal_report_daily_limit_paused" not in events
diff --git a/products/signals/backend/test/test_buffer_workflow.py b/products/signals/backend/test/test_buffer_workflow.py
index 841181a85158..1009cf09ec78 100644
--- a/products/signals/backend/test/test_buffer_workflow.py
+++ b/products/signals/backend/test/test_buffer_workflow.py
@@ -2,22 +2,26 @@ import uuid
import asyncio
import pytest
+from unittest.mock import patch
from temporalio import activity
-from temporalio.testing import WorkflowEnvironment
+from temporalio.testing import ActivityEnvironment, WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from products.signals.backend.daily_limit import DailyReportLimitGate
from products.signals.backend.temporal.buffer import (
BufferSignalsWorkflow,
CheckSignalsQuotaInput,
FlushBufferInput,
FlushBufferOutput,
SignalWithStartGroupingV2Input,
+ check_signals_quota_limited_activity,
)
from products.signals.backend.temporal.safety_filter import SafetyFilterInput, SafetyFilterOutput
from products.signals.backend.temporal.types import BufferSignalsInput, EmitSignalInputs
TASK_QUEUE = "test-buffer-queue"
+BUFFER_MODULE = "products.signals.backend.temporal.buffer"
def _signal(team_id: int) -> EmitSignalInputs:
@@ -104,3 +108,50 @@ async def test_under_quota_batch_flows_through():
assert recorder.safety_checks == 1
assert recorder.flushes == 1
assert recorder.grouping_starts == 1
+
+
+# ---------------------------------------------------------------------------
+# check_signals_quota_limited_activity: which limit fired decides the drop attribution
+# ---------------------------------------------------------------------------
+
+
+ ("billing_limited", "daily_limited", "expected", "expected_reason"),
+ [
+ (True, False, True, "quota_limited"),
+ (False, True, True, "daily_report_limit"),
+ (True, True, True, "quota_limited"),
+ (False, False, False, None),
+ ],
+)
+async def test_check_activity_attributes_drop_to_the_limit_that_fired(
+ ateam, billing_limited, daily_limited, expected, expected_reason
+):
+ with (
+ patch(f"{BUFFER_MODULE}.is_team_signals_quota_limited", return_value=billing_limited),
+ patch(
+ f"{BUFFER_MODULE}.daily_report_limit_gate",
+ return_value=DailyReportLimitGate(limited=daily_limited, limit=2, reports_today=2),
+ ),
+ patch(f"{BUFFER_MODULE}.metrics.increment_dropped") as dropped,
+ patch(f"{BUFFER_MODULE}.capture_signal_report_daily_limit_paused") as capture,
+ ):
+ result = await ActivityEnvironment().run(
+ check_signals_quota_limited_activity,
+ CheckSignalsQuotaInput(team_id=ateam.id, signal_count=3),
+ )
+
+ assert result is expected
+ if expected_reason is None:
+ dropped.assert_not_called()
+ else:
+ dropped.assert_called_once_with(stage="ingestion", reason=expected_reason, count=3)
+ # The capture event tracks its own gate: it fires whenever the daily limit binds, even when
+ # the quota drop wins the single-reason metric attribution.
+ if daily_limited:
+ assert capture.call_args.kwargs["stage"] == "ingestion"
+ assert capture.call_args.kwargs["report_id"] is None
+ else:
+ capture.assert_not_called()
diff --git a/products/signals/backend/test/test_daily_limit.py b/products/signals/backend/test/test_daily_limit.py
new file mode 100644
index 000000000000..f594625a1db5
--- /dev/null
+++ b/products/signals/backend/test/test_daily_limit.py
@@ -0,0 +1,155 @@
+from datetime import UTC, datetime, timedelta
+
+from freezegun import freeze_time
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.signals.backend.daily_limit import DailyReportLimitGate, daily_report_limit_gate
+from products.signals.backend.models import SignalReport, SignalTeamConfig
+
+DAILY_LIMIT_MODULE = "products.signals.backend.daily_limit"
+
+
+class TestDailyReportLimitGate(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # A SignalTeamConfig is auto-created for every team via register_team_extension_signal.
+ self.config = SignalTeamConfig.objects.get(team=self.team)
+
+ def _set_limit(self, limit: int | None) -> None:
+ self.config.max_reports_per_day = limit
+ self.config.save(update_fields=["max_reports_per_day"])
+
+ def _visible_report(self, first_visible_at: datetime | None) -> SignalReport:
+ return SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.READY, first_visible_at=first_visible_at
+ )
+
+ def test_no_limit_short_circuits_without_counting(self):
+ # The count query must stay off the fleet-wide hot path (every buffer flush runs this
+ # gate): with no limit configured, only the single limit read may execute.
+ self._visible_report(datetime.now(UTC))
+ with self.assertNumQueries(1):
+ gate = daily_report_limit_gate(self.team)
+ assert gate == DailyReportLimitGate(limited=False, limit=None, reports_today=0)
+
+ @parameterized.expand(
+ [
+ ("under", 1, 2, False),
+ ("at", 2, 2, True),
+ ("over", 3, 2, True),
+ ]
+ )
+ def test_gate_compares_todays_count_to_limit(self, _name, visible_today, limit, expected_limited):
+ self._set_limit(limit)
+ for _ in range(visible_today):
+ self._visible_report(datetime.now(UTC))
+ gate = daily_report_limit_gate(self.team)
+ assert gate == DailyReportLimitGate(limited=expected_limited, limit=limit, reports_today=visible_today)
+
+ def test_only_reports_stamped_today_count(self):
+ self._set_limit(1)
+ with freeze_time("2026-08-10T12:00:00Z"):
+ self._visible_report(datetime(2026, 8, 9, 12, 0, tzinfo=UTC))
+ # A pre-migration (or never-surfaced) row has no stamp and must never count.
+ self._visible_report(None)
+ gate = daily_report_limit_gate(self.team)
+ assert gate.reports_today == 0
+ assert gate.limited is False
+
+ def test_day_boundary_follows_project_timezone(self):
+ # At 05:00 UTC Aug 10 it is 22:00 Aug 9 in Los Angeles, so the local day started at
+ # 07:00 UTC Aug 9. A report stamped 08:00 UTC Aug 9 is "today" locally (a UTC boundary
+ # would miss it) and one stamped 06:00 UTC Aug 9 (23:00 Aug 8 local) is not.
+ self.team.timezone = "America/Los_Angeles"
+ self.team.save()
+ self._set_limit(1)
+ self._visible_report(datetime(2026, 8, 9, 8, 0, tzinfo=UTC))
+ self._visible_report(datetime(2026, 8, 9, 6, 0, tzinfo=UTC))
+ with freeze_time("2026-08-10T05:00:00Z"):
+ # Fresh instance: timezone_info is a cached property on the pre-save one.
+ gate = daily_report_limit_gate(Team.objects.get(pk=self.team.pk))
+ assert gate.reports_today == 1
+ assert gate.limited is True
+
+ def test_limit_lowered_below_todays_count_pauses_immediately(self):
+ for _ in range(3):
+ self._visible_report(datetime.now(UTC))
+ self._set_limit(2)
+ assert daily_report_limit_gate(self.team).limited is True
+
+ def test_fails_open_on_count_error(self):
+ self._set_limit(1)
+ with patch(f"{DAILY_LIMIT_MODULE}.reports_generated_today", side_effect=RuntimeError("db down")):
+ gate = daily_report_limit_gate(self.team)
+ assert gate == DailyReportLimitGate(limited=False, limit=None, reports_today=0)
+
+ def test_fail_open_metric_noops_outside_activity(self):
+ self._set_limit(1)
+ with (
+ patch(f"{DAILY_LIMIT_MODULE}.reports_generated_today", side_effect=RuntimeError("db down")),
+ patch(f"{DAILY_LIMIT_MODULE}.get_metric_meter") as mock_meter,
+ ):
+ assert daily_report_limit_gate(self.team).limited is False
+ mock_meter.assert_not_called()
+
+
+class TestFirstVisibleStamp(BaseTest):
+ @parameterized.expand(
+ [
+ ("ready", SignalReport.Status.READY, None),
+ ("pending_input", SignalReport.Status.PENDING_INPUT, "needs a repository"),
+ ]
+ )
+ def test_first_visible_transition_stamps(self, _name, target, error):
+ report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.IN_PROGRESS)
+ updated_fields = report.transition_to(target, title="t", summary="s", error=error)
+ assert report.first_visible_at is not None
+ assert "first_visible_at" in updated_fields
+
+ def test_stamp_survives_reresearch_and_restore(self):
+ report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.IN_PROGRESS)
+ report.transition_to(SignalReport.Status.READY, title="t", summary="s")
+ original = report.first_visible_at
+ assert original is not None
+
+ # A full re-research cycle a day later must not re-stamp: the report already surfaced
+ # once and must not consume the daily limit again.
+ report.transition_to(SignalReport.Status.CANDIDATE)
+ report.transition_to(SignalReport.Status.IN_PROGRESS, signals_at_run_increment=3)
+ with freeze_time(datetime.now(UTC) + timedelta(days=1)):
+ updated_fields = report.transition_to(SignalReport.Status.READY, title="t2", summary="s2")
+ assert report.first_visible_at == original
+ assert "first_visible_at" not in updated_fields
+
+ # Neither must an archive/restore round trip.
+ report.transition_to(SignalReport.Status.SUPPRESSED)
+ report.transition_to(report.restore_target_status())
+ assert report.first_visible_at == original
+
+ @parameterized.expand(
+ [
+ ("promote", SignalReport.Status.POTENTIAL, SignalReport.Status.CANDIDATE, {}),
+ (
+ "start_run",
+ SignalReport.Status.CANDIDATE,
+ SignalReport.Status.IN_PROGRESS,
+ {"signals_at_run_increment": 3},
+ ),
+ ("fail", SignalReport.Status.IN_PROGRESS, SignalReport.Status.FAILED, {"error": "boom"}),
+ (
+ "reset",
+ SignalReport.Status.IN_PROGRESS,
+ SignalReport.Status.POTENTIAL,
+ {"reset_weight": True},
+ ),
+ ]
+ )
+ def test_non_visible_transitions_do_not_stamp(self, _name, start, target, kwargs):
+ report = SignalReport.objects.create(team=self.team, status=start)
+ report.transition_to(target, **kwargs)
+ assert report.first_visible_at is None
diff --git a/products/signals/backend/test/test_migration_0099.py b/products/signals/backend/test/test_migration_0099.py
new file mode 100644
index 000000000000..ac76ba3b867d
--- /dev/null
+++ b/products/signals/backend/test/test_migration_0099.py
@@ -0,0 +1,56 @@
+from datetime import UTC, datetime
+from typing import Any
+
+from posthog.test.base import NonAtomicTestMigrations
+
+
+# Non-atomic so a future signals migration with a CONCURRENTLY index doesn't break the rewind.
+class BackfillFirstVisibleAtMigrationTest(NonAtomicTestMigrations):
+ migrate_from = "0098_signalreport_first_visible_index"
+ migrate_to = "0099_backfill_first_visible_at"
+
+ CLASS_DATA_LEVEL_SETUP = False
+
+ @property
+ def app(self) -> str:
+ return "signals"
+
+ def setUpBeforeMigration(self, apps: Any) -> None:
+ Organization = apps.get_model("posthog", "Organization")
+ Project = apps.get_model("posthog", "Project")
+ Team = apps.get_model("posthog", "Team")
+ SignalReport = apps.get_model("signals", "SignalReport")
+
+ org = Organization.objects.create(name="Test Organization")
+ project = Project.objects.create(id=999997, organization=org, name="Test Project")
+ team = Team.objects.create(organization=org, project=project, name="Test Team")
+
+ def make_report(status: str, **kwargs: Any) -> Any:
+ return SignalReport.objects.create(team_id=team.id, status=status, **kwargs)
+
+ self.stamped_ids = [
+ make_report("ready").id,
+ make_report("pending_input").id,
+ make_report("resolved").id,
+ make_report("suppressed", status_before_suppression="ready").id,
+ ]
+ self.untouched_ids = [
+ make_report("potential").id,
+ make_report("failed").id,
+ make_report("suppressed", status_before_suppression="potential").id,
+ ]
+ self.preset_stamp = datetime(2026, 1, 5, 12, 0, tzinfo=UTC)
+ self.preset_id = make_report("ready", first_visible_at=self.preset_stamp).id
+
+ def test_backfills_only_previously_visible_unstamped_reports(self) -> None:
+ assert self.apps is not None
+ SignalReport = self.apps.get_model("signals", "SignalReport")
+
+ for report_id in self.stamped_ids:
+ report = SignalReport.objects.get(id=report_id)
+ assert report.first_visible_at == report.created_at
+
+ for report_id in self.untouched_ids:
+ assert SignalReport.objects.get(id=report_id).first_visible_at is None
+
+ assert SignalReport.objects.get(id=self.preset_id).first_visible_at == self.preset_stamp
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index 7c02a7b12ae5..ea594214c5a3 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -28,6 +28,7 @@ from posthog.models.utils import uuid7
from posthog.sync import database_sync_to_async
from products.signals.backend.agent_runtime import AgentRuntime
+from products.signals.backend.daily_limit import DailyReportLimitGate
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
from products.signals.backend.report_charts import ReportChart
from products.signals.backend.scout_harness.derived_metadata import DERIVED_METADATA_KEY
@@ -2132,13 +2133,30 @@ async def test_activity_returns_skip_outcome_when_already_running(ateam):
@pytest.mark.asyncio
@pytest.mark.django_db
-async def test_activity_skips_run_when_team_over_signals_quota(ateam):
+ ("billing_limited", "daily_limited", "expected_skip_reason"),
+ [
+ (True, False, "quota_limited"),
+ (False, True, "daily_report_limit"),
+ (True, True, "quota_limited"),
+ ],
+)
+async def test_activity_skips_run_attributed_to_the_limit_that_fired(
+ ateam, billing_limited, daily_limited, expected_skip_reason
+):
fake_arun = AsyncMock()
with (
patch(
"products.signals.backend.temporal.agentic.scout_scheduler.is_team_signals_quota_limited",
- return_value=True,
+ return_value=billing_limited,
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_scheduler.daily_report_limit_gate",
+ return_value=DailyReportLimitGate(limited=daily_limited, limit=2, reports_today=2),
),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_scheduler.capture_signal_report_daily_limit_paused"
+ ) as capture,
patch("products.signals.backend.scout_harness.runner.arun_signals_scout", fake_arun),
):
env = ActivityEnvironment()
@@ -2150,7 +2168,13 @@ async def test_activity_skips_run_when_team_over_signals_quota(ateam):
fake_arun.assert_not_called()
assert output.run_id is None
assert output.status is None
- assert output.skip_reason == "quota_limited"
+ assert output.skip_reason == expected_skip_reason
+ # The capture event tracks its own gate: it fires whenever the daily limit binds, even when
+ # the quota skip wins the single-status run counter.
+ if daily_limited:
+ assert capture.call_args.kwargs["stage"] == "scout_run"
+ else:
+ capture.assert_not_called()
@pytest.mark.asyncio
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index a068abb64a9e..7427acf37ae8 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -29,6 +29,7 @@ from posthog.temporal.oauth import (
create_oauth_access_token_for_user,
)
+from products.signals.backend.daily_limit import DailyReportLimitGate
from products.signals.backend.models import (
SignalProjectProfile,
SignalReport,
@@ -2857,6 +2858,7 @@ class TestScoutHarnessMetadataAPI(APIBaseTest):
_QUOTA = "products.signals.backend.scout_harness.views.is_team_signals_quota_limited"
+_DAILY_GATE = "products.signals.backend.scout_harness.views.daily_report_limit_gate"
_START = "products.signals.backend.temporal.agentic.scout_scheduler.start_manual_signals_scout_run"
_CONNECT = "products.signals.backend.scout_harness.views.sync_connect"
_WITHHELD = "products.signals.backend.scout_harness.views.withheld_skills_for_team"
@@ -2902,6 +2904,18 @@ class TestScoutHarnessConfigRunAPI(APIBaseTest):
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
start.assert_not_called()
+ def test_run_over_daily_report_limit_returns_429_without_dispatching(self) -> None:
+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
+ with (
+ patch(_QUOTA, return_value=False),
+ patch(_DAILY_GATE, return_value=DailyReportLimitGate(limited=True, limit=2, reports_today=2)),
+ patch(_START) as start,
+ ):
+ response = self.client.post(self._run_url(str(config.id)))
+
+ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ start.assert_not_called()
+
def test_run_with_in_flight_run_returns_409_without_dispatching(self) -> None:
config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
_make_run(self.team, skill_name="signals-scout-foo") # TaskRun IN_PROGRESS by default
diff --git a/products/signals/backend/test/test_scout_report_persistence.py b/products/signals/backend/test/test_scout_report_persistence.py
index d18b2ef587b3..f7e035dd9748 100644
--- a/products/signals/backend/test/test_scout_report_persistence.py
+++ b/products/signals/backend/test/test_scout_report_persistence.py
@@ -81,6 +81,30 @@ class TestScoutReportPersistence(BaseTest):
)
return run
+ @parameterized.expand(
+ [
+ ("ready", SignalReport.Status.READY, True),
+ ("pending_input", SignalReport.Status.PENDING_INPUT, True),
+ ("suppressed", SignalReport.Status.SUPPRESSED, False),
+ ]
+ )
+ def test_create_stamps_first_visible_only_for_visible_born_status(self, _name, born_status, expect_stamp):
+ # Scout reports are born in their final status without passing through transition_to (which
+ # stamps pipeline reports), so creation must stamp visible births or the daily report limit
+ # would never count them.
+ run = self._make_run()
+ result = create_scout_report(
+ team_id=self.team.id,
+ title="Checkout API p99 latency regressed",
+ summary="The checkout endpoint p99 doubled after the 4.2 deploy.",
+ signals=[ScoutReportSignal(description="p99 doubled on /checkout", source_id="obs-1", weight=1.0)],
+ attribution=ArtefactAttribution.from_task(str(run.task_run.task_id)),
+ status=born_status,
+ run=run,
+ )
+ report = SignalReport.objects.get(id=result.report_id)
+ assert (report.first_visible_at is not None) is expect_stamp
+
def test_create_writes_report_with_bound_signals_metadata(self) -> None:
# The load-bearing contract (decision #5): each backing signal is written to the embeddings
# pipeline with report_id pre-set, as a signals/signal row, so every read-side consumer
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 70b41d5f57dc..c69972e308de 100644
--- a/products/signals/backend/test/test_signal_team_config_api.py
+++ b/products/signals/backend/test/test_signal_team_config_api.py
@@ -1,9 +1,11 @@
+from datetime import UTC, datetime
+
from posthog.test.base import APIBaseTest
from parameterized import parameterized
from rest_framework import status
-from products.signals.backend.models import SignalTeamConfig
+from products.signals.backend.models import SignalReport, SignalTeamConfig
class TestSignalTeamConfigAPI(APIBaseTest):
@@ -140,6 +142,61 @@ class TestSignalTeamConfigAPI(APIBaseTest):
self.config.refresh_from_db()
assert self.config.autostart_enabled is sent
+ def test_get_config_defaults_daily_report_limit_fields(self):
+ response = self.client.get(self._url())
+ data = response.json()
+ assert response.status_code == status.HTTP_200_OK, data
+ assert data["max_reports_per_day"] is None
+ assert data["reports_generated_today"] == 0
+ assert data["daily_report_limit_reached"] is False
+
+ @parameterized.expand(
+ [
+ ("set", None, 5, 5),
+ ("clear", 5, None, None),
+ ]
+ )
+ def test_update_max_reports_per_day(self, _name, initial, sent, expected):
+ if initial is not None:
+ self.config.max_reports_per_day = initial
+ self.config.save(update_fields=["max_reports_per_day"])
+ response = self.client.post(self._url(), data={"max_reports_per_day": sent}, format="json")
+ data = response.json()
+ assert response.status_code == status.HTTP_200_OK, data
+ assert data["max_reports_per_day"] == expected
+ self.config.refresh_from_db()
+ assert self.config.max_reports_per_day == expected
+
+ @parameterized.expand([("zero", 0), ("negative", -3), ("above_int4", 2147483648)])
+ def test_update_max_reports_per_day_rejects_out_of_range(self, _name, sent):
+ response = self.client.post(self._url(), data={"max_reports_per_day": sent}, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "max_reports_per_day"
+
+ 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.
+ SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.READY, first_visible_at=datetime.now(UTC)
+ )
+ response = self.client.get(self._url())
+ data = response.json()
+ assert response.status_code == status.HTTP_200_OK, data
+ assert data["max_reports_per_day"] is None
+ assert data["reports_generated_today"] == 0
+
+ def test_daily_report_limit_reached_reflects_todays_visible_reports(self):
+ self.config.max_reports_per_day = 1
+ self.config.save(update_fields=["max_reports_per_day"])
+ SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.READY, first_visible_at=datetime.now(UTC)
+ )
+ response = self.client.get(self._url())
+ data = response.json()
+ assert response.status_code == status.HTTP_200_OK, data
+ assert data["reports_generated_today"] == 1
+ assert data["daily_report_limit_reached"] is True
+
def test_partial_update_preserves_autostart_enabled(self):
# A team that turned autostart off must not have it silently re-enabled when it later
# edits an unrelated field.
diff --git a/products/signals/backend/test/test_summary_workflow.py b/products/signals/backend/test/test_summary_workflow.py
index 4318cc278ea7..1eb6e4f71c6f 100644
--- a/products/signals/backend/test/test_summary_workflow.py
+++ b/products/signals/backend/test/test_summary_workflow.py
@@ -16,6 +16,7 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from posthog.models import Organization, Team
from posthog.sync import database_sync_to_async
+from products.signals.backend.daily_limit import DailyReportLimitGate
from products.signals.backend.models import SignalReport
from products.signals.backend.quota import SelfDrivingQuotaGate
from products.signals.backend.report_generation.research import ActionabilityChoice
@@ -118,6 +119,29 @@ async def test_check_activity_returns_enforced(ateam, enforced):
assert result is enforced
+async def test_check_activity_pauses_on_daily_limit_with_billing_clear(ateam):
+ # The daily report limit must pause the run on its own: it has no enforcement flag, so
+ # `limited` alone blocks even while the billing quota gate stays clear.
+ with (
+ patch(
+ f"{SUMMARY_MODULE_PATH}.daily_report_limit_gate",
+ return_value=DailyReportLimitGate(limited=True, limit=3, reports_today=3),
+ ),
+ patch("products.signals.backend.daily_limit.posthoganalytics.capture") as capture,
+ ):
+ result = await check_report_quota_gate_activity(
+ CheckReportQuotaGateInput(team_id=ateam.id, report_id=str(uuid.uuid4()), stage="pre_research")
+ )
+ assert result is True
+ assert capture.call_args.kwargs["event"] == "signal_report_daily_limit_paused"
+ properties = capture.call_args.kwargs["properties"]
+ assert properties["stage"] == "pre_research"
+ assert properties["limit"] == 3
+ assert properties["reports_today"] == 3
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_check_activity_fails_open_when_team_lookup_errors():
diff --git a/products/signals/backend/test/test_task_run_artefacts.py b/products/signals/backend/test/test_task_run_artefacts.py
index 2fdc01942595..09f3e6ab2d38 100644
--- a/products/signals/backend/test/test_task_run_artefacts.py
+++ b/products/signals/backend/test/test_task_run_artefacts.py
@@ -229,6 +229,20 @@ class TestTaskRunArtefacts(BaseTest):
assert artefact.task_id is None
assert artefact.created_by_id is None
+ def test_custom_agent_report_is_stamped_first_visible_at_creation(self):
+ # Born READY without passing through transition_to, so creation must stamp first_visible_at
+ # or the daily report limit would never count custom-agent reports.
+ persisted = create_custom_agent_ready_report(
+ team_id=self.team.id,
+ final_report=self._final_report(),
+ repo_selection=RepoSelectionResult(repository="acme/repo", reason="r"),
+ task_id=None,
+ agent_identifier=("billing", "anomaly_scan"),
+ )
+
+ report = SignalReport.objects.get(id=persisted.report_id)
+ assert report.first_visible_at is not None
+
class TestAssociatedTaskRunsFilter(BaseTest):
"""`SignalReport.associated_task_runs_filter` matches a TaskRun whose task is associated with
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 6c482495dec0..248d99591b84 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -840,7 +840,7 @@ export const getSignalsScoutConfigRunUrl = (projectId: string, id: string) => {
}
/**
- * Dispatch one on-demand run of this scout immediately, regardless of its schedule. Useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously on the worker and inherits every guard the scheduled path has: it is forbidden if scouts are not enabled for the project (403), and skipped if the project is over its Signals credits quota or daily run budget (429) or a run for this scout is already in progress (409). A manual run counts against the same daily run budget as scheduled runs, so repeated manual runs of the same scout can exhaust the project's daily allowance. A manual run does not change the scout's schedule or `last_run_at`. A disabled scout can still be run this way (to test before enabling). Returns immediately with the workflow id — poll the scout's runs for the result.
+ * Dispatch one on-demand run of this scout immediately, regardless of its schedule. Useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously on the worker and inherits every guard the scheduled path has: it is forbidden if scouts are not enabled for the project (403), and skipped if the project is over its Signals credits quota, daily report limit, or daily run budget (429) or a run for this scout is already in progress (409). A manual run counts against the same daily run budget as scheduled runs, so repeated manual runs of the same scout can exhaust the project's daily allowance. A manual run does not change the scout's schedule or `last_run_at`. A disabled scout can still be run this way (to test before enabling). Returns immediately with the workflow id — poll the scout's runs for the result.
* @summary Run a scout now
*/
export const signalsScoutConfigRun = async (
diff --git a/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx b/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx
new file mode 100644
index 000000000000..28c6043497eb
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx
@@ -0,0 +1,57 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { useStorybookMocks } from '~/mocks/browser'
+
+import { SelfDrivingSection } from './SelfDrivingSection'
+
+interface SectionState {
+ dailyLimit: number | null
+ reportsToday: number
+}
+
+function StateMocks({ state }: { state: SectionState }): JSX.Element {
+ useStorybookMocks({
+ get: {
+ '/api/projects/:team_id/signals/config/': {
+ id: 'cfg-1',
+ autostart_enabled: true,
+ default_autostart_priority: 'P4',
+ autostart_base_branches: {},
+ max_reports_per_day: state.dailyLimit,
+ reports_generated_today: state.reportsToday,
+ daily_report_limit_reached: state.dailyLimit != null && state.reportsToday >= state.dailyLimit,
+ },
+ '/api/environments/:team_id/integrations/': { results: [] },
+ },
+ })
+ // Mimic the agents rail's narrow column so the card lays out as it does in the scene.
+ return (
+ <div className="w-[260px] p-4 bg-surface-secondary">
+ <SelfDrivingSection />
+ </div>
+ )
+}
+
+const meta: Meta = {
+ title: 'Scenes-App/Inbox/SelfDrivingSection',
+ component: SelfDrivingSection,
+ parameters: {
+ layout: 'centered',
+ viewMode: 'story',
+ },
+}
+export default meta
+
+type Story = StoryObj
+
+export const NoDailyLimit: Story = {
+ render: () => <StateMocks state={{ dailyLimit: null, reportsToday: 0 }} />,
+}
+
+export const DailyLimitSet: Story = {
+ render: () => <StateMocks state={{ dailyLimit: 10, reportsToday: 3 }} />,
+}
+
+export const DailyLimitReached: Story = {
+ render: () => <StateMocks state={{ dailyLimit: 10, reportsToday: 10 }} />,
+}
diff --git a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
index 27cac8afa671..4ed6e7f67367 100644
--- a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { IconPlus, IconRocket, IconX } from '@posthog/icons'
-import { LemonSegmentedButton, LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonSegmentedButton, LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'
import {
Button,
ButtonGroup,
@@ -21,6 +21,7 @@ import { GitHubBranchCombobox } from 'lib/integrations/GitHubBranchCombobox'
import { GitHubRepositoryCombobox } from 'lib/integrations/GitHubRepositoryCombobox'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { inboxUsageLogic } from '../../logics/inboxUsageLogic'
import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'
import { PRIORITY_THRESHOLD_OPTIONS, SignalReportPriority } from '../../types'
@@ -220,6 +221,78 @@ function BaseBranchOverrides(): JSX.Element {
)
}
+/**
+ * A self-imposed cap on reports per day, deliberately housed with the autonomy throttles rather
+ * than the billing usage card: it is "how much should the agents do", not "what does the plan
+ * allow", and placing it next to plan usage read as if the two limits were one system. Renders
+ * regardless of the auto-start toggle, since the cap pauses report generation, not just PRs.
+ * While the billing quota has the pipeline paused, the live count is withheld so remaining daily
+ * headroom is not advertised on a day when nothing will arrive. Same collapsed-by-default shape
+ * as Base branch overrides: the trigger's count keeps the state readable without opening.
+ */
+function DailyReportLimit(): JSX.Element {
+ const {
+ maxReportsPerDay,
+ reportsGeneratedToday,
+ dailyReportLimitReached,
+ draftMaxReportsPerDay,
+ saveMaxReportsPerDayDisabledReason,
+ teamConfigUpdating,
+ } = useValues(signalTeamConfigLogic)
+ const { setDraftMaxReportsPerDay, saveDraftMaxReportsPerDay } = useActions(signalTeamConfigLogic)
+ const { quotaLimited } = useValues(inboxUsageLogic)
+
+ const summary = quotaLimited
+ ? 'Paused by plan limit'
+ : maxReportsPerDay != null
+ ? `${Math.min(reportsGeneratedToday, maxReportsPerDay)} / ${maxReportsPerDay} today`
+ : null
+
+ return (
+ <>
+ <Collapsible className="bg-transparent hover:bg-transparent">
+ <CollapsibleTrigger className="w-full h-auto px-2.5 py-1.5 text-xs text-secondary font-normal bg-transparent hover:bg-[var(--fill-hover)]">
+ <span className="flex-1 text-left">Daily report limit</span>
+ {summary && <span className="text-tertiary tabular-nums">{summary}</span>}
+ </CollapsibleTrigger>
+ <CollapsibleContent className="flex flex-col gap-1.5 px-2.5 pb-1.5">
+ <p className="text-[11px] text-tertiary leading-snug mb-0">
+ Pause new report generation after this many reports in a day. Leave empty for no limit.
+ </p>
+ <div className="flex items-center gap-1">
+ <LemonInput
+ type="number"
+ min={1}
+ step={1}
+ size="small"
+ placeholder="No limit"
+ value={draftMaxReportsPerDay ?? undefined}
+ onChange={(value) => setDraftMaxReportsPerDay(value ?? null)}
+ onPressEnter={saveDraftMaxReportsPerDay}
+ fullWidth
+ />
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={saveDraftMaxReportsPerDay}
+ loading={teamConfigUpdating}
+ disabledReason={saveMaxReportsPerDayDisabledReason ?? undefined}
+ data-attr="signals-daily-report-limit-save"
+ >
+ Save
+ </LemonButton>
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ {dailyReportLimitReached && !quotaLimited && (
+ <p className="text-xs font-medium text-danger mb-0 px-2.5 pb-1.5">
+ Daily report limit reached. New reports resume at midnight in your project's timezone.
+ </p>
+ )}
+ </>
+ )
+}
+
/**
* Team-wide PR-generation control, backed by `autostart_enabled` and `default_autostart_priority`
* on `signalTeamConfigLogic`. The inline switch is the master opt-out for autonomous inbox PRs;
@@ -280,6 +353,9 @@ export function SelfDrivingSection(): JSX.Element {
Reports still arrive and notify your team.
</p>
)}
+ <div className="border-t border-primary">
+ <DailyReportLimit />
+ </div>
</div>
</div>
)
diff --git a/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx b/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx
index 34de75eaab86..8659b470ba70 100644
--- a/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx
+++ b/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx
@@ -11,6 +11,7 @@ import { cn } from 'lib/utils/css-classes'
import { GithubIntegration } from 'scenes/integrations/components/GithubIntegration'
import { urls } from 'scenes/urls'
+import { inboxUsageLogic } from '../../logics/inboxUsageLogic'
import { scoutFleetLogic } from '../../logics/scoutFleetLogic'
import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'
import { userAutonomyLogic } from '../../logics/userAutonomyLogic'
@@ -311,6 +312,9 @@ function SetupModal(): JSX.Element {
export function AgentSetupColumn({ layout }: { layout: 'rail' | 'stacked' }): JSX.Element {
useMountedLogic(integrationsLogic)
useMountedLogic(signalSourcesLogic)
+ // The usage widget renders nothing without the billing product, so the section title
+ // must hide with it rather than sit over an empty area.
+ const { product: inboxUsageProduct, isLoading: inboxUsageLoading } = useValues(inboxUsageLogic)
return (
<div
@@ -329,9 +333,11 @@ export function AgentSetupColumn({ layout }: { layout: 'rail' | 'stacked' }): JS
<CodeAccessWidget />
<NotificationsWidget />
</SetupSection>
- <SetupSection title="Usage">
- <InboxUsageWidget />
- </SetupSection>
+ {(inboxUsageProduct != null || inboxUsageLoading) && (
+ <SetupSection title="Usage">
+ <InboxUsageWidget />
+ </SetupSection>
+ )}
<SetupModal />
</div>
)
diff --git a/products/signals/frontend/inbox/components/shell/InboxUsageWidget.tsx b/products/signals/frontend/inbox/components/shell/InboxUsageWidget.tsx
index 3ff86e0b2c21..dda2e5487173 100644
--- a/products/signals/frontend/inbox/components/shell/InboxUsageWidget.tsx
+++ b/products/signals/frontend/inbox/components/shell/InboxUsageWidget.tsx
@@ -135,7 +135,8 @@ function EditLimitModal(): JSX.Element {
* alongside it, then `X / Y PRs created` on the left and `Resets <date>` on the right. On a paid plan
* the limit is editable (and the edit affordance escalates to "Increase limit" at the cap); on the
* free plan it shows an in-place upgrade instead. Renders nothing until billing has loaded and the
- * inbox product is present.
+ * inbox product is present. Deliberately billing-only: the team's daily report cap lives with the
+ * autonomy throttles in SelfDrivingSection, so a self-imposed cap never reads as a plan limit.
*/
export function InboxUsageWidget(): JSX.Element | null {
const {
diff --git a/products/signals/frontend/inbox/logics/inboxUsageLogic.test.ts b/products/signals/frontend/inbox/logics/inboxUsageLogic.test.ts
index e853619a30fd..c135ed943bfa 100644
--- a/products/signals/frontend/inbox/logics/inboxUsageLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/inboxUsageLogic.test.ts
@@ -137,6 +137,10 @@ describe('inboxUsageLogic', () => {
404,
{ detail: 'PR refunds are not enabled for this organization.' },
],
+ '/api/projects/:team_id/signals/config/': () => [
+ 200,
+ { id: 'cfg-1', default_autostart_priority: 'P4' },
+ ],
},
})
featureFlagLogic.mount()
diff --git a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.test.ts b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.test.ts
index 610277a1517b..7e6aa46dff49 100644
--- a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.test.ts
@@ -114,6 +114,246 @@ describe('signalTeamConfigLogic', () => {
expect(lastPostBody?.autostart_base_branches).toEqual({ 'acme/web': 'release', 'acme/api': 'develop' })
})
+ it('saves and clears the daily report limit through the draft', async () => {
+ await mountWith({})
+ logic.actions.setDraftMaxReportsPerDay(5)
+ expect(logic.values.saveMaxReportsPerDayDisabledReason).toBeNull()
+ logic.actions.saveDraftMaxReportsPerDay()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(lastPostBody).toEqual({ max_reports_per_day: 5 })
+ expect(logic.values.maxReportsPerDay).toBe(5)
+
+ logic.actions.setDraftMaxReportsPerDay(null)
+ logic.actions.saveDraftMaxReportsPerDay()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(lastPostBody).toEqual({ max_reports_per_day: null })
+ expect(logic.values.maxReportsPerDay).toBeNull()
+ })
+
+ it('keeps an unsaved daily limit draft when an unrelated setting is saved', async () => {
+ await mountWith({})
+ logic.actions.setDraftMaxReportsPerDay(7)
+ // Saving a different field on this shared singleton logic must not re-anchor the draft.
+ logic.actions.patchTeamConfig({ autostart_enabled: false })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.draftMaxReportsPerDay).toBe(7)
+ })
+
+ it('keeps an unsaved daily limit draft when an unrelated save fails and reloads', async () => {
+ const serverConfig: SignalTeamConfig = {
+ id: 'cfg-1',
+ autostart_enabled: true,
+ default_autostart_priority: 'P4',
+ autostart_base_branches: {},
+ }
+ useMocks({
+ get: { '/api/projects/:team_id/signals/config/': () => [200, serverConfig] },
+ post: { '/api/projects/:team_id/signals/config/': () => [500, { detail: 'Failed to save' }] },
+ })
+ initKeaTests()
+ logic = signalTeamConfigLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setDraftMaxReportsPerDay(7)
+ // The failed patch triggers a reload; the reseed guard must not clobber the unsaved draft.
+ logic.actions.patchTeamConfig({ autostart_enabled: false })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.draftMaxReportsPerDay).toBe(7)
+ })
+
+ it('refreshes the config when the user returns to the tab, without wiping the draft', async () => {
+ let reportsToday = 3
+ useMocks({
+ get: {
+ '/api/projects/:team_id/signals/config/': () => [
+ 200,
+ {
+ id: 'cfg-1',
+ autostart_enabled: true,
+ default_autostart_priority: 'P4',
+ autostart_base_branches: {},
+ max_reports_per_day: 10,
+ reports_generated_today: reportsToday,
+ },
+ ],
+ },
+ })
+ initKeaTests()
+ logic = signalTeamConfigLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.reportsGeneratedToday).toBe(3)
+
+ logic.actions.setDraftMaxReportsPerDay(7)
+ reportsToday = 9
+ // jsdom's visibilityState is 'visible', so this dispatch is a return-to-tab.
+ document.dispatchEvent(new Event('visibilitychange'))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.reportsGeneratedToday).toBe(9)
+ // The reseed guard must hold for this reload path too, not just failure reloads.
+ expect(logic.values.draftMaxReportsPerDay).toBe(7)
+ })
+
+ it('does not save the daily limit while a config request is in flight', async () => {
+ let getCount = 0
+ let resolveRefresh: (() => void) | undefined
+ const postBodies: Partial<SignalTeamConfig>[] = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/signals/config/': async () => {
+ getCount += 1
+ if (getCount > 1) {
+ // Hold the refresh GET open so a save can land while it is in flight.
+ await new Promise<void>((resolve) => {
+ resolveRefresh = resolve
+ })
+ }
+ return [
+ 200,
+ {
+ id: 'cfg-1',
+ autostart_enabled: true,
+ default_autostart_priority: 'P4',
+ autostart_base_branches: {},
+ max_reports_per_day: null,
+ },
+ ]
+ },
+ },
+ post: {
+ '/api/projects/:team_id/signals/config/': async ({ request }) => {
+ const body = (await request.json()) as Partial<SignalTeamConfig>
+ postBodies.push(body)
+ return [200, { id: 'cfg-1', autostart_enabled: true, default_autostart_priority: 'P4', ...body }]
+ },
+ },
+ })
+ initKeaTests()
+ logic = signalTeamConfigLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ // Type a new limit, then a background refresh starts (jsdom's visibilityState is 'visible').
+ logic.actions.setDraftMaxReportsPerDay(5)
+ document.dispatchEvent(new Event('visibilitychange'))
+ await waitFor(() => expect(logic.values.teamConfigLoading).toBe(true))
+ // The draft differs from the saved value, so only the in-flight guard can block the save.
+ expect(logic.values.saveMaxReportsPerDayDisabledReason).toBeNull()
+
+ // Pressing Enter while the refresh GET is in flight must not fire a racing PATCH.
+ logic.actions.saveDraftMaxReportsPerDay()
+ expect(postBodies).toHaveLength(0)
+
+ resolveRefresh?.()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it('throttles rapid tab-return refreshes to one request per window', async () => {
+ let getCount = 0
+ useMocks({
+ get: {
+ '/api/projects/:team_id/signals/config/': () => {
+ getCount += 1
+ return [
+ 200,
+ {
+ id: 'cfg-1',
+ autostart_enabled: true,
+ default_autostart_priority: 'P4',
+ autostart_base_branches: {},
+ },
+ ]
+ },
+ },
+ })
+ initKeaTests()
+ logic = signalTeamConfigLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(getCount).toBe(1)
+
+ // jsdom's visibilityState is 'visible', so each dispatch is a return-to-tab.
+ document.dispatchEvent(new Event('visibilitychange'))
+ await expectLogic(logic).toFinishAllListeners()
+ expect(getCount).toBe(2)
+
+ // A second return within the throttle window must not fire another GET.
+ document.dispatchEvent(new Event('visibilitychange'))
+ await expectLogic(logic).toFinishAllListeners()
+ expect(getCount).toBe(2)
+ })
+
+ it('stays out of the updating state during a background tab-return refresh', async () => {
+ let getCount = 0
+ let resolveRefresh: (() => void) | undefined
+ useMocks({
+ get: {
+ '/api/projects/:team_id/signals/config/': async () => {
+ getCount += 1
+ if (getCount > 1) {
+ // Hold the refresh GET open so its in-flight state can be observed.
+ await new Promise<void>((resolve) => {
+ resolveRefresh = resolve
+ })
+ }
+ return [
+ 200,
+ {
+ id: 'cfg-1',
+ autostart_enabled: true,
+ default_autostart_priority: 'P4',
+ autostart_base_branches: {},
+ },
+ ]
+ },
+ },
+ })
+ initKeaTests()
+ logic = signalTeamConfigLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ // jsdom's visibilityState is 'visible', so this dispatch is a return-to-tab.
+ document.dispatchEvent(new Event('visibilitychange'))
+ // The refresh GET is now in flight, but it is a load, not a save, so the controls stay enabled.
+ await waitFor(() => expect(logic.values.teamConfigLoading).toBe(true))
+ expect(logic.values.teamConfigUpdating).toBe(false)
+
+ resolveRefresh?.()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.teamConfigUpdating).toBe(false)
+ })
+
+ it('treats a cleared (NaN) daily limit input as unlimited', async () => {
+ await mountWith({})
+ logic.actions.setDraftMaxReportsPerDay(5)
+ logic.actions.saveDraftMaxReportsPerDay()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.maxReportsPerDay).toBe(5)
+
+ // A cleared number LemonInput emits NaN; it must reset the draft to null, not disable Save.
+ logic.actions.setDraftMaxReportsPerDay(Number.NaN)
+ expect(logic.values.draftMaxReportsPerDay).toBeNull()
+ expect(logic.values.saveMaxReportsPerDayDisabledReason).toBeNull()
+ logic.actions.saveDraftMaxReportsPerDay()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(lastPostBody).toEqual({ max_reports_per_day: null })
+ expect(logic.values.maxReportsPerDay).toBeNull()
+ })
+
+ it('blocks saving an invalid or unchanged daily report limit draft', async () => {
+ await mountWith({})
+ // Loading anchored the draft to the server value, so there is nothing to save yet.
+ expect(logic.values.saveMaxReportsPerDayDisabledReason).toBe('No changes to save')
+ logic.actions.setDraftMaxReportsPerDay(0)
+ expect(logic.values.saveMaxReportsPerDayDisabledReason).toBe('Enter a whole number of at least 1')
+ logic.actions.saveDraftMaxReportsPerDay()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(lastPostBody).toBeNull()
+ })
+
it('serializes rapid override updates so the latest map is persisted last', async () => {
const initialConfig: SignalTeamConfig = {
id: 'cfg-1',
diff --git a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts
index 6203c5f8931c..4ca6a2d36f6b 100644
--- a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts
+++ b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts
@@ -18,15 +18,25 @@ function isRepositoryKey(repo: string): boolean {
return parts.length === 2 && parts.every((part) => !!part)
}
+// Floor between return-to-tab refreshes; without it, alt-tab flapping turns into request bursts.
+// Mirrors inboxOnboardingLogic's VISIBILITY_REFETCH_THROTTLE_MS in this same folder.
+const VISIBILITY_REFETCH_THROTTLE_MS = 5 * 1000
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface signalTeamConfigLogicValues {
addBaseBranchOverrideDisabledReason: string | null
autostartEnabled: boolean
baseBranchOverrides: BaseBranchOverride[]
+ dailyReportLimitReached: boolean
defaultAutostartPriority: SignalReportPriority
draftBaseBranchBranch: string
draftBaseBranchIntegrationId: number | null
draftBaseBranchRepo: string
+ draftMaxReportsPerDay: number | null
+ maxReportsPerDay: number | null
+ patchesInFlight: number
+ reportsGeneratedToday: number
+ saveMaxReportsPerDayDisabledReason: string | null
teamConfig: SignalTeamConfig | null
teamConfigLoading: boolean
teamConfigUpdating: boolean
@@ -85,6 +95,9 @@ export interface signalTeamConfigLogicActions {
removeBaseBranchOverride: (repo: string) => {
repo: string
}
+ saveDraftMaxReportsPerDay: () => {
+ value: true
+ }
setDraftBaseBranchBranch: (branch: string) => {
branch: string
}
@@ -94,6 +107,9 @@ export interface signalTeamConfigLogicActions {
setDraftBaseBranchRepo: (repo: string) => {
repo: string
}
+ setDraftMaxReportsPerDay: (value: number | null) => {
+ value: number | null
+ }
updateBaseBranchOverride: (
repo: string,
branch: string
@@ -109,7 +125,14 @@ export interface signalTeamConfigLogicMeta {
autostartEnabled: (teamConfig: SignalTeamConfig | null) => boolean
defaultAutostartPriority: (teamConfig: SignalTeamConfig | null) => SignalReportPriority
baseBranchOverrides: (teamConfig: SignalTeamConfig | null) => BaseBranchOverride[]
- teamConfigUpdating: (teamConfigLoading: boolean, teamConfig: SignalTeamConfig | null) => boolean
+ maxReportsPerDay: (teamConfig: SignalTeamConfig | null) => number | null
+ reportsGeneratedToday: (teamConfig: SignalTeamConfig | null) => number
+ dailyReportLimitReached: (teamConfig: SignalTeamConfig | null) => boolean
+ teamConfigUpdating: (patchesInFlight: number) => boolean
+ saveMaxReportsPerDayDisabledReason: (
+ draftMaxReportsPerDay: number | null,
+ maxReportsPerDay: number | null
+ ) => string | null
addBaseBranchOverrideDisabledReason: (
draftBaseBranchRepo: string,
draftBaseBranchBranch: string
@@ -150,6 +173,8 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
addBaseBranchOverride: true,
updateBaseBranchOverride: (repo: string, branch: string) => ({ repo, branch }),
removeBaseBranchOverride: (repo: string) => ({ repo }),
+ setDraftMaxReportsPerDay: (value: number | null) => ({ value }),
+ saveDraftMaxReportsPerDay: true,
}),
loaders(() => {
// Every patch of `autostart_base_branches` sends the whole map, so two in flight at once let the
@@ -211,6 +236,32 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
clearDraftBaseBranch: () => '',
},
],
+ // A save is in flight while this is above zero. Tracked explicitly rather than read off
+ // teamConfigLoading, because that flag also flips for the initial load and the background
+ // tab-return refresh (both plain GETs), neither of which should disable the save controls.
+ patchesInFlight: [
+ 0,
+ {
+ patchTeamConfig: (state: number) => state + 1,
+ patchTeamConfigSuccess: (state: number) => Math.max(0, state - 1),
+ patchTeamConfigFailure: (state: number) => Math.max(0, state - 1),
+ },
+ ],
+ // The daily-limit input's draft. Seeded from the server once on first load (see the
+ // loadTeamConfigSuccess listener) and re-anchored only when its own save settles, so saving
+ // an unrelated setting on this shared singleton logic never wipes an unsaved edit.
+ draftMaxReportsPerDay: [
+ null as number | null,
+ {
+ // A cleared number LemonInput emits NaN, which is never a valid draft — treat it as
+ // null ("no limit") so the field can be reset to unlimited.
+ setDraftMaxReportsPerDay: (_, { value }) => (value != null && Number.isNaN(value) ? null : value),
+ patchTeamConfigSuccess: (state, { teamConfig, payload }) =>
+ payload?.patch && 'max_reports_per_day' in payload.patch
+ ? (teamConfig?.max_reports_per_day ?? null)
+ : state,
+ },
+ ],
}),
selectors({
// Master switch for autonomous inbox PRs: only an explicit false disables
@@ -231,12 +282,35 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
.map(([repo, branch]) => ({ repo, branch }))
.sort((a, b) => a.repo.localeCompare(b.repo)),
],
- // One loader serves both the initial fetch and every patch, so what separates them is whether
- // there's already a config on screen to be updating.
- teamConfigUpdating: [
- (s) => [s.teamConfigLoading, s.teamConfig],
- (teamConfigLoading: boolean, teamConfig: SignalTeamConfig | null): boolean =>
- teamConfigLoading && teamConfig !== null,
+ maxReportsPerDay: [
+ (s) => [s.teamConfig],
+ (teamConfig: SignalTeamConfig | null): number | null => teamConfig?.max_reports_per_day ?? null,
+ ],
+ reportsGeneratedToday: [
+ (s) => [s.teamConfig],
+ (teamConfig: SignalTeamConfig | null): number => teamConfig?.reports_generated_today ?? 0,
+ ],
+ dailyReportLimitReached: [
+ (s) => [s.teamConfig],
+ (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.daily_report_limit_reached === true,
+ ],
+ // True only while a save (patch) is in flight. Deliberately not derived from teamConfigLoading:
+ // the shared loader also raises that flag for the initial load and the background tab-return
+ // refresh, and neither should disable the save controls or show a "Saving changes" state.
+ teamConfigUpdating: [(s) => [s.patchesInFlight], (patchesInFlight: number): boolean => patchesInFlight > 0],
+ // Doubles as the save button's tooltip, same single-statement pattern as
+ // addBaseBranchOverrideDisabledReason below.
+ saveMaxReportsPerDayDisabledReason: [
+ (s) => [s.draftMaxReportsPerDay, s.maxReportsPerDay],
+ (draftMaxReportsPerDay: number | null, maxReportsPerDay: number | null): string | null => {
+ if (
+ draftMaxReportsPerDay !== null &&
+ (!Number.isInteger(draftMaxReportsPerDay) || draftMaxReportsPerDay < 1)
+ ) {
+ return 'Enter a whole number of at least 1'
+ }
+ return draftMaxReportsPerDay === maxReportsPerDay ? '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.
@@ -293,6 +367,24 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
delete next[repo]
actions.patchTeamConfig({ autostart_base_branches: next })
},
+ saveDraftMaxReportsPerDay: () => {
+ // Guard the Enter path against double-submission: the Save button disables itself while
+ // a save runs, but LemonInput's onPressEnter does not, so also bail while any request
+ // for this singleton is in flight. A save must not race a concurrent GET or PATCH — they
+ // share one loader key with no ordering, so a late response could clobber the saved value.
+ if (values.saveMaxReportsPerDayDisabledReason || values.teamConfigLoading) {
+ return
+ }
+ actions.patchTeamConfig({ max_reports_per_day: values.draftMaxReportsPerDay })
+ },
+ loadTeamConfigSuccess: ({ teamConfig }) => {
+ // Seed the draft 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
+ actions.setDraftMaxReportsPerDay(teamConfig?.max_reports_per_day ?? null)
+ }
+ },
patchTeamConfigSuccess: ({ payload }) => {
captureSettled(true)
if (payload?.clearDraftOnSuccess) {
@@ -307,7 +399,28 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
},
}
}),
- afterMount(({ actions }) => {
+ afterMount(({ actions, values, cache }) => {
actions.loadTeamConfig()
+ // Refresh on return to the tab: reports keep generating in the background, so the
+ // daily-limit count and reached-banner would otherwise stay stale until a reload or save.
+ cache.disposables.add(
+ () => {
+ const handler = (): void => {
+ if (document.visibilityState !== 'visible' || values.teamConfigLoading) {
+ return
+ }
+ const now = Date.now()
+ if (now - (cache.lastVisibilityRefetch ?? 0) < VISIBILITY_REFETCH_THROTTLE_MS) {
+ return
+ }
+ cache.lastVisibilityRefetch = now
+ actions.loadTeamConfig()
+ }
+ document.addEventListener('visibilitychange', handler)
+ return () => document.removeEventListener('visibilitychange', handler)
+ },
+ 'refreshOnTabReturn',
+ { pauseOnPageHidden: false }
+ )
}),
])
diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.ts
index b6e97fb4d571..3e14b16a7537 100644
--- a/products/signals/frontend/inbox/types.ts
+++ b/products/signals/frontend/inbox/types.ts
@@ -283,6 +283,12 @@ export interface SignalTeamConfig {
default_slack_notification_channel?: string | null
/** Per-repo base-branch overrides for auto-started PRs, keyed by 'org/repo'. */
autostart_base_branches?: Record<string, string>
+ /** Daily cap on new reports surfacing to the inbox (project-timezone day). Null means unlimited. */
+ max_reports_per_day?: number | 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. */
+ daily_report_limit_reached?: boolean
created_at?: string
updated_at?: string
}
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index f4c1a7b966de..8c8f61b5be31 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -860,7 +860,7 @@ export const SignalsScoutConfigDestroyParams = /* @__PURE__ */ zod.object({
})
/**
- * Dispatch one on-demand run of this scout immediately, regardless of its schedule. Useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously on the worker and inherits every guard the scheduled path has: it is forbidden if scouts are not enabled for the project (403), and skipped if the project is over its Signals credits quota or daily run budget (429) or a run for this scout is already in progress (409). A manual run counts against the same daily run budget as scheduled runs, so repeated manual runs of the same scout can exhaust the project's daily allowance. A manual run does not change the scout's schedule or `last_run_at`. A disabled scout can still be run this way (to test before enabling). Returns immediately with the workflow id — poll the scout's runs for the result.
+ * Dispatch one on-demand run of this scout immediately, regardless of its schedule. Useful to test a scout right after authoring it, or to refresh its findings on demand. The run executes asynchronously on the worker and inherits every guard the scheduled path has: it is forbidden if scouts are not enabled for the project (403), and skipped if the project is over its Signals credits quota, daily report limit, or daily run budget (429) or a run for this scout is already in progress (409). A manual run counts against the same daily run budget as scheduled runs, so repeated manual runs of the same scout can exhaust the project's daily allowance. A manual run does not change the scout's schedule or `last_run_at`. A disabled scout can still be run this way (to test before enabling). Returns immediately with the workflow id — poll the scout's runs for the result.
* @summary Run a scout now
*/
export const SignalsScoutConfigRunParams = /* @__PURE__ */ zod.object({