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.

fix(signals): archive trials and scope run loading errors (#114572)

Alex Lebedevfee9246f5ac9
diff --git a/docs/internal/scout-online-evals-devbox.md b/docs/internal/scout-online-evals-devbox.md
index 22f2d309d361..7443f655a4a7 100644
--- a/docs/internal/scout-online-evals-devbox.md
+++ b/docs/internal/scout-online-evals-devbox.md
@@ -47,6 +47,8 @@ Revoke or expire private tokens before rolling the gateway back to a version wit
The rubric stays fixed across scout edits, and saved results retain the rubric used for that trial. If a run is interrupted, reopen the existing trial before starting another paid attempt.
+History shows 30 trials per page, with previous and next controls for older results. Archive a completed or failed trial to hide it from history. Show archived trials to view their saved reports or restore them; archiving never deletes evidence or stops a running trial. Archive and restore remain available when the trials flag is off, with the same access checks. Open a trial to see its individual runs. Run-detail loading errors appear beside the affected run with a retry action, while the history page continues to show saved results.
+
Trial scouts have a 30-minute runtime limit. Regular scouts keep their 15-minute limit. Timed-out scouts cannot be scored; start a new trial to try again.
Trial scout deadlines include five minutes for startup and log reads, plus time to collect and save the final result.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e27442865db1..423d5a67f8dd 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11220,6 +11220,10 @@ snapshots:
hash: v1.k794b7964.9cf8176ad44b0563ecc481e6efefde6f516c9ddc2d2a973e3cf9d8ade0bccb0e.ERV9ltQ2LPFqcLeFW1MrxcOXLWYFmwZgm73uqyE4aAI
scenes-app-inbox-scout-comparison-report--twelve-rubrics-narrow--light:
hash: v1.k794b7964.481b6146b8c00208b408cee3bc04af2674277a2ed91e7d66665077671afaed07.a8lIdTdMTxzmGA7VPzBP6cKlTfjTXa5SJ540vbfN_BQ
+ scenes-app-inbox-scout-comparisons--archived--dark:
+ hash: v1.k794b7964.d79efd52758535007dda391ffa79c431fc723269aa9063f13953ac53d933b20d.g0dlEEoVoPSiCLJbBapVwSmLN4GjGPBRdG1XMYPDHaE
+ scenes-app-inbox-scout-comparisons--archived--light:
+ hash: v1.k794b7964.2d21cec92c1105667d1da96e7995773a8d67453cefae68ac0a8471dfcbd484e1.TVXGG7Vxpcr8boyKqYV8coOasOLiafqxUPzCQqTuSS0
scenes-app-inbox-scout-comparisons--disabled--dark:
hash: v1.k794b7964.1ce389f3e3a5ba0eff3a45e629a3e02c4725c6bc2de1b146046406b86f79cf2a.lWA9iziUe2UTjly9npOQrqLCHBe1GcDq63-GUrCqNQU
scenes-app-inbox-scout-comparisons--disabled--light:
@@ -11229,25 +11233,25 @@ snapshots:
scenes-app-inbox-scout-comparisons--error--light:
hash: v1.k794b7964.8d219f419b1aba806315c0caaa2936d397b5a8ed5c17ed65d9f8e1de1a0cc1d1.dJe9rctG1oBbi7tLhweIJHhTlAEhgT2_UWJMdcGIDXg
scenes-app-inbox-scout-comparisons--history--dark:
- hash: v1.k794b7964.3722fd9114585b23d7b42a53c9369d898a5ee9a5edabcbc519ed2c4ee2d55531.1fYUFPBTmHkuBG-OA2D6L7IPmm74WWKRIO_F6gu_oqs
+ hash: v1.k794b7964.bb7bd7dea82d592b42da97b92b1cae2d27115fcb688e6731c1563d60cee00b1c.J8kSqJMjNkxzBPYbiELKjpxHpBF5DqFr3Mf9vTH-uDQ
scenes-app-inbox-scout-comparisons--history--light:
- hash: v1.k794b7964.0adc592213b4cdf445231c7ac94c5dc340e66bf73ec469d9a0a144a18cbe5957.PsWs5YUYfe0tAfBIdpMktSqMPUFo85C4km0z1jgT60Y
+ hash: v1.k794b7964.af0e31196c4ecf9237b466e17ecb78cc52d764996f0d20e445b12b696a9fd433.bQfP0_0MtFdud26bBjre9tKAHyRbAuQgvKyS1uwp9rM
scenes-app-inbox-scout-comparisons--history-narrow--dark:
- hash: v1.k794b7964.f406fb22d0ea37aafbbe8c2fc1a1e0b016df504e7dee73dbb4d3368cdd7f980f.Ofr61NuLdYO2G-0uSTwHOhsfLsBgmeKd6A3Ek0dFrwM
+ hash: v1.k794b7964.61f57af7b611bcd1ec13659bfdfdb9241fd154e6bbe1caff866a0f9f31b06395.82OJYVn1hMlTo25lEzsunV8XyLQvc3c6OUM5fwH8790
scenes-app-inbox-scout-comparisons--history-narrow--light:
- hash: v1.k794b7964.0a52883584f3f19fc57e58a24376c3dcc371b616967aeb7f5a80ac05a1d537f0.rYMQDCVAl1amJg9BIJUcG6qv0LCEAUqM8W_uC-zpklA
+ hash: v1.k794b7964.dfb1880f515a414343f1a9a5bcec3582eaa87cb47930709a3a07f281eb4352a2.oDnNVZC2Z7_xeX34EDZuXgLIuhoxE60LbcktiNG5Id8
scenes-app-inbox-scout-comparisons--idle--dark:
- hash: v1.k794b7964.7d04d46238fac53fbca14a26a4a5756da5ab96a1784340e0a847bb391fd2e1c1.Y9_V5oZwGzKqXaNRstsgQP-77oZ1JZ6aLZuVg17huLI
+ hash: v1.k794b7964.0ce009766434866d9827637fae2d78be7bbf405c8fb2438c15abd133e96f4524.2AIDXZYipLJaP3rGbZA61J13VGZOpJaMHhd_yXB5ogQ
scenes-app-inbox-scout-comparisons--idle--light:
- hash: v1.k794b7964.a4f89e3346dfdbefd1307d299d693c867d804287252c3e39cf193bde87e2719a.gco8Ny3dGVniIb1tURE7xSneGMPj2mIeyyiSD4HOBUU
+ hash: v1.k794b7964.ced1b85e89f21d34e9986e4190be7a79a1e669e2d830cf943b1ed4982011c216.FFhoZ7SxbuLos2BVpWdxn8-_k8go5T7T_FUSOsk_OlQ
scenes-app-inbox-scout-comparisons--loading--dark:
hash: v1.k794b7964.e33c9e76913c6a2ec05a47e35a96bf3abacdd30df2193c2d87ce24205165c250.mhh6xV7B1fq41uh4vld9aq_Ku887x2xjfjZw8Iet70s
scenes-app-inbox-scout-comparisons--loading--light:
hash: v1.k794b7964.fae1773a8784657a9dd1bd51c1b570e8c15f9241ad8d036b1b156f36825878b9.oOu9d0u7ST7-M7zYyck7t9jqn7XeIQHlxsx5YNqqH68
scenes-app-inbox-scout-comparisons--many-rubrics--dark:
- hash: v1.k794b7964.1738cecc990c9f350f92b2fabdcfb56eb24591660cb47c19a54030e8a2c445fa.UeCbsoS5pJ4ddUyd_jtGdPbTzSLC9LE3PJ_XSDnrGJ0
+ hash: v1.k794b7964.cbe8c0154013b6efcac26021b143cc6863eb82e71549e54f49b8ec8f4e0f0ace.dO340mgPLkHDwmSPd1dYnC4rjVvuvoaOUtPFL-3TvXQ
scenes-app-inbox-scout-comparisons--many-rubrics--light:
- hash: v1.k794b7964.b1244ec442e77a5fa630f9aaaf9d1fceae5878d63db09d12757d77581f0de85e.CaopCLUHQAIOPntKw2lrP_gUIbuk6LhRWJv1TKdg1Qg
+ hash: v1.k794b7964.5df26dccf7b8cf5960878c5faf5f6cd6a837f073d086b2db497003db8b66fbd2.SowFWB7XSAu_5YPzXHAAfVMWJgjxdm5rdPqVtCDN1lM
scenes-app-inbox-scout-comparisons--many-rubrics-narrow--dark:
hash: v1.k794b7964.202841a7046db4a42fd3f1864a57a4d55fdcd1dbbb4bfc9e93a0b14232fd9560.tFEFTbkmVxeRo9Oo0WhdxJ_wciCqkTm1dHj1kePcFUQ
scenes-app-inbox-scout-comparisons--many-rubrics-narrow--light:
@@ -11260,6 +11264,10 @@ snapshots:
hash: v1.k794b7964.64e26d4eecdc41fb094b826f3865afaaaeef864a84f9e8afa7d14d6d5348a6a2.BNr70NN4Nbxz7d--Rjyn1ChHNvMIc04iCDTnyTBpmrQ
scenes-app-inbox-scout-comparisons--narrow--light:
hash: v1.k794b7964.9c82534c7ac6a859f168a15b06304b37c0ecae5ca64c745b235e6ef52f612025.rENRZ5rJ-OEE4x3SrPb3qabOqQX4fVoIfp7YsL8LZRQ
+ scenes-app-inbox-scout-comparisons--run-details-unavailable--dark:
+ hash: v1.k794b7964.3c016a1395a30c1214f1ae7c6e081700afa5f23807f30704f2c02c023b1fb1c9.a7sqEt-Eac9xbRHVyrOQcgtO0XNIVLvpKjyfQXi8FDE
+ scenes-app-inbox-scout-comparisons--run-details-unavailable--light:
+ hash: v1.k794b7964.8b3bbb625dcff883e259f002d3d4c650cedbf9f9a21d56b98254896874ff2265.HStZjeLdVoYRo4A4K7hSQJ21BJQwcbYkJQQkV9ENGZs
scenes-app-inbox-scout-comparisons--running--dark:
hash: v1.k794b7964.9a3e868936bf1017d283ac618c53eaefbdb0bdb908aa8c746fb607a81f23f5d1.ooPHbC8I9aHhq06iTP8nGdqCPWLifR_AE6sbKxFmxNo
scenes-app-inbox-scout-comparisons--running--light:
@@ -11269,17 +11277,17 @@ snapshots:
scenes-app-inbox-scout-comparisons--running-narrow--light:
hash: v1.k794b7964.0632ed3f575ede03298517f28143be6a4ccbc6ae6a26899ab4594a2caa75d790.gQ_D2rm8Ohh7Rk0VrFcW1RFnsuiYH6sovnxm7xl9Bxc
scenes-app-inbox-scout-comparisons--scored--dark:
- hash: v1.k794b7964.f5211f2a0159b52811e88b0ca0ecd321b57b397b1f445a26d3987b2aa8f0b057.LqHYg19SvelJMn8E0cwPVNGR-oLKS3im4kAHmHLWbOM
+ hash: v1.k794b7964.f3661b7f31dce3f4f203f3f0330357a03b0189a05dc2933890d61bb9f6515601.1PQigdYmDLF30RBjjBq1q5kJ9N6FZq19zYdyu3nTgCw
scenes-app-inbox-scout-comparisons--scored--light:
- hash: v1.k794b7964.a0d1b7f7e59614bce59ff6a7ac012559b8856ebd51758d837135a21090e5e888.PoKGUUk9ixd4gfDvJQmzqBHQ35cbrNrblHuXGiVoIB8
+ hash: v1.k794b7964.f3a5e2f20df24053c5e6d93457d7c9b69d6197d22b9abbe6eab61e272c14d58d.et8rU3sDnPRmqFfRB86FwixaOOb0kl4xTV-SOn5vWi8
scenes-app-inbox-scout-comparisons--scored-narrow--dark:
hash: v1.k794b7964.8e9213a5f9628415367afd7564f156eae7666f832dbde6e863833b78a40c4ada.PAy7h5uc8-VBeYUrUFVcGZkJJ2g50aFFFa6khQM4GSE
scenes-app-inbox-scout-comparisons--scored-narrow--light:
hash: v1.k794b7964.f0437cc149985372ae4f679d50bf9876b38da564f68c0536b727462db36747db.TUIkBdQJfAA0VIhuUq8z5PY0rlOhu_Nuw9CIXFs9Pz4
scenes-app-inbox-scout-comparisons--scored-with-judge-error--dark:
- hash: v1.k794b7964.350edff5e48abf05ce127b87e3129045ce27a8474cbcaf0833ea45c8794a53d7.W9e31TztDWezagZc8EBF9CpjyTAVyN28MtyhSCHUNuE
+ hash: v1.k794b7964.c93b40e3960f14f2b3df60e2e61a310d76623ca2267555fb25a65f21c477e2e3.iqftelzyEFEDXeW5QR1myZ8Kyck5NH7SUGMpj0_szoo
scenes-app-inbox-scout-comparisons--scored-with-judge-error--light:
- hash: v1.k794b7964.9e54a028555f45b1fa5245a83a3197c6e346f624b06e2e87c7b3648bea87f405.07RfrOzQc7DTtXhafpyl2pevLantIIjI293_fZz5x2Q
+ hash: v1.k794b7964.04eab8f290c46ca9245d105742f1a30f832142b803d7330ca0b1d3ca28a1300a.qMmsG_g2u-KuRuVzEeQE_0ywkQvNLqrDfG_AsX8lVhQ
scenes-app-inbox-scout-comparisons--scoring--dark:
hash: v1.k794b7964.8520822da584372a1269788304b1b2c6876ddfe0e6394fa1d152fb041595e2e1.eF-e2oYCBolypY5GadwqVJGj3QQj6Ubk4kqGcCBHkBo
scenes-app-inbox-scout-comparisons--scoring--light:
@@ -11297,17 +11305,17 @@ snapshots:
scenes-app-inbox-scout-comparisons--wide--light:
hash: v1.k794b7964.53e27319e86fcb2918993900aaf488b6405308de17ff14ddbe2073b5757ba0ed.GHbHAKZ3QEONYiTleLwq2bqK5-ebFEdkNANN1lzb37s
scenes-app-inbox-scout-comparisons-interactive--disabled--dark:
- hash: v1.k794b7964.8e7645fce4fc532503f8784d2490abf066104915306a0c5b8305f414a76012c5.oBKFsbT85RJrJ4huElNpg9Kllvs_98LbTp1eTt92u8w
+ hash: v1.k794b7964.ffac6d9d683d1207d5d769a6daa4414b5d8d4890892502e956d1b84a25550259.4_6_SYfICMHOO5LFXcaBIWLXRa3dUpwyumEPZtpd4SQ
scenes-app-inbox-scout-comparisons-interactive--disabled--light:
- hash: v1.k794b7964.c796d8eebf19dc1792d6b3603123d141db2f32f020bd24b8f85988ad56fae337.Nmf0vcNFgQByNUJwRHPgmVDk2ckhafor5IrwDz302s8
+ hash: v1.k794b7964.14b6690de8cae8f70a2b9d2de606e217bb24f8aa2ecbeee5987780d86ec1e44c.QBP0sv3YAzRY6yS-EAbNRM7DLb83xGj_BBGIMfPmUqE
scenes-app-inbox-scout-comparisons-interactive--interactive--dark:
- hash: v1.k794b7964.547a62853e330f34d53826b01eb82bfe2163e7eedbbf86ef5089206273d5f060.KKxbD8YWbFvOBAqmAO6hnG8483WmwPvqLxW4BT2FYMM
+ hash: v1.k794b7964.cd052c60dab59e9f154f347b9052eed0d228dcccc5d1d2db5d1363eb21c2c7df.k0B0pOgviMky-hU2GyDHpYc82JOJyo9tH3c8djxKRt8
scenes-app-inbox-scout-comparisons-interactive--interactive--light:
- hash: v1.k794b7964.835e8f977d4626345c861a5718ee9d795efd4da66fb50c647102d49f38eccaa0.B6FXHHYYqSgiUmyhpgJp37odifCEMH2bNojmOfZWx0Y
+ hash: v1.k794b7964.2c724cfb7b5d9a8e15f937941b66bd5575a022b33cf2e6e282f348a21d5833bc.s78kxosEcaNAYi8Cz60d5lOhMCcyY_SFotGlXEFk8cE
scenes-app-inbox-scout-comparisons-interactive--running--dark:
- hash: v1.k794b7964.547a62853e330f34d53826b01eb82bfe2163e7eedbbf86ef5089206273d5f060.9ECagfdvs1bbKtNBUr_oQArj38hWzGhjIewSPG_Gzd4
+ hash: v1.k794b7964.cd052c60dab59e9f154f347b9052eed0d228dcccc5d1d2db5d1363eb21c2c7df.3KKQfuBxdAINbe5twrPNBaSyLTpGJiWRHM0MGmIcyFg
scenes-app-inbox-scout-comparisons-interactive--running--light:
- hash: v1.k794b7964.835e8f977d4626345c861a5718ee9d795efd4da66fb50c647102d49f38eccaa0.y9Yo-nONWsusEu4JGHhvuZp8H1ig3BdmukRw8qf__8I
+ hash: v1.k794b7964.2c724cfb7b5d9a8e15f937941b66bd5575a022b33cf2e6e282f348a21d5833bc.0teQG0zbWYrggZxddhCeGjKnmqekaSSzwIuZfs5R81I
scenes-app-inbox-scout-run-judgment--evidence--dark:
hash: v1.k794b7964.82d40c7f60f4be6d171ea66af4a50b130e7d546b576dc9f96b4f28933793c64b.4sbbhzJJlvyEi1i6H1YDa_206SAev8KVnFH3OYjkp_A
scenes-app-inbox-scout-run-judgment--evidence--light:
@@ -11425,13 +11433,13 @@ snapshots:
scenes-app-inbox-scoutdetailview--scout-page-non-staff--light:
hash: v1.k794b7964.b02062fb06fed2b8dcf9420248e766e7eeb568eed6ae95fdbd64cd492bb7a5cb.QRExoYG5mqVAJzaTmxuySi9THVuOFVKwiQDOIxQLWNs
scenes-app-inbox-scoutdetailview--scout-page-trials--dark:
- hash: v1.k794b7964.d704ac0527187eeccfca88b4fab46cf77df2aacbf48cc5de0bb42f4443f09ec1.1OPra5jWsi4bsowt-w72QCBqd1tmQSxcDrOJKQZDoDE
+ hash: v1.k794b7964.3a223f2531e459ba2a28208cf34b8a23d5112656540965023c198c2b20af913f.NkwQaQOnWuF0quACA0HuKHJUee2b2qoLyJPLOnAn3S4
scenes-app-inbox-scoutdetailview--scout-page-trials--light:
- hash: v1.k794b7964.00a00ca59cad10ce8ad438eb459a2226e435fb546169f5e152e0aabb8a8bf6a8.thBojAAQyy7LQ8q26dG-D1DkNZgxy3ZoO-EsoqIp2tM
+ hash: v1.k794b7964.eb5e2db873e189725b889360393ce3ec8b72906cec670d65893bf958f9dbcb35.yY8ej17thzHmYNKY1wr2vtms2ysohmKUUMzdqrDJSpo
scenes-app-inbox-scoutdetailview--scout-page-trials-narrow--dark:
- hash: v1.k794b7964.9dd3ba6e8b555bd9566508ec00e1a197ff5e3007e273402b5f0e225d67d6f573.O9YkCeoyOoy5OTLqwn3AZ8rtlazf2G2OesMMROFegB8
+ hash: v1.k794b7964.03bc63cb4d2d799205e6e6bbe59f40a82c12b444a288f4bad0578f68ca17bb15.kX0R-4VEbYkirUHg27e3jkzbgp4oA5aAgTAR1PJrlQw
scenes-app-inbox-scoutdetailview--scout-page-trials-narrow--light:
- hash: v1.k794b7964.29e841c62bbdfa0a774cda698b84d6baacfa8c44e85abef8d41210eaeb1e064c.y3dByJhpQCUNCFXLMR_vVGMJepQxgOqWfNAXbw5-LjQ
+ hash: v1.k794b7964.720f18582938628b8603898e5cde8320e1ac1689963910831af5a2d1d3d02168.D5cjOjUWZ8SApnk56YYWxKgmCjuZIspU8QaopOHUGAo
scenes-app-inbox-scoutmcpserverspicker--create-dialog-variant--dark:
hash: v1.k794b7964.afe2203f4dd53373a3203fcfa611b5b65555341bdc2fc7fd73c15c2d83914600.O4kSRnOgICuQDkyD2HJCwBXdzE-KwsfzWT98nm43_5A
scenes-app-inbox-scoutmcpserverspicker--create-dialog-variant--light:
diff --git a/products/signals/backend/scout_harness/trial_comparison.py b/products/signals/backend/scout_harness/trial_comparison.py
index 47950d3a7e6e..c4153885c6ec 100644
--- a/products/signals/backend/scout_harness/trial_comparison.py
+++ b/products/signals/backend/scout_harness/trial_comparison.py
@@ -85,13 +85,16 @@ def comparison_evaluation_request(request: TrialComparisonRequest) -> TrialEvalu
return request.evaluation_request()
-def list_comparison_history_keys(prefix: str, limit: int) -> list[str]:
+def list_comparison_history_keys(prefix: str, limit: int, *, start_after: str | None = None) -> list[str]:
client = object_storage.object_storage_client()
if not isinstance(client, object_storage.ObjectStorage):
raise object_storage.ObjectStorageError("Comparison history storage is unavailable.")
try:
response: dict[str, object] = client.aws_client.list_objects_v2(
- Bucket=settings.OBJECT_STORAGE_BUCKET, Prefix=prefix, MaxKeys=limit + 1
+ Bucket=settings.OBJECT_STORAGE_BUCKET,
+ Prefix=prefix,
+ MaxKeys=limit + 1,
+ **({"StartAfter": start_after} if start_after is not None else {}),
)
contents = response.get("Contents", [])
if not isinstance(contents, list):
@@ -99,7 +102,11 @@ def list_comparison_history_keys(prefix: str, limit: int) -> list[str]:
keys: list[str] = []
for item in contents:
key = item.get("Key") if isinstance(item, dict) else None
- if not isinstance(key, str) or not key.startswith(prefix):
+ if (
+ not isinstance(key, str)
+ or not key.startswith(prefix)
+ or (start_after is not None and key <= start_after)
+ ):
raise ValueError("Invalid object key")
keys.append(key)
return keys
@@ -180,12 +187,14 @@ class ScoutTrialComparisons:
def _history_prefix(self) -> str:
return f"signals/scout-trials/{self.config.team_id}/comparison-history/{self.user.id}/{self.config.id}/"
- def _index(self, plan: TrialComparisonPlan) -> None:
+ def _history_key(self, plan: TrialComparisonPlan) -> str:
# Newest first even when the object-store listing stops at its first page.
reverse_time = 9_999_999_999_999_999_999 - int(plan.created_at.timestamp() * 1_000_000)
- key = f"{self._history_prefix()}{reverse_time:019d}-{plan.comparison_id}.json"
+ return f"{self._history_prefix()}{reverse_time:019d}-{plan.comparison_id}.json"
+
+ def _index(self, plan: TrialComparisonPlan) -> None:
_write_once(
- key,
+ self._history_key(plan),
TrialComparisonHistoryEntry(
team_id=plan.team_id,
config_id=plan.config_id,
@@ -309,6 +318,7 @@ class ScoutTrialComparisons:
)
self._assert_access(plan)
+ history_entry = _read_document(self._history_key(plan), TrialComparisonHistoryEntry)
snapshot = self.evaluation(plan) if not history else None
report = read_trial_evaluation_report(snapshot) if snapshot else None
state: LiteralComparisonStatus = "completed" if report else "judging" if snapshot else "running"
@@ -337,6 +347,7 @@ class ScoutTrialComparisons:
rubric_revision=cast(int, plan.rubric_document["revision"]),
variants=plan.variants,
status=state,
+ archived=history_entry.summary.archived if history_entry is not None else False,
error=error,
evaluation=TrialComparisonEvaluation(
request=snapshot.request,
@@ -351,37 +362,74 @@ class ScoutTrialComparisons:
)
@private_capture_context()
- def history(self, limit: int) -> TrialComparisonHistory:
+ def set_archived(self, plan: TrialComparisonPlan, *, archived: bool) -> TrialComparisonResult:
+ result = self.result(plan)
+ if archived and result.status == "not_started":
+ # Temporal can expire a finished workflow while its trial history remains available.
+ progress = _read_document(
+ comparison_progress_key(plan.team_id, plan.comparison_id), TrialComparisonProgress
+ )
+ if progress is not None and progress.status == "failed":
+ result = result.model_copy(update={"status": "failed", "error": progress.error})
+ if archived and result.status not in {"completed", "failed"}:
+ raise TrialEvaluationError("Only completed or failed trials can be archived.")
+ key = self._history_key(plan)
+ entry = _read_document(key, TrialComparisonHistoryEntry)
+ if entry is None:
+ raise TrialEvaluationError("The saved trial history is unavailable.")
+ entry = entry.model_copy(update={"summary": entry.summary.model_copy(update={"archived": archived})})
+ object_storage.write(key, entry.model_dump_json(), extras={"ContentType": "application/json"})
+ return result.model_copy(update={"archived": archived})
+
+ @private_capture_context()
+ def history(
+ self, limit: int, *, include_archived: bool = False, cursor: str | None = None
+ ) -> TrialComparisonHistory:
ScoutTrialInspection(self.config, self.user)._check_skill_access()
- keys = sorted(list_comparison_history_keys(self._history_prefix(), limit))
results: list[TrialComparisonResult] = []
- for key in keys[: limit + 1]:
- try:
- entry = _read_document(key, TrialComparisonHistoryEntry)
- if entry is None or entry.summary.config_id != entry.config_id:
- raise TrialEvaluationError("The saved comparison history is unavailable.")
- _assert_context_access(entry, config=self.config, user=self.user)
- progress = _read_document(
- comparison_progress_key(entry.team_id, entry.summary.comparison_id), TrialComparisonProgress
- )
- state = progress.status if progress else "not_started"
- error = progress.error if progress else None
- if state != "completed":
- snapshot = self.evaluation(self.read(entry.summary.comparison_id))
- if snapshot is not None and read_trial_evaluation_report(snapshot) is not None:
- state, error = "completed", None
- results.append(
- entry.summary.model_copy(
- update={
- "status": state,
- "error": error,
- "evaluation": None,
- }
+ prefix = self._history_prefix()
+ start_after = f"{prefix}{cursor}" if cursor is not None else None
+ next_cursor: str | None = None
+ while len(results) <= limit:
+ keys = sorted(list_comparison_history_keys(prefix, limit, start_after=start_after))
+ for key in keys:
+ try:
+ entry = _read_document(key, TrialComparisonHistoryEntry)
+ if entry is None or entry.summary.config_id != entry.config_id:
+ raise TrialEvaluationError("The saved comparison history is unavailable.")
+ if entry.summary.archived and not include_archived:
+ continue
+ _assert_context_access(entry, config=self.config, user=self.user)
+ progress = _read_document(
+ comparison_progress_key(entry.team_id, entry.summary.comparison_id), TrialComparisonProgress
)
- )
- except (ValueError, TrialEvaluationError):
- continue
- return TrialComparisonHistory(results=results[:limit], has_more=len(keys) > limit)
+ state = progress.status if progress else "not_started"
+ error = progress.error if progress else None
+ if state != "completed":
+ snapshot = self.evaluation(self.read(entry.summary.comparison_id))
+ if snapshot is not None and read_trial_evaluation_report(snapshot) is not None:
+ state, error = "completed", None
+ results.append(
+ entry.summary.model_copy(
+ update={
+ "status": state,
+ "error": error,
+ "evaluation": None,
+ }
+ )
+ )
+ if len(results) > limit:
+ break
+ next_cursor = key.removeprefix(prefix)
+ except (ValueError, TrialEvaluationError):
+ continue
+ if len(keys) <= limit:
+ break
+ start_after = keys[-1]
+ has_more = len(results) > limit
+ return TrialComparisonHistory(
+ results=results[:limit], has_more=has_more, next_cursor=next_cursor if has_more else None
+ )
type LiteralComparisonStatus = Literal[
diff --git a/products/signals/backend/scout_harness/trial_comparison_serializers.py b/products/signals/backend/scout_harness/trial_comparison_serializers.py
index 5dbdcbd880b8..12b4561226cb 100644
--- a/products/signals/backend/scout_harness/trial_comparison_serializers.py
+++ b/products/signals/backend/scout_harness/trial_comparison_serializers.py
@@ -2,6 +2,7 @@ from rest_framework import serializers
from products.signals.backend.scout_harness.limits import MAX_RUN_NOTE_CHARS, MAX_TRIAL_REPEATS, MAX_TRIAL_VARIANTS
from products.signals.backend.scout_harness.trial_evaluation_serializers import ScoutTrialEvaluationSerializer
+from products.signals.backend.scout_harness.trial_serializers import ScoutTrialHistoryQuerySerializer
class ScoutTrialComparisonVariantRequestSerializer(serializers.Serializer):
@@ -46,6 +47,21 @@ class ScoutTrialComparisonQuerySerializer(serializers.Serializer):
comparison_id = serializers.UUIDField(help_text="Saved comparison identity.")
+class ScoutTrialComparisonArchiveRequestSerializer(ScoutTrialComparisonQuerySerializer):
+ archived = serializers.BooleanField(
+ help_text="Hide a finished trial from history, or restore it without rerunning it."
+ )
+
+
+class ScoutTrialComparisonHistoryQuerySerializer(ScoutTrialHistoryQuerySerializer):
+ include_archived = serializers.BooleanField(default=False, help_text="Include archived trials in the history.")
+ cursor = serializers.RegexField(
+ r"\A[0-9]{19}-[0-9a-f-]{36}\.json\Z",
+ required=False,
+ help_text="Cursor returned by the previous history page. Omit to read the newest trials.",
+ )
+
+
class ScoutTrialComparisonVariantSerializer(serializers.Serializer):
id = serializers.UUIDField(help_text="Variant identity.")
label = serializers.CharField(help_text="Saved variant name.") # type: ignore[assignment]
@@ -67,6 +83,7 @@ class ScoutTrialComparisonSerializer(serializers.Serializer):
choices=["not_started", "starting", "running", "judging", "completed", "failed", "unknown"],
help_text="Comparison lifecycle, including automatic judging.",
)
+ archived = serializers.BooleanField(help_text="Whether this finished trial is hidden from the default history.")
error = serializers.CharField(allow_null=True, help_text="Sanitized comparison error, if any.")
evaluation = ScoutTrialEvaluationSerializer(
allow_null=True, help_text="Saved evaluation and report when available."
@@ -76,3 +93,6 @@ class ScoutTrialComparisonSerializer(serializers.Serializer):
class ScoutTrialComparisonHistorySerializer(serializers.Serializer):
results = ScoutTrialComparisonSerializer(many=True, help_text="This operator's most recent saved comparisons.")
has_more = serializers.BooleanField(help_text="Whether more comparisons exist than the requested limit.")
+ next_cursor = serializers.CharField(
+ allow_null=True, help_text="Cursor for the next page, or null on the last page."
+ )
diff --git a/products/signals/backend/scout_harness/trial_comparison_types.py b/products/signals/backend/scout_harness/trial_comparison_types.py
index d55bddeac433..5e07052ca34f 100644
--- a/products/signals/backend/scout_harness/trial_comparison_types.py
+++ b/products/signals/backend/scout_harness/trial_comparison_types.py
@@ -85,6 +85,7 @@ class TrialComparisonResult(EvaluationDocument):
rubric_revision: int
variants: list[TrialComparisonVariantResult]
status: Literal["not_started", "starting", "running", "judging", "completed", "failed", "unknown"]
+ archived: bool = False
error: str | None
evaluation: TrialComparisonEvaluation | None
@@ -92,6 +93,7 @@ class TrialComparisonResult(EvaluationDocument):
class TrialComparisonHistory(EvaluationDocument):
results: list[TrialComparisonResult]
has_more: bool
+ next_cursor: str | None = None
class TrialComparisonProgress(EvaluationDocument):
diff --git a/products/signals/backend/scout_harness/trial_comparison_views.py b/products/signals/backend/scout_harness/trial_comparison_views.py
index 03d0f6c38b99..9a3d745f208d 100644
--- a/products/signals/backend/scout_harness/trial_comparison_views.py
+++ b/products/signals/backend/scout_harness/trial_comparison_views.py
@@ -14,6 +14,8 @@ from posthog.models import User
from products.signals.backend.models import SignalScoutConfig
from products.signals.backend.scout_harness.trial_comparison_serializers import (
+ ScoutTrialComparisonArchiveRequestSerializer,
+ ScoutTrialComparisonHistoryQuerySerializer,
ScoutTrialComparisonHistorySerializer,
ScoutTrialComparisonQuerySerializer,
ScoutTrialComparisonRequestSerializer,
@@ -21,10 +23,12 @@ from products.signals.backend.scout_harness.trial_comparison_serializers import
)
from products.signals.backend.scout_harness.trial_comparison_types import TrialComparisonRequest
from products.signals.backend.scout_harness.trial_launch import ScoutTrialLaunchError
-from products.signals.backend.scout_harness.trial_serializers import ScoutTrialHistoryQuerySerializer
class ScoutTrialComparisonMixin:
+ def _internal_trial_access(self, request: Request, identifier: str) -> SignalScoutConfig:
+ raise NotImplementedError
+
def _internal_trial_config(self, request: Request, identifier: str) -> SignalScoutConfig:
raise NotImplementedError
@@ -55,6 +59,8 @@ class ScoutTrialComparisonMixin:
try:
plan = service.create(TrialComparisonRequest.model_validate(request.validated_data))
result = service.result(plan, inspect_workflow=False, starting=True)
+ if result.archived:
+ raise ScoutTrialLaunchError("Restore this trial before resuming it.")
if result.status != "completed":
start_trial_comparison(config.team_id, plan.comparison_id)
except ScoutTrialLaunchError as error:
@@ -93,6 +99,8 @@ class ScoutTrialComparisonMixin:
raise exceptions.NotFound() from error
try:
result = service.result(plan, inspect_workflow=False, starting=True)
+ if result.archived:
+ raise ScoutTrialLaunchError("Restore this trial before resuming it.")
if result.status != "completed":
service.assert_can_start(
launch_ids=[launch_id for variant in plan.request.variants for launch_id in variant.launch_ids]
@@ -133,7 +141,38 @@ class ScoutTrialComparisonMixin:
@private_capture_context()
@validated_request(
- query_serializer=ScoutTrialHistoryQuerySerializer,
+ request_serializer=ScoutTrialComparisonArchiveRequestSerializer,
+ responses={200: OpenApiResponse(response=ScoutTrialComparisonSerializer)},
+ operation_id="signals_scout_config_trial_comparison_archive",
+ summary="Archive or restore a saved scout trial",
+ description="Hide a finished trial from history or restore it without deleting results or starting any work.",
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="trial_comparison_archive",
+ required_scopes=["signal_scout:write", "llm_skill:write"],
+ )
+ def trial_comparison_archive(self, request: ValidatedRequest, **kwargs: str) -> Response:
+ from products.signals.backend.scout_harness.trial_comparison import ( # noqa: PLC0415 -- avoid loading the judge and worker graph at route discovery
+ ScoutTrialComparisons,
+ )
+
+ config = self._internal_trial_access(request, kwargs.get("id", ""))
+ service = ScoutTrialComparisons(config, cast(User, request.user))
+ try:
+ plan = service.read(request.validated_data["comparison_id"])
+ except ScoutTrialLaunchError as error:
+ raise exceptions.NotFound() from error
+ try:
+ result = service.set_archived(plan, archived=request.validated_data["archived"])
+ except ScoutTrialLaunchError as error:
+ raise exceptions.ValidationError({"detail": str(error)}) from error
+ return Response(ScoutTrialComparisonSerializer(result.model_dump(mode="json")).data)
+
+ @private_capture_context()
+ @validated_request(
+ query_serializer=ScoutTrialComparisonHistoryQuerySerializer,
responses={200: OpenApiResponse(response=ScoutTrialComparisonHistorySerializer)},
operation_id="signals_scout_config_trial_comparison_history",
summary="List your saved scout comparisons",
@@ -151,5 +190,9 @@ class ScoutTrialComparisonMixin:
)
config = self._internal_trial_config(request, kwargs.get("id", ""))
- history = ScoutTrialComparisons(config, cast(User, request.user)).history(request.validated_query_data["limit"])
+ history = ScoutTrialComparisons(config, cast(User, request.user)).history(
+ request.validated_query_data["limit"],
+ include_archived=request.validated_query_data["include_archived"],
+ cursor=request.validated_query_data.get("cursor"),
+ )
return Response(ScoutTrialComparisonHistorySerializer(history.model_dump(mode="json")).data)
diff --git a/products/signals/backend/scout_harness/trial_views.py b/products/signals/backend/scout_harness/trial_views.py
index c791bca54bce..6574c3f81e16 100644
--- a/products/signals/backend/scout_harness/trial_views.py
+++ b/products/signals/backend/scout_harness/trial_views.py
@@ -5,7 +5,10 @@ from typing import cast
from uuid import UUID
from drf_spectacular.utils import OpenApiResponse
-from pydantic import JsonValue
+from pydantic import (
+ JsonValue,
+ ValidationError as PydanticValidationError,
+)
from rest_framework import exceptions, status
from rest_framework.decorators import action
from rest_framework.request import Request
@@ -53,20 +56,26 @@ from products.signals.backend.scout_harness.trial_serializers import (
ScoutTrialSetupSerializer,
ScoutTrialStartedSerializer,
)
-from products.signals.backend.scout_harness.trial_state import ScoutTrialStore
+from products.signals.backend.scout_harness.trial_state import ScoutTrialStateError, ScoutTrialStore
+
+TRIAL_DATA_UNAVAILABLE_REASON = "Saved run data is unavailable. This run cannot be judged."
class ScoutTrialConfigMixin(ScoutTrialComparisonMixin):
team: Team
- def _internal_trial_config(self, request: Request, identifier: str) -> SignalScoutConfig:
+ def _internal_trial_access(self, request: Request, identifier: str) -> SignalScoutConfig:
if self.team.id != 2 or not request.user.is_staff:
raise exceptions.NotFound()
+ return self._trial_config(request, identifier)
+
+ def _internal_trial_config(self, request: Request, identifier: str) -> SignalScoutConfig:
+ config = self._internal_trial_access(request, identifier)
if request.method not in {"GET", "HEAD", "OPTIONS"} and not scout_trials_enabled(self.team):
raise exceptions.PermissionDenied(
"Scout trials are disabled for this project. Saved results remain available."
)
- return self._trial_config(request, identifier)
+ return config
def _trial_config(self, request: Request, identifier: str) -> SignalScoutConfig:
if (
@@ -209,12 +218,13 @@ class ScoutTrialConfigMixin(ScoutTrialComparisonMixin):
)
reports: list[JsonValue] = []
memory: JsonValue = {}
- invalid_reason = None
+ invalid_reason: JsonValue = None
result_key = None
export_error = None
error = None
trial_status = run.task_run.status if run else "pending"
saved_result = None
+ private: dict[str, JsonValue] | None = None
if run is not None:
try:
saved_result = read_trial_result(run)
@@ -223,6 +233,10 @@ class ScoutTrialConfigMixin(ScoutTrialComparisonMixin):
trial_status = cast(str, saved_result["status"])
except (object_storage.ObjectStorageError, ValueError):
export_error = "The result export failed. Retry this request to save it again."
+ try:
+ private = ScoutTrialStore(run).export()
+ except (ScoutTrialStateError, PydanticValidationError):
+ invalid_reason = TRIAL_DATA_UNAVAILABLE_REASON
if saved_result is None:
workflow = get_trial_workflow_status(team_id=config.team_id, launch_id=launch.id)
error = workflow.error
@@ -230,19 +244,24 @@ class ScoutTrialConfigMixin(ScoutTrialComparisonMixin):
trial_status = "pending" if workflow.status == "completed" and workflow.run_id else workflow.status
else:
trial_status = "in_progress" if workflow.status == "pending" else workflow.status
- if workflow.status in {"failed", "cancelled", "skipped"}:
- ScoutTrialStore(run).invalidate(
- error or "The controlling scout workflow ended before its task.", allow_terminal=True
- )
- if workflow.status == "completed":
- trial_status = "unknown"
- try:
- saved_result = recover_trial_result(run, workflow=workflow)
- if saved_result is not None:
- result_key = trial_result_key(run)
- trial_status = cast(str, saved_result["status"])
- except (object_storage.ObjectStorageError, ValueError):
- export_error = "The result export failed. Retry this request to save it again."
+ if private is not None:
+ try:
+ if workflow.status in {"failed", "cancelled", "skipped"}:
+ ScoutTrialStore(run).invalidate(
+ error or "The controlling scout workflow ended before its task.", allow_terminal=True
+ )
+ if workflow.status == "completed":
+ trial_status = "unknown"
+ saved_result = recover_trial_result(run, workflow=workflow)
+ if saved_result is not None:
+ result_key = trial_result_key(run)
+ trial_status = cast(str, saved_result["status"])
+ except (ScoutTrialStateError, PydanticValidationError):
+ private = None
+ invalid_reason = TRIAL_DATA_UNAVAILABLE_REASON
+ trial_status = "in_progress" if workflow.status == "pending" else workflow.status
+ except (object_storage.ObjectStorageError, ValueError):
+ export_error = "The result export failed. Retry this request to save it again."
usage: dict[str, JsonValue] = {}
summary = run.summary if run else ""
if run is not None:
@@ -251,17 +270,29 @@ class ScoutTrialConfigMixin(ScoutTrialComparisonMixin):
if isinstance(saved_summary, str):
summary = saved_summary
run.task_run.refresh_from_db(fields=["status", "state", "completed_at"])
- if trial_status == "completed":
- if run.task_run.status not in {"completed", "failed", "cancelled"}:
- trial_status = "in_progress"
- elif run.task_run.status != "completed":
- trial_status = run.task_run.status
- error = "The scout task stopped before completion."
- private = ScoutTrialStore(run).export()
- stored_reports = private["reports"]
- reports = list(stored_reports.values()) if isinstance(stored_reports, dict) else []
- memory = private["memory"]
- invalid_reason = private["invalid_reason"]
+ if trial_status == "completed":
+ if run.task_run.status not in {"completed", "failed", "cancelled"}:
+ trial_status = "in_progress"
+ elif run.task_run.status != "completed":
+ trial_status = run.task_run.status
+ error = "The scout task stopped before completion."
+ if private is not None:
+ try:
+ private = ScoutTrialStore(run).export()
+ except (ScoutTrialStateError, PydanticValidationError):
+ private = None
+ invalid_reason = TRIAL_DATA_UNAVAILABLE_REASON
+ if private is not None:
+ stored_reports = private["reports"]
+ reports = list(stored_reports.values()) if isinstance(stored_reports, dict) else []
+ memory = private["memory"]
+ invalid_reason = private["invalid_reason"]
+ elif trial_status in {"unknown", "not_started"} and run.task_run.status in {
+ "completed",
+ "failed",
+ "cancelled",
+ }:
+ trial_status = run.task_run.status
token_usage = (run.task_run.state or {}).get("token_usage")
if isinstance(token_usage, dict):
usage = token_usage
diff --git a/products/signals/backend/test/test_scout_trial_comparison.py b/products/signals/backend/test/test_scout_trial_comparison.py
index b936d7a68a7c..c376805ca748 100644
--- a/products/signals/backend/test/test_scout_trial_comparison.py
+++ b/products/signals/backend/test/test_scout_trial_comparison.py
@@ -240,28 +240,36 @@ class TestScoutTrialComparisonSerializer(SimpleTestCase):
class TestScoutTrialComparisonStorage(SimpleTestCase):
- @parameterized.expand(["empty", "populated", "failure"])
+ @parameterized.expand(["empty", "populated", "next_page", "invalid_page", "failure"])
def test_history_listing_is_bounded_and_does_not_hide_storage_failures(self, scenario: str) -> None:
prefix = "signals/scout-trials/2/comparison-history/17/example/"
+ start_after = prefix + "example.json" if scenario in {"next_page", "invalid_page"} else None
client = MagicMock()
client.list_objects_v2.return_value = (
- {"Contents": [{"Key": prefix + "example.json"}]} if scenario == "populated" else {}
+ {"Contents": [{"Key": prefix + "example.json"}]} if scenario in {"populated", "invalid_page"} else {}
)
+ if scenario == "next_page":
+ client.list_objects_v2.return_value = {"Contents": [{"Key": prefix + "next.json"}]}
if scenario == "failure":
client.list_objects_v2.side_effect = RuntimeError("Synthetic private storage failure")
with patch.object(object_storage, "object_storage_client", return_value=object_storage.ObjectStorage(client)):
- if scenario == "failure":
+ if scenario in {"failure", "invalid_page"}:
with self.assertRaisesMessage(
object_storage.ObjectStorageError, "history could not be loaded"
) as failure:
- list_comparison_history_keys(prefix, 10)
+ list_comparison_history_keys(prefix, 10, start_after=start_after)
assert "private" not in str(failure.exception)
else:
- assert list_comparison_history_keys(prefix, 10) == (
- [prefix + "example.json"] if scenario == "populated" else []
+ assert list_comparison_history_keys(prefix, 10, start_after=start_after) == (
+ [prefix + "example.json"]
+ if scenario == "populated"
+ else [prefix + "next.json"]
+ if scenario == "next_page"
+ else []
)
assert client.list_objects_v2.call_args.kwargs["MaxKeys"] == 11
assert client.list_objects_v2.call_args.kwargs["Prefix"] == prefix
+ assert client.list_objects_v2.call_args.kwargs.get("StartAfter") == start_after
@parameterized.expand(["comparison", "evaluation"])
def test_manual_and_automatic_evaluations_cannot_claim_the_same_identity(self, first_kind: str) -> None:
diff --git a/products/signals/backend/test/test_scout_trials_api.py b/products/signals/backend/test/test_scout_trials_api.py
index f4fe179fdb0d..a4b929665cb5 100644
--- a/products/signals/backend/test/test_scout_trials_api.py
+++ b/products/signals/backend/test/test_scout_trials_api.py
@@ -30,7 +30,8 @@ from products.signals.backend.models import (
from products.signals.backend.scout_harness.model_selection import ScoutModel
from products.signals.backend.scout_harness.run_gates import check_fleet_gates
from products.signals.backend.scout_harness.tools.scratchpad import ScratchpadEntry
-from products.signals.backend.scout_harness.trial_comparison import dispatch_trial_comparison
+from products.signals.backend.scout_harness.trial_comparison import dispatch_trial_comparison, save_comparison_progress
+from products.signals.backend.scout_harness.trial_comparison_types import TrialComparisonProgress
from products.signals.backend.scout_harness.trial_evaluation import TrialEvaluationError
from products.signals.backend.scout_harness.trial_launch import (
ScoutTrialLaunchError,
@@ -782,6 +783,86 @@ class TestScoutTrialLaunch(APIBaseTest):
assert second.json() == result
assert self.documents[result["result_key"]] == saved_content
+ @parameterized.expand(
+ [
+ ("missing_completed_controller", None, "completed", None, "completed", "completed"),
+ ("missing_completed_controller_active_task", None, "in_progress", None, "completed", "in_progress"),
+ ("missing_completed_controller_failed_task", None, "failed", None, "completed", "failed"),
+ ("missing_failed_controller", None, "in_progress", None, "failed", "failed"),
+ ("missing_expired_controller", None, "failed", None, "not_started", "failed"),
+ ("malformed_unknown_controller", {"reports": []}, "completed", None, "unknown", "completed"),
+ ("malformed_active_controller", {"reports": []}, "in_progress", None, "pending", "in_progress"),
+ ("missing_saved_result", None, "completed", "cancelled", "unknown", "cancelled"),
+ ("malformed_saved_result", {"memory": []}, "completed", "completed", "unknown", "completed"),
+ ]
+ )
+ def test_poll_preserves_run_details_when_private_state_is_unavailable(
+ self,
+ _label: str,
+ private_state: dict[str, list[object]] | None,
+ task_status: str,
+ saved_status: str | None,
+ workflow_status: Literal["unknown", "completed", "pending", "failed", "not_started"],
+ expected_status: str,
+ ) -> None:
+ base = self._internal_scout_base()
+ launch = create_trial_launch(config=self.config, user=self.user, launch_id=uuid4())
+ run = _make_run(
+ self.team,
+ scout_config=self.config,
+ skill_name=self.skill.name,
+ task_run_status=task_status,
+ summary="The scout's saved observation.",
+ metadata={"scout_trial": {"version": 1, "launch_id": str(launch.id), "context_id": str(launch.context_id)}},
+ )
+ run.task_run.task.created_by = self.user
+ run.task_run.task.save(update_fields=["created_by"])
+ legacy_report = TrialReport(id=str(uuid4()), document={"title": "Legacy task state must not be restored"})
+ original_task_state = {
+ "runtime_adapter": launch.runtime_adapter,
+ "model": launch.model,
+ "reasoning_effort": launch.reasoning_effort,
+ "service_tier": launch.service_tier,
+ "token_usage": {"input_tokens": 120, "output_tokens": 30},
+ "scout_trial_private": {"reports": {legacy_report.id: legacy_report.model_dump(mode="json")}},
+ }
+ run.task_run.state = original_task_state
+ run.task_run.save(update_fields=["state"])
+ expected_summary = run.summary
+ if saved_status is not None:
+ export_trial_result(run, status=saved_status)
+ run.summary = "A later row summary must not replace the saved result."
+ run.trial_state = private_state
+ run.save(update_fields=["trial_state", "summary"])
+ saved_documents = dict(self.documents)
+
+ with patch(
+ "products.signals.backend.scout_harness.trial_views.get_trial_workflow_status",
+ return_value=TrialWorkflowStatus(status=workflow_status),
+ ):
+ response = self.client.get(f"{base}trial_result/", {"launch_id": str(launch.id)})
+
+ assert response.status_code == 200, response.data
+ result = response.json()
+ assert result["status"] == expected_status
+ assert result["task_status"] == task_status
+ assert result["summary"] == expected_summary
+ assert result["run_id"] == str(run.id)
+ assert result["task_id"] == str(run.task_run.task_id)
+ assert result["task_run_id"] == str(run.task_run_id)
+ assert result["input_tokens"] == 120
+ assert result["output_tokens"] == 30
+ assert result["invalid_reason"] == "Saved run data is unavailable. This run cannot be judged."
+ assert result["reports"] == []
+ assert result["memory"] == {}
+ assert result["export_error"] is None
+ assert (result["result_key"] is not None) == (saved_status is not None)
+ run.refresh_from_db()
+ run.task_run.refresh_from_db()
+ assert run.trial_state == private_state
+ assert run.task_run.state == original_task_state
+ assert self.documents == saved_documents
+
def test_evaluation_endpoints_save_exact_request_and_reject_another_operator(self) -> None:
base = self._internal_scout_base()
launch = create_trial_launch(config=self.config, user=self.user, launch_id=uuid4(), variant="Baseline")
@@ -1155,6 +1236,172 @@ class TestScoutTrialLaunch(APIBaseTest):
dispatch.assert_not_called()
assert not self.documents
+ @parameterized.expand([True, False])
+ def test_finished_trials_can_be_archived_and_restored_without_changing_their_runs(
+ self, trials_enabled: bool
+ ) -> None:
+ base = self._internal_scout_base()
+ self.config.rubrics = {
+ "revision": 1,
+ "criteria": [criterion.model_dump(mode="json") for criterion in default_criteria()],
+ "reference_context": _reference_context(
+ skill_id=str(self.skill.id), skill_name=self.skill.name, instructions=self.skill.body
+ ).model_dump(mode="json"),
+ "reference_generation_id": str(uuid4()),
+ }
+ self.config.save(update_fields=["rubrics"])
+ storage_client = MagicMock()
+ storage_client.list_objects_v2.side_effect = lambda **kwargs: {
+ "Contents": [
+ {"Key": key}
+ for key in sorted(self.documents)
+ if key.startswith(kwargs["Prefix"]) and key > kwargs.get("StartAfter", "")
+ ][: kwargs["MaxKeys"]]
+ }
+ module = "products.signals.backend.temporal.agentic.scout_trial_comparison"
+ with (
+ patch(f"{module}.start_trial_comparison", return_value="synthetic-workflow") as dispatch,
+ patch(
+ f"{module}.get_trial_comparison_status", return_value=TrialWorkflowStatus(status="pending")
+ ) as workflow,
+ patch.object(
+ object_storage, "object_storage_client", return_value=object_storage.ObjectStorage(storage_client)
+ ),
+ ):
+ comparison_ids: list[str] = []
+ payload: dict[str, object] = {}
+ created_at = timezone.now()
+ for index in range(3):
+ variant_id = str(uuid4())
+ comparison_id = str(uuid4())
+ payload = {
+ "comparison_id": comparison_id,
+ "baseline_variant_id": variant_id,
+ "variants": [
+ {
+ "id": variant_id,
+ "label": "Baseline",
+ "launch_ids": [str(uuid4())],
+ "model": "gpt-5.5",
+ "reasoning_effort": "medium",
+ }
+ ],
+ }
+ with patch(
+ "products.signals.backend.scout_harness.trial_comparison.timezone.now",
+ return_value=created_at + timedelta(seconds=index),
+ ):
+ created = self.client.post(f"{base}trial_comparison/", payload, format="json")
+ assert created.status_code == 202, created.data
+ comparison_ids.append(comparison_id)
+ history_url = f"{base}trial_comparison_history/"
+ first_page = self.client.get(history_url, {"limit": 1})
+ assert first_page.status_code == 200, first_page.data
+ assert [row["comparison_id"] for row in first_page.json()["results"]] == comparison_ids[-1:]
+ assert first_page.json()["has_more"] is True
+ cursor = first_page.json()["next_cursor"]
+ assert cursor is not None
+ for index, comparison_id in enumerate(reversed(comparison_ids[:-1])):
+ page = self.client.get(history_url, {"limit": "1", "cursor": cursor})
+ assert page.status_code == 200, page.data
+ assert [row["comparison_id"] for row in page.json()["results"]] == [comparison_id]
+ assert page.json()["has_more"] is (index == 0)
+ cursor = page.json()["next_cursor"]
+ assert cursor is None
+ assert self.client.get(history_url, {"cursor": "../another-history/"}).status_code == 400
+ self.trials_flag.return_value = trials_enabled
+ archive_url = f"{base}trial_comparison_archive/"
+ archive_request = {"comparison_id": comparison_ids[-1], "archived": True}
+ before_archive = dict(self.documents)
+ active = self.client.post(archive_url, archive_request, format="json")
+ assert active.status_code == 400, active.data
+ workflow.return_value = TrialWorkflowStatus(status="unknown")
+ unknown = self.client.post(archive_url, archive_request, format="json")
+ assert unknown.status_code == 400, unknown.data
+ assert self.documents == before_archive
+
+ workflow.return_value = TrialWorkflowStatus(status="failed", error="The trial could not finish.")
+ for comparison_id in comparison_ids:
+ save_comparison_progress(self.team.id, UUID(comparison_id), TrialComparisonProgress(status="failed"))
+ frozen_documents = {
+ key: value for key, value in self.documents.items() if "/comparison-history/" not in key
+ }
+ workflow.return_value = TrialWorkflowStatus(status="unknown")
+ assert self.client.post(archive_url, archive_request, format="json").status_code == 400
+ for index, comparison_id in enumerate(comparison_ids[1:]):
+ workflow.return_value = TrialWorkflowStatus(status="not_started" if index == 0 else "failed")
+ response = self.client.post(
+ archive_url, {"comparison_id": comparison_id, "archived": True}, format="json"
+ )
+ assert response.status_code == 200, response.data
+ assert response.json()["archived"] is True
+ assert response.json()["status"] == "failed"
+ save_comparison_progress(self.team.id, UUID(comparison_ids[-1]), TrialComparisonProgress(status="failed"))
+
+ history = self.client.get(history_url, {"limit": 1})
+ assert history.status_code == 200, history.data
+ assert [row["comparison_id"] for row in history.json()["results"]] == comparison_ids[:1]
+ assert history.json()["has_more"] is False
+ assert history.json()["next_cursor"] is None
+ assert any("StartAfter" in call.kwargs for call in storage_client.list_objects_v2.call_args_list)
+ included = self.client.get(history_url, {"limit": "1", "include_archived": "true"})
+ assert included.status_code == 200, included.data
+ assert included.json()["results"][0]["comparison_id"] == comparison_ids[-1]
+ assert included.json()["results"][0]["archived"] is True
+ assert included.json()["has_more"] is True
+ older = self.client.get(
+ history_url,
+ {"limit": "1", "include_archived": "true", "cursor": included.json()["next_cursor"]},
+ )
+ assert older.status_code == 200, older.data
+ assert older.json()["results"][0]["comparison_id"] == comparison_ids[1]
+ assert older.json()["results"][0]["archived"] is True
+ unarchived = self.client.get(history_url, {"cursor": included.json()["next_cursor"]})
+ assert unarchived.status_code == 200, unarchived.data
+ assert [row["comparison_id"] for row in unarchived.json()["results"]] == comparison_ids[:1]
+ assert unarchived.json()["next_cursor"] is None
+ saved = self.client.get(f"{base}trial_comparison_result/", {"comparison_id": comparison_ids[-1]})
+ assert saved.status_code == 200, saved.data
+ assert saved.json()["archived"] is True
+ assert self.client.post(
+ f"{base}trial_comparison_resume/", {"comparison_id": comparison_ids[-1]}, format="json"
+ ).status_code == (400 if trials_enabled else 403)
+ assert self.client.post(f"{base}trial_comparison/", payload, format="json").status_code == (
+ 400 if trials_enabled else 403
+ )
+ restored = self.client.post(archive_url, {**archive_request, "archived": False}, format="json")
+ assert restored.status_code == 200, restored.data
+ assert restored.json()["archived"] is False
+ history = self.client.get(history_url)
+ assert [row["comparison_id"] for row in history.json()["results"]] == [
+ comparison_ids[-1],
+ comparison_ids[0],
+ ]
+ assert dispatch.call_count == 3
+ assert {
+ key: value for key, value in self.documents.items() if "/comparison-history/" not in key
+ } == frozen_documents
+
+ self.user.is_staff = False
+ self.user.save(update_fields=["is_staff"])
+ assert self.client.post(archive_url, archive_request, format="json").status_code == 404
+ self.user.is_staff = True
+ self.user.save(update_fields=["is_staff"])
+ other_team = Team.objects.create(organization=self.organization, name="Other example")
+ assert (
+ self.client.post(
+ archive_url.replace("/projects/2/", f"/projects/{other_team.id}/"), archive_request, format="json"
+ ).status_code
+ == 404
+ )
+ other_user = self._create_user("[email protected]")
+ other_user.is_staff = True
+ other_user.save(update_fields=["is_staff"])
+ self.client.force_login(other_user)
+ before_denied = dict(self.documents)
+ assert self.client.post(archive_url, archive_request, format="json").status_code == 404
+ assert self.documents == before_denied
+
class TestScoutTrialsGate(SimpleTestCase):
@parameterized.expand([(2, True, True), (2, False, False), (2, None, False), (2, "true", False), (3, True, False)])
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 5a72c28a9842..4d5ca9de9fcb 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -4467,6 +4467,8 @@ export interface ScoutTrialComparisonApi {
* * `failed` - failed
* * `unknown` - unknown */
status: ScoutTrialComparisonStatusEnumApi
+ /** Whether this finished trial is hidden from the default history. */
+ archived: boolean
/**
* Sanitized comparison error, if any.
* @nullable
@@ -4476,11 +4478,23 @@ export interface ScoutTrialComparisonApi {
evaluation: ScoutTrialEvaluationApi | null
}
+export interface ScoutTrialComparisonArchiveRequestApi {
+ /** Saved comparison identity. */
+ comparison_id: string
+ /** Hide a finished trial from history, or restore it without rerunning it. */
+ archived: boolean
+}
+
export interface ScoutTrialComparisonHistoryApi {
/** This operator's most recent saved comparisons. */
results: ScoutTrialComparisonApi[]
/** Whether more comparisons exist than the requested limit. */
has_more: boolean
+ /**
+ * Cursor for the next page, or null on the last page.
+ * @nullable
+ */
+ next_cursor: string | null
}
export interface ScoutTrialComparisonQueryApi {
@@ -7710,6 +7724,16 @@ export type SignalsScoutConfigListParams = {
}
export type SignalsScoutConfigTrialComparisonHistoryParams = {
+ /**
+ * Cursor returned by the previous history page. Omit to read the newest trials.
+ * @minLength 1
+ * @pattern ^[0-9]{19}-[0-9a-f-]{36}\.json$
+ */
+ cursor?: string
+ /**
+ * Include archived trials in the history.
+ */
+ include_archived?: boolean
/**
* Maximum number of recent private runs to return.
* @minimum 1
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 03d05169ae58..07f74e34ea51 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -70,6 +70,7 @@ import type {
ScoutSuggestionSetApi,
ScoutToolCatalogueApi,
ScoutTrialComparisonApi,
+ ScoutTrialComparisonArchiveRequestApi,
ScoutTrialComparisonHistoryApi,
ScoutTrialComparisonQueryApi,
ScoutTrialComparisonRequestApi,
@@ -1545,6 +1546,28 @@ export const signalsScoutConfigTrialComparisonCreate = async (
})
}
+export const getSignalsScoutConfigTrialComparisonArchiveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/scout/configs/${id}/trial_comparison_archive/`
+}
+
+/**
+ * Hide a finished trial from history or restore it without deleting results or starting any work.
+ * @summary Archive or restore a saved scout trial
+ */
+export const signalsScoutConfigTrialComparisonArchive = async (
+ projectId: string,
+ id: string,
+ scoutTrialComparisonArchiveRequestApi: ScoutTrialComparisonArchiveRequestApi,
+ options?: RequestInit
+): Promise<ScoutTrialComparisonApi> => {
+ return apiMutator<ScoutTrialComparisonApi>(getSignalsScoutConfigTrialComparisonArchiveUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(scoutTrialComparisonArchiveRequestApi),
+ })
+}
+
export const getSignalsScoutConfigTrialComparisonHistoryUrl = (
projectId: string,
id: string,
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index ac213f946729..24fe860509d1 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -1479,6 +1479,15 @@ export const SignalsScoutConfigTrialComparisonCreateBody = /* @__PURE__ */ zod.o
.describe('Source version shown in the editor. Refuse a new trial if the instructions changed since setup.'),
})
+/**
+ * Hide a finished trial from history or restore it without deleting results or starting any work.
+ * @summary Archive or restore a saved scout trial
+ */
+export const SignalsScoutConfigTrialComparisonArchiveBody = /* @__PURE__ */ zod.object({
+ comparison_id: zod.uuid().describe('Saved comparison identity.'),
+ archived: zod.boolean().describe('Hide a finished trial from history, or restore it without rerunning it.'),
+})
+
/**
* Recover the same comparison without repeating saved scout runs or judge attempts.
* @summary Resume a saved scout comparison
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialDetail.tsx b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialDetail.tsx
index 668508b6aa95..e5a068a30b43 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialDetail.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialDetail.tsx
@@ -1,4 +1,4 @@
-import { IconArrowLeft, IconDownload, IconRefresh } from '@posthog/icons'
+import { IconArrowLeft, IconDownload, IconRefresh, IconUndo } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonCollapse, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
@@ -43,6 +43,22 @@ export function ScoutTrialDetail(props: ScoutTrialsViewProps): JSX.Element {
</LemonButton>
</div>
</div>
+ {trial?.archived && (
+ <LemonBanner
+ type="info"
+ action={{
+ children: 'Restore trial',
+ icon: <IconUndo />,
+ loading: props.archiving.includes(trial.comparison_id),
+ onClick: () => props.archiveComparison(trial.comparison_id, false),
+ }}
+ >
+ This trial is archived. Its report and run details are still available.
+ </LemonBanner>
+ )}
+ {trial && props.archiveErrors[trial.comparison_id] && (
+ <LemonBanner type="error">{props.archiveErrors[trial.comparison_id]}</LemonBanner>
+ )}
{props.managedComparison ? (
<>
{submitting ? (
@@ -99,6 +115,10 @@ export function ScoutTrialDetail(props: ScoutTrialsViewProps): JSX.Element {
loading={props.comparisonState.resuming}
disabledReason={
props.trialsDisabledReason ||
+ (trial?.archived ? 'Restore this trial before retrying it.' : undefined) ||
+ (trial && props.archiving.includes(trial.comparison_id)
+ ? 'Wait for the archive request to finish.'
+ : undefined) ||
(props.comparisonState.loading ? 'Wait for the current status.' : undefined)
}
data-attr="scout-comparison-resume"
@@ -126,58 +146,6 @@ export function ScoutTrialDetail(props: ScoutTrialsViewProps): JSX.Element {
</LemonButton>
{selectedConfig && <ScoutRubricsButton config={selectedConfig} />}
</div>
- {!props.evaluationState.value?.report && props.comparisonRows.length > 0 && (
- <div className="flex flex-col gap-2">
- <p className="m-0 text-sm font-semibold">Runs in this trial</p>
- {props.comparisonRows.map((row) => (
- <LemonCard
- key={row.launchId}
- hoverEffect={false}
- className="flex flex-wrap items-center justify-between gap-2 p-3"
- >
- <div className="min-w-0 flex-1">
- <strong className="break-words">{row.variant}</strong>
- <p className="m-0 text-xs text-muted break-words">{`${row.model || 'Saved model'} · ${row.effort || 'default'} effort`}</p>
- {row.error && (
- <p className="m-0 text-xs text-danger break-words">{row.error}</p>
- )}
- </div>
- <LemonTag
- type={
- row.status === 'completed'
- ? 'success'
- : row.status === 'failed'
- ? 'danger'
- : 'muted'
- }
- >
- {row.status === 'not_started' ? 'Queued' : row.status.replaceAll('_', ' ')}
- </LemonTag>
- <LemonButton
- size="xsmall"
- type="tertiary"
- onClick={() => props.selectResult(row.launchId)}
- disabledReason={!row.result ? 'Run details have not loaded yet.' : undefined}
- >
- Run details
- </LemonButton>
- {row.result?.task_id &&
- row.result.task_run_id &&
- (trialIsActive(row.status) || trialTaskIsActive(row.result.task_status)) && (
- <LemonButton
- size="xsmall"
- type="tertiary"
- status="danger"
- loading={props.canceling.includes(row.launchId)}
- onClick={() => props.cancelRun(row.launchId)}
- >
- Stop run
- </LemonButton>
- )}
- </LemonCard>
- ))}
- </div>
- )}
</>
) : (
<>
@@ -204,11 +172,14 @@ export function ScoutTrialDetail(props: ScoutTrialsViewProps): JSX.Element {
type="secondary"
size="small"
icon={<IconRefresh />}
- loading={props.evaluationState.loading}
+ loading={props.evaluationState.loading || props.refreshing}
disabledReason={
props.evaluationState.scoring ? 'Wait for judging to be submitted.' : undefined
}
- onClick={() => props.loadEvaluation(props.selectedComparison!.id)}
+ onClick={() => {
+ props.loadEvaluation(props.selectedComparison!.id)
+ props.refreshResults(true)
+ }}
>
Refresh status
</LemonButton>
@@ -232,22 +203,102 @@ export function ScoutTrialDetail(props: ScoutTrialsViewProps): JSX.Element {
)}
</>
)}
+ {!props.evaluationState.value?.report && props.comparisonRows.length > 0 && (
+ <div className="flex flex-col gap-2">
+ <p className="m-0 text-sm font-semibold">Runs in this trial</p>
+ {props.comparisonRows.map((row) => (
+ <LemonCard
+ key={row.launchId}
+ hoverEffect={false}
+ className="flex flex-wrap items-center justify-between gap-2 p-3"
+ >
+ <div className="min-w-0 flex-1">
+ <strong className="break-words">{row.variant}</strong>
+ <p className="m-0 text-xs text-muted break-words">{`${row.model || 'Saved model'} · ${row.effort || 'default'} effort`}</p>
+ {props.resultErrors[row.launchId] && (
+ <p className="m-0 text-xs text-danger break-words">
+ {props.resultErrors[row.launchId]}
+ </p>
+ )}
+ {props.cancelErrors[row.launchId] &&
+ (trialIsActive(row.status) || trialTaskIsActive(row.result?.task_status)) && (
+ <p className="m-0 text-xs text-danger break-words">
+ {props.cancelErrors[row.launchId]}
+ </p>
+ )}
+ </div>
+ <LemonTag
+ type={
+ row.status === 'completed'
+ ? 'success'
+ : row.status === 'failed'
+ ? 'danger'
+ : 'muted'
+ }
+ >
+ {row.status === 'not_started' ? 'Queued' : row.status.replaceAll('_', ' ')}
+ </LemonTag>
+ <LemonButton size="xsmall" type="tertiary" onClick={() => props.selectResult(row.launchId)}>
+ Run details
+ </LemonButton>
+ {props.resultErrors[row.launchId] && (
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ onClick={() => props.retryResult(row.launchId)}
+ loading={props.refreshingLaunchIds.includes(row.launchId)}
+ data-attr="scout-trial-run-retry"
+ >
+ Retry
+ </LemonButton>
+ )}
+ {row.result?.task_id &&
+ row.result.task_run_id &&
+ (trialIsActive(row.status) || trialTaskIsActive(row.result.task_status)) && (
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ status="danger"
+ loading={props.canceling.includes(row.launchId)}
+ onClick={() => props.cancelRun(row.launchId)}
+ >
+ Stop run
+ </LemonButton>
+ )}
+ </LemonCard>
+ ))}
+ </div>
+ )}
{props.evaluationState.value?.report && (
- <>
- <ScoutTrialComparisonReport
- report={props.evaluationState.value.report}
- rows={props.comparisonRows}
- onSelectRun={props.selectResult}
- />
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconDownload />}
- onClick={props.downloadEvaluation}
- >
- Download report
- </LemonButton>
- </>
+ <ScoutTrialComparisonReport
+ report={props.evaluationState.value.report}
+ rows={props.comparisonRows}
+ onSelectRun={props.selectResult}
+ />
+ )}
+ {(props.evaluationState.value?.report || props.comparisonRows.some((row) => row.result)) && (
+ <div className="flex flex-wrap gap-2">
+ {props.evaluationState.value?.report && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconDownload />}
+ onClick={props.downloadEvaluation}
+ >
+ Download report
+ </LemonButton>
+ )}
+ {props.comparisonRows.some((row) => row.result) && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconDownload />}
+ onClick={props.downloadResults}
+ >
+ Download results
+ </LemonButton>
+ )}
+ </div>
)}
{(props.evaluationState.value?.status === 'completed' ||
props.evaluationState.value?.status === 'failed') && (
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialHistory.tsx b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialHistory.tsx
index 0bd86f004c49..b747022bf380 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialHistory.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialHistory.tsx
@@ -1,5 +1,5 @@
-import { IconPlus, IconRefresh } from '@posthog/icons'
-import { LemonButton, LemonTable, LemonTag } from '@posthog/lemon-ui'
+import { IconArchive, IconPlus, IconRefresh, IconUndo } from '@posthog/icons'
+import { LemonButton, LemonSwitch, LemonTable, LemonTag } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
@@ -18,7 +18,7 @@ const STATUS_LABELS: Record<string, string> = {
export function ScoutTrialHistory(props: ScoutTrialsViewProps): JSX.Element {
return (
- <div className="flex min-w-0 flex-col gap-5">
+ <div className="@container/trial-history flex min-w-0 flex-col gap-5">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0 flex-1 basis-72">
<h2 className="m-0 text-lg font-semibold">Trials</h2>
@@ -52,14 +52,41 @@ export function ScoutTrialHistory(props: ScoutTrialsViewProps): JSX.Element {
</LemonButton>
</div>
</div>
+ <LemonSwitch
+ checked={props.showArchived}
+ onChange={props.setShowArchived}
+ label="Show archived"
+ className="self-start"
+ data-attr="scout-trials-show-archived"
+ />
<LemonTable<ScoutTrialComparison>
dataSource={props.comparisonsForConfig}
rowKey="id"
loading={props.comparisonHistoryLoading && !props.comparisonsForConfig.length}
- emptyState="No trials yet. Create a trial to compare prompts, models, or effort."
+ nouns={['trial', 'trials']}
+ pagination={{
+ controlled: true,
+ useUrl: false,
+ hideOnSinglePage: !props.comparisonHistoryCursors.length && !props.comparisonHistory?.next_cursor,
+ onForward:
+ props.comparisonHistory?.next_cursor && !props.comparisonHistoryLoading
+ ? props.nextComparisonHistoryPage
+ : undefined,
+ onBackward:
+ props.comparisonHistoryCursors.length && !props.comparisonHistoryLoading
+ ? props.previousComparisonHistoryPage
+ : undefined,
+ }}
+ emptyState={
+ props.showArchived
+ ? 'No trials yet. Create a trial to compare prompts, models, or effort.'
+ : 'No trials to show. Create a trial or turn on Show archived.'
+ }
+ tableLayout="fixed"
columns={[
{
title: 'Trial',
+ width: '28%',
render: (_, trial) => {
const saved = props.comparisonStates[trial.id]?.value
return (
@@ -77,12 +104,18 @@ export function ScoutTrialHistory(props: ScoutTrialsViewProps): JSX.Element {
{dayjs(saved.created_at).format('MMM D, YYYY, HH:mm')}
</span>
)}
+ {props.archiveErrors[trial.id] && (
+ <span className="text-xs text-danger break-words">
+ {props.archiveErrors[trial.id]}
+ </span>
+ )}
</div>
)
},
},
{
title: 'Versions',
+ width: '32%',
render: (_, trial) => (
<div className="flex flex-col gap-1">
<span>{`${trial.groups.length} versions · ${trial.groups.reduce((count, group) => count + group.launchIds.length, 0)} runs`}</span>
@@ -96,33 +129,67 @@ export function ScoutTrialHistory(props: ScoutTrialsViewProps): JSX.Element {
},
{
title: 'Status',
+ width: '22%',
render: (_, trial) => {
const status = props.comparisonStates[trial.id]?.value?.status
return (
- <LemonTag
- type={
- status === 'completed'
- ? 'success'
- : status === 'failed'
- ? 'danger'
- : status === 'judging' || status === 'running'
- ? 'primary'
- : 'muted'
+ <div className="flex flex-wrap gap-1">
+ <LemonTag
+ type={
+ status === 'completed'
+ ? 'success'
+ : status === 'failed'
+ ? 'danger'
+ : status === 'judging' || status === 'running'
+ ? 'primary'
+ : 'muted'
+ }
+ wrap
+ >
+ {STATUS_LABELS[status ?? 'unknown'] ?? 'Status unavailable'}
+ </LemonTag>
+ {props.comparisonStates[trial.id]?.value?.archived && (
+ <LemonTag type="muted">Archived</LemonTag>
+ )}
+ </div>
+ )
+ },
+ },
+ {
+ title: '',
+ width: '18%',
+ render: (_, trial) => {
+ const state = props.comparisonStates[trial.id]
+ const saved = state?.value
+ return (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={saved?.archived ? <IconUndo /> : <IconArchive />}
+ tooltip={saved?.archived ? 'Restore trial' : 'Archive trial'}
+ loading={props.archiving.includes(trial.id)}
+ disabledReason={
+ state?.loading || state?.resuming
+ ? 'Wait for the current status.'
+ : !saved?.archived &&
+ saved?.status !== 'completed' &&
+ saved?.status !== 'failed'
+ ? 'Only completed or failed trials can be archived.'
+ : undefined
}
- wrap
+ onClick={() => props.archiveComparison(trial.id, !saved?.archived)}
+ aria-label={`${saved?.archived ? 'Restore' : 'Archive'} trial ${trial.id.slice(0, 8)}`}
+ data-attr="scout-trial-archive"
>
- {STATUS_LABELS[status ?? 'unknown'] ?? 'Status unavailable'}
- </LemonTag>
+ <span className="hidden @3xl/trial-history:inline">
+ {saved?.archived ? 'Restore' : 'Archive'}
+ </span>
+ </LemonButton>
)
},
},
]}
/>
- {props.comparisonHistory?.has_more && (
- <p className="m-0 text-xs text-secondary">
- Showing your 30 most recent trials, plus trials saved in this browser.
- </p>
- )}
<p className="m-0 text-xs text-secondary">
Trials and their results are private to you. Your live scout stays unchanged.
</p>
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialRunDrawer.tsx b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialRunDrawer.tsx
index 0ca00cfd7870..abe3149c88a1 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialRunDrawer.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialRunDrawer.tsx
@@ -15,12 +15,16 @@ export function ScoutTrialRunDrawer({
report,
launchId,
error,
+ loading = false,
+ onRetry,
onClose,
}: {
result: ScoutTrialResultApi | null
report?: TrialComparisonReportApi | null
launchId?: string | null
error?: string | null
+ loading?: boolean
+ onRetry?: () => void
onClose: () => void
}): JSX.Element | null {
const selectedLaunchId = launchId ?? result?.launch_id
@@ -59,7 +63,14 @@ export function ScoutTrialRunDrawer({
className="ph-no-capture ph-replay-block"
>
<div className="@container flex flex-col gap-4 min-w-0 break-words">
- {error && <LemonBanner type="warning">{error}</LemonBanner>}
+ {error && (
+ <LemonBanner
+ type="warning"
+ action={onRetry ? { children: 'Retry', onClick: onRetry, loading } : undefined}
+ >
+ {error}
+ </LemonBanner>
+ )}
{!result && !judgment && !error && <LemonSkeleton className="h-32" />}
{result?.status === 'failed' && !result.error && !result.invalid_reason && (
<LemonBanner type="error">This run failed. It was not judged.</LemonBanner>
@@ -68,7 +79,7 @@ export function ScoutTrialRunDrawer({
<LemonBanner type="warning">This run was stopped. It was not judged.</LemonBanner>
)}
{(result?.error || result?.invalid_reason) && (
- <LemonBanner type="error">{result.error || result.invalid_reason}</LemonBanner>
+ <LemonBanner type="error">{result.invalid_reason || result.error}</LemonBanner>
)}
{result?.export_error && (
<LemonBanner type="warning">
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialRunHistory.tsx b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialRunHistory.tsx
deleted file mode 100644
index 42b6f6eacb6d..000000000000
--- a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialRunHistory.tsx
+++ /dev/null
@@ -1,158 +0,0 @@
-import { IconDownload, IconRefresh } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonCollapse, LemonTable, LemonTag } from '@posthog/lemon-ui'
-
-import { dayjs } from 'lib/dayjs'
-
-import type { ScoutTrialsViewProps } from './ScoutTrialsView'
-import { ScoutTrialRow, trialIsActive, trialTaskIsActive } from './scoutTrialUtils'
-
-export function ScoutTrialRunHistory(props: ScoutTrialsViewProps): JSX.Element {
- const { rows, selectedConfigId } = props
- return (
- <LemonCollapse
- panels={[
- {
- key: 'run-history',
- header: 'Individual run history',
- content: (
- <div className="flex flex-col gap-3 border-t pt-4">
- <div className="flex flex-wrap items-center justify-between gap-2">
- <h3 className="m-0 text-base">Recent executions</h3>
- <div className="flex flex-wrap gap-2">
- <LemonButton
- size="small"
- type="secondary"
- icon={<IconRefresh />}
- loading={props.refreshing || props.historyLoading}
- onClick={() => {
- props.refreshResults(true)
- props.loadHistory(selectedConfigId!)
- props.loadComparisonHistory(selectedConfigId!)
- }}
- >
- Refresh
- </LemonButton>
- <LemonButton
- size="small"
- type="secondary"
- icon={<IconDownload />}
- onClick={props.downloadResults}
- disabledReason={
- !rows.some((row) => row.result) ? 'No results have loaded yet.' : undefined
- }
- >
- Download results
- </LemonButton>
- </div>
- </div>
- {props.pollError && <LemonBanner type="warning">{props.pollError}</LemonBanner>}
- <LemonTable<ScoutTrialRow>
- dataSource={rows}
- rowKey="launchId"
- tableLayout="fixed"
- size="small"
- loading={props.historyLoading && !rows.length}
- emptyState="No trial runs yet. Start a trial to compare versions."
- columns={[
- {
- title: 'Run',
- width: '50%',
- render: (_, row) => (
- <div className="min-w-0">
- <strong className="break-words">{row.variant}</strong>
- <div className="text-xs text-muted break-all">
- {row.model ? `${row.model} · ${row.effort}` : row.launchId}
- </div>
- {row.startedAt && (
- <div className="text-xs text-muted">
- {dayjs(row.startedAt).format('MMM D, HH:mm')}
- </div>
- )}
- {row.error && (
- <div className="text-xs text-danger break-words">{row.error}</div>
- )}
- </div>
- ),
- },
- {
- title: 'Status',
- width: '27%',
- render: (_, row) => (
- <div className="flex flex-col items-start gap-1">
- <LemonTag
- type={
- row.status === 'completed'
- ? 'success'
- : row.status === 'failed'
- ? 'danger'
- : trialIsActive(row.status)
- ? 'primary'
- : 'muted'
- }
- wrap
- >
- {row.status.replaceAll('_', ' ')}
- </LemonTag>
- {row.result && (
- <>
- <span className="text-xs">{`${row.result.reports.length} ${row.result.reports.length === 1 ? 'report' : 'reports'}`}</span>
- <span className="text-xs text-muted">
- {row.result.cost_usd === null
- ? 'Cost unknown'
- : `$${row.result.cost_usd.toFixed(2)}`}
- </span>
- </>
- )}
- </div>
- ),
- },
- {
- title: '',
- width: '23%',
- render: (_, row) => (
- <div className="flex flex-col items-start gap-1">
- <LemonButton
- size="xsmall"
- type="tertiary"
- onClick={() => props.selectResult(row.launchId)}
- disabledReason={
- !row.result ? 'Results have not loaded yet.' : undefined
- }
- >
- Results
- </LemonButton>
- {row.result?.task_id &&
- row.result.task_run_id &&
- (trialIsActive(row.status) ||
- trialTaskIsActive(row.result.task_status)) && (
- <LemonButton
- size="xsmall"
- type="tertiary"
- status="danger"
- loading={props.canceling.includes(row.launchId)}
- onClick={() => props.cancelRun(row.launchId)}
- >
- Stop run
- </LemonButton>
- )}
- </div>
- ),
- },
- ]}
- />
- {props.history?.has_more && (
- <p className="text-xs text-muted m-0">
- Showing your 30 most recent runs, plus runs started in this browser.
- </p>
- )}
- <p className="text-xs text-muted m-0">
- Each row is one scout execution. This history includes older runs and runs from other
- trials. Select a trial to see its grouped judging report.
- </p>
- </div>
- ),
- },
- ]}
- />
- )
-}
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialsPanel.test.tsx b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialsPanel.test.tsx
index e9ecbce73aac..de20991a3cd0 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialsPanel.test.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialsPanel.test.tsx
@@ -1,8 +1,11 @@
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { ApiError } from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { promiseResolveReject } from 'lib/utils/async'
+import { downloadFile } from 'lib/utils/dom'
import { initKeaTests } from '~/test/init'
@@ -10,12 +13,17 @@ import {
signalsScoutConfigList,
signalsScoutConfigTrialComparisonHistory,
signalsScoutConfigTrialComparisonRetrieve,
+ signalsScoutConfigTrialEvaluationRetrieve,
signalsScoutConfigTrialHistory,
signalsScoutConfigTrialResult,
signalsScoutConfigTrialSetup,
signalsScoutRubricsRetrieve,
} from 'products/signals/frontend/generated/api'
-import type { ScoutRubricDocumentApi } from 'products/signals/frontend/generated/api.schemas'
+import type {
+ ScoutRubricDocumentApi,
+ ScoutTrialComparisonHistoryApi,
+} from 'products/signals/frontend/generated/api.schemas'
+import { tasksRunsCancelCreate } from 'products/tasks/frontend/generated/api'
import { scoutRubricReferenceFixture } from '../scoutRubricFixtures'
import {
@@ -32,12 +40,23 @@ jest.mock('products/signals/frontend/generated/api', () => ({
signalsScoutConfigList: jest.fn(),
signalsScoutConfigTrialComparisonHistory: jest.fn(),
signalsScoutConfigTrialComparisonRetrieve: jest.fn(),
+ signalsScoutConfigTrialEvaluationRetrieve: jest.fn(),
signalsScoutConfigTrialHistory: jest.fn(),
signalsScoutConfigTrialResult: jest.fn(),
signalsScoutConfigTrialSetup: jest.fn(),
signalsScoutRubricsRetrieve: jest.fn(),
}))
+jest.mock('lib/utils/dom', () => ({
+ ...jest.requireActual('lib/utils/dom'),
+ downloadFile: jest.fn(),
+}))
+
+jest.mock('products/tasks/frontend/generated/api', () => ({
+ ...jest.requireActual('products/tasks/frontend/generated/api'),
+ tasksRunsCancelCreate: jest.fn(),
+}))
+
const savedRubric: ScoutRubricDocumentApi = {
config_id: trialFixtureConfig.id,
skill_name: trialFixtureConfig.skill_name,
@@ -64,10 +83,42 @@ describe('ScoutTrialsPanel', () => {
jest.mocked(signalsScoutConfigList).mockResolvedValue([trialFixtureConfig])
jest.mocked(signalsScoutConfigTrialSetup).mockResolvedValue(trialFixtureSetup)
jest.mocked(signalsScoutConfigTrialHistory).mockResolvedValue({ results: [], has_more: false })
- jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({ results: [], has_more: false })
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
+ results: [],
+ next_cursor: null,
+ has_more: false,
+ })
jest.mocked(signalsScoutRubricsRetrieve).mockResolvedValue(savedRubric)
})
+ it('navigates between trial history pages and disables navigation while loading', async () => {
+ const recent = { ...trialFixtureServerComparison, comparison_id: 'new-trial', variants: [] }
+ const older = { ...trialFixtureServerComparison, comparison_id: 'old-trial', variants: [] }
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
+ results: [recent],
+ has_more: true,
+ next_cursor: 'older-trials',
+ })
+ render(<ScoutTrialsPanel teamId={2} userId={42} configId={trialFixtureConfig.id} />)
+ expect(await screen.findByText('Trial new-tria')).toBeTruthy()
+ const page = promiseResolveReject<ScoutTrialComparisonHistoryApi>()
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockReturnValueOnce(page.promise)
+ await userEvent.click(screen.getByLabelText('Next page'))
+ expect(screen.getByLabelText('Next page').getAttribute('aria-disabled')).toBe('true')
+ expect(screen.getByLabelText('Previous page').getAttribute('aria-disabled')).toBe('true')
+ expect(screen.getByText('Trial new-tria')).toBeTruthy()
+ await act(async () => page.resolve({ results: [older], has_more: false, next_cursor: null }))
+ expect(await screen.findByText('Trial old-tria')).toBeTruthy()
+ expect(screen.queryByText('Trial new-tria')).toBeNull()
+ expect(screen.getByLabelText('Next page').getAttribute('aria-disabled')).toBe('true')
+ await userEvent.click(screen.getByLabelText('Previous page'))
+ expect(await screen.findByText('Trial new-tria')).toBeTruthy()
+ expect(signalsScoutConfigTrialComparisonHistory).toHaveBeenLastCalledWith('2', trialFixtureConfig.id, {
+ limit: 30,
+ include_archived: false,
+ })
+ })
+
test.each([true, false])(
'waits for a saved rubric before starting a trial with captured reference=%s',
async (hasReference) => {
@@ -123,6 +174,7 @@ describe('ScoutTrialsPanel', () => {
featureFlagLogic.actions.setFeatureFlags([], {})
jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
results: [trialFixtureServerComparison],
+ next_cursor: null,
has_more: false,
})
jest.mocked(signalsScoutConfigTrialComparisonRetrieve).mockResolvedValue(trialFixtureServerComparison)
@@ -143,30 +195,64 @@ describe('ScoutTrialsPanel', () => {
}
)
+ it('lists runs and reloads unconfirmed results from refresh in a new judging attempt', async () => {
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
+ results: [trialFixtureServerComparison],
+ next_cursor: null,
+ has_more: false,
+ })
+ jest.mocked(signalsScoutConfigTrialComparisonRetrieve).mockResolvedValue(trialFixtureServerComparison)
+ jest.mocked(signalsScoutConfigTrialEvaluationRetrieve).mockRejectedValue(new ApiError('Not found', 404))
+ jest.mocked(signalsScoutConfigTrialResult).mockResolvedValue({ ...trialFixtureResult, status: 'unknown' })
+
+ render(<ScoutTrialsPanel teamId={2} userId={42} />)
+
+ await userEvent.click(
+ await screen.findByText(`Trial ${trialFixtureServerComparison.comparison_id.slice(0, 8)}`)
+ )
+ await userEvent.click(await screen.findByText('Judge these runs again'))
+ await userEvent.click(screen.getByText('Prepare another judging attempt'))
+ const judge = (): HTMLElement | null => screen.getByText('Judge saved runs').closest('button')
+ await waitFor(() => expect(judge()?.getAttribute('aria-disabled')).toBe('true'))
+
+ expect(screen.getAllByText('Run details').length).toBeGreaterThan(0)
+
+ jest.mocked(signalsScoutConfigTrialResult).mockResolvedValue(trialFixtureResult)
+ await userEvent.click(screen.getByText('Refresh status'))
+ await waitFor(() => expect(judge()?.getAttribute('aria-disabled')).toBe('false'))
+ })
+
it('keeps the stop action available when a failed scout still has a task waiting to start', async () => {
- jest.mocked(signalsScoutConfigTrialHistory).mockResolvedValue({
- results: [
- {
- ...trialFixtureResult,
- variant: 'Baseline',
- status: 'failed',
- started_at: trialFixtureResult.started_at!,
- run_id: trialFixtureResult.run_id!,
- task_id: trialFixtureResult.task_id!,
- task_run_id: trialFixtureResult.task_run_id!,
- },
- ],
+ const comparison = {
+ ...trialFixtureServerComparison,
+ status: 'failed' as const,
+ evaluation: null,
+ variants: [{ ...trialFixtureServerComparison.variants[0], launch_ids: [trialFixtureResult.launch_id] }],
+ }
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
+ results: [comparison],
+ next_cursor: null,
has_more: false,
})
+ jest.mocked(signalsScoutConfigTrialComparisonRetrieve).mockResolvedValue(comparison)
jest.mocked(signalsScoutConfigTrialResult).mockResolvedValue({
...trialFixtureResult,
status: 'failed',
task_status: 'not_started',
+ invalid_reason: 'Saved run data is unavailable. This run cannot be judged.',
})
render(<ScoutTrialsPanel teamId={2} userId={42} />)
- await userEvent.click(await screen.findByText('Individual run history'))
+ await userEvent.click(await screen.findByText(`Trial ${comparison.comparison_id.slice(0, 8)}`))
expect(await screen.findByText('Stop run')).not.toBeNull()
+ jest.mocked(tasksRunsCancelCreate).mockRejectedValueOnce(new Error('Connection closed'))
+ await userEvent.click(screen.getByText('Stop run'))
+ expect(await screen.findByText("Couldn't stop this run. Try again.")).not.toBeNull()
+ expect(screen.queryByText('Saved run data is unavailable. This run cannot be judged.')).toBeNull()
+ await userEvent.click(screen.getByText('Download results'))
+ expect(jest.mocked(downloadFile).mock.calls[0][0].name).toBe('scout-comparison-results.json')
+ await userEvent.click(screen.getByText('Run details'))
+ expect(await screen.findByText('Saved run data is unavailable. This run cannot be judged.')).not.toBeNull()
})
})
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialsView.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialsView.stories.tsx
index 875514ca94e8..68ee1542e892 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialsView.stories.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialsView.stories.tsx
@@ -31,7 +31,8 @@ const defaults: ScoutTrialsViewProps = {
trialsDisabledReason: null,
comparisonStates: {},
comparisonState: { value: null, loading: false, resuming: false, error: null, notStarted: false },
- comparisonHistory: { results: [], has_more: false },
+ comparisonHistory: { results: [], has_more: false, next_cursor: null },
+ comparisonHistoryCursors: [],
comparisonHistoryLoading: false,
comparisonRows: [],
managedComparison: false,
@@ -43,6 +44,8 @@ const defaults: ScoutTrialsViewProps = {
loadComparison: noop,
resumeComparison: noop,
loadComparisonHistory: noop,
+ nextComparisonHistoryPage: noop,
+ previousComparisonHistoryPage: noop,
comparisons: [],
comparisonsForConfig: [],
selectedComparisonIds: {},
@@ -71,12 +74,15 @@ const defaults: ScoutTrialsViewProps = {
resultErrors: {},
submitting: false,
refreshing: false,
+ refreshingLaunchIds: [],
+ showArchived: false,
+ archiving: [],
+ archiveErrors: {},
canceling: [],
cancelErrors: {},
pageError: null,
pollError: null,
formPageError: null,
- resultPollError: null,
loadErrors: { configs: null, setup: null, history: null, comparisonHistory: null },
selectedLaunchId: null,
rows: [],
@@ -100,6 +106,9 @@ const defaults: ScoutTrialsViewProps = {
selectResult: noop,
downloadResults: noop,
cancelRun: noop,
+ setShowArchived: noop,
+ archiveComparison: noop,
+ retryResult: noop,
}
const meta: Meta<typeof ScoutTrialsView> = {
@@ -335,5 +344,31 @@ export const MissingSavedRubric: Story = {
},
}
-export const History: Story = { args: { ...Scored.args, trialView: 'list' } }
+export const History: Story = {
+ args: {
+ ...Scored.args,
+ trialView: 'list',
+ comparisonHistory: { results: [trialFixtureServerComparison], has_more: true, next_cursor: 'older-trials' },
+ },
+}
export const HistoryNarrow: Story = { ...History, decorators: Narrow.decorators }
+
+export const Archived: Story = {
+ args: {
+ ...History.args,
+ showArchived: true,
+ comparisonStates: {
+ [trialFixtureComparison.id]: {
+ ...Scored.args!.comparisonState!,
+ value: { ...trialFixtureServerComparison, archived: true },
+ },
+ },
+ },
+}
+
+export const RunDetailsUnavailable: Story = {
+ args: {
+ ...Running.args,
+ resultErrors: { [runningRows[0].launchId]: "Couldn't load run details. Try again." },
+ },
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialsView.tsx b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialsView.tsx
index 6035dcefa5a0..b3607328d37a 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialsView.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialsView.tsx
@@ -7,7 +7,6 @@ import { scoutDisplayName } from '../../../../utils/scoutRunsWindow'
import { ScoutTrialDetail } from './ScoutTrialDetail'
import { ScoutTrialHistory } from './ScoutTrialHistory'
import { ScoutTrialRunDrawer } from './ScoutTrialRunDrawer'
-import { ScoutTrialRunHistory } from './ScoutTrialRunHistory'
import { ScoutTrialSetupPanel } from './ScoutTrialSetupPanel'
type ViewAction =
@@ -36,6 +35,11 @@ type ViewAction =
| 'loadComparison'
| 'resumeComparison'
| 'loadComparisonHistory'
+ | 'nextComparisonHistoryPage'
+ | 'previousComparisonHistoryPage'
+ | 'setShowArchived'
+ | 'archiveComparison'
+ | 'retryResult'
export type ScoutTrialsViewProps = scoutTrialsLogicValues & {
teamId: number
@@ -92,7 +96,25 @@ export function ScoutTrialsView(props: ScoutTrialsViewProps): JSX.Element {
{pageError}
</LemonBanner>
)}
- {props.pollError && <LemonBanner type="warning">{props.pollError}</LemonBanner>}
+ {props.pollError && (
+ <LemonBanner
+ type="warning"
+ action={{
+ children: 'Retry',
+ loading: props.comparisonHistoryLoading || props.historyLoading,
+ onClick: () => {
+ if (selectedConfigId) {
+ props.loadComparisonHistory(selectedConfigId)
+ if (props.loadErrors.history) {
+ props.loadHistory(selectedConfigId)
+ }
+ }
+ },
+ }}
+ >
+ {props.pollError}
+ </LemonBanner>
+ )}
{configsLoading && !configs ? (
<LemonSkeleton className="h-64" />
) : configs?.length === 0 ? (
@@ -116,10 +138,7 @@ export function ScoutTrialsView(props: ScoutTrialsViewProps): JSX.Element {
) : props.trialView === 'detail' && props.selectedComparison ? (
<ScoutTrialDetail {...props} />
) : (
- <>
- <ScoutTrialHistory {...props} />
- <ScoutTrialRunHistory {...props} />
- </>
+ <ScoutTrialHistory {...props} />
)}
</>
)
@@ -128,6 +147,12 @@ export function ScoutTrialsView(props: ScoutTrialsViewProps): JSX.Element {
result={props.selectedResult}
launchId={props.selectedLaunchId}
error={props.selectedLaunchId ? props.resultErrors[props.selectedLaunchId] : null}
+ loading={!!props.selectedLaunchId && props.refreshingLaunchIds.includes(props.selectedLaunchId)}
+ onRetry={() => {
+ if (props.selectedLaunchId) {
+ props.retryResult(props.selectedLaunchId)
+ }
+ }}
report={props.evaluationState.value?.report}
onClose={() => props.selectResult(null)}
/>
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialsFixtures.ts b/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialsFixtures.ts
index ad0500ceb4a5..97f2a3008b8f 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialsFixtures.ts
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialsFixtures.ts
@@ -426,6 +426,7 @@ trialFixtureLongReport.variants = trialFixtureLongReport.variants.map((variant)
}))
export const trialFixtureServerComparison: ScoutTrialComparisonApi = {
+ archived: false,
comparison_id: trialFixtureComparison.id,
config_id: trialFixtureComparison.configId,
context_id: trialFixtureResult.context_id,
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialsStoryMocks.ts b/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialsStoryMocks.ts
index eff83b07877d..ef8214c03166 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialsStoryMocks.ts
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialsStoryMocks.ts
@@ -6,6 +6,7 @@ import type {
ScoutRubricDocumentApi,
ScoutRubricSaveApi,
ScoutTrialComparisonApi,
+ ScoutTrialComparisonArchiveRequestApi,
ScoutTrialComparisonRequestApi,
ScoutTrialComparisonQueryApi,
ScoutTrialEvaluationApi,
@@ -117,13 +118,19 @@ export function createScoutTrialsStoryMocks(): { mocks: Mocks; runningMocks: Moc
const mocks: Mocks = {
get: {
'/api/projects/:team/signals/scout/rubrics/:config/': () => [200, rubric],
- '/api/projects/:team/signals/scout/configs/:config/trial_comparison_history/': () => [
+ '/api/projects/:team/signals/scout/configs/:config/trial_comparison_history/': ({ request }) => [
200,
{
results: [...comparisons.values()]
.reverse()
+ .filter(
+ (comparison) =>
+ !comparison.archived ||
+ new URL(request.url).searchParams.get('include_archived') === 'true'
+ )
.map((comparison) => ({ ...comparison, evaluation: null })),
has_more: false,
+ next_cursor: null,
},
],
'/api/projects/:team/signals/scout/configs/:config/trial_comparison_result/': ({ request }) => {
@@ -196,6 +203,19 @@ export function createScoutTrialsStoryMocks(): { mocks: Mocks; runningMocks: Moc
},
},
post: {
+ '/api/projects/:team/signals/scout/configs/:config/trial_comparison_archive/': async ({ request }) => {
+ const payload = (await request.json()) as ScoutTrialComparisonArchiveRequestApi
+ const comparison = comparisons.get(payload.comparison_id)
+ if (!comparison) {
+ return [404, { detail: 'Trial not found.' }]
+ }
+ if (payload.archived && comparison.status !== 'completed' && comparison.status !== 'failed') {
+ return [400, { detail: 'Only completed or failed trials can be archived.' }]
+ }
+ const updated = { ...comparison, archived: payload.archived }
+ comparisons.set(payload.comparison_id, updated)
+ return [200, updated]
+ },
'/api/projects/:team/signals/scout/configs/:config/trial_comparison/': async ({ request }) => {
const payload = (await request.json()) as ScoutTrialComparisonRequestApi
const existing = comparisons.get(payload.comparison_id)
@@ -224,6 +244,7 @@ export function createScoutTrialsStoryMocks(): { mocks: Mocks; runningMocks: Moc
})),
})
const comparison: ScoutTrialComparisonApi = {
+ archived: false,
comparison_id: payload.comparison_id,
config_id: trialFixtureConfig.id,
context_id: trialFixtureResult.context_id,
diff --git a/products/signals/frontend/inbox/logics/scoutTrialsLogic.test.ts b/products/signals/frontend/inbox/logics/scoutTrialsLogic.test.ts
index 66d333248012..c66809f4da25 100644
--- a/products/signals/frontend/inbox/logics/scoutTrialsLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scoutTrialsLogic.test.ts
@@ -13,6 +13,7 @@ import {
signalsScoutConfigList,
signalsScoutConfigTrial,
signalsScoutConfigTrialComparisonCreate,
+ signalsScoutConfigTrialComparisonArchive,
signalsScoutConfigTrialComparisonRetrieve,
signalsScoutConfigTrialComparisonHistory,
signalsScoutConfigTrialComparisonResume,
@@ -26,6 +27,7 @@ import type {
ScoutTrialEvaluationApi,
ScoutTrialResultApi,
ScoutTrialComparisonApi,
+ ScoutTrialComparisonHistoryApi,
} from 'products/signals/frontend/generated/api.schemas'
import { tasksRunsCancelCreate } from 'products/tasks/frontend/generated/api'
@@ -45,6 +47,7 @@ jest.mock('products/signals/frontend/generated/api', () => ({
signalsScoutConfigList: jest.fn(),
signalsScoutConfigTrial: jest.fn(),
signalsScoutConfigTrialComparisonCreate: jest.fn(),
+ signalsScoutConfigTrialComparisonArchive: jest.fn(),
signalsScoutConfigTrialComparisonRetrieve: jest.fn(),
signalsScoutConfigTrialComparisonHistory: jest.fn(),
signalsScoutConfigTrialComparisonResume: jest.fn(),
@@ -84,7 +87,11 @@ describe('scoutTrialsLogic', () => {
...trialFixtureResult,
launch_id: params.launch_id,
}))
- jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({ results: [], has_more: false })
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
+ results: [],
+ next_cursor: null,
+ has_more: false,
+ })
jest.mocked(signalsScoutConfigTrialComparisonRetrieve).mockRejectedValue(new ApiError('Not found', 404))
jest.mocked(signalsScoutConfigTrialComparisonResume).mockResolvedValue({
...trialFixtureServerComparison,
@@ -99,6 +106,11 @@ describe('scoutTrialsLogic', () => {
status: 'running',
evaluation: null,
}))
+ jest.mocked(signalsScoutConfigTrialComparisonArchive).mockImplementation(async (_, __, request) => ({
+ ...trialFixtureServerComparison,
+ comparison_id: request.comparison_id,
+ archived: request.archived,
+ }))
logic = scoutTrialsLogic({ teamId: 2, userId: 42 })
await expectLogic(logic, () => {
logic.mount()
@@ -297,6 +309,7 @@ describe('scoutTrialsLogic', () => {
evaluation: null,
},
],
+ next_cursor: null,
has_more: false,
})
throw new Error('Connection closed after saving the plan')
@@ -341,6 +354,7 @@ describe('scoutTrialsLogic', () => {
{ ...saved, status: 'not_started' },
{ ...saved, comparison_id: 'older-trial', status: 'completed', variants: [] },
],
+ next_cursor: null,
has_more: false,
})
await expectLogic(logic, () =>
@@ -375,6 +389,7 @@ describe('scoutTrialsLogic', () => {
jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
results: [{ ...saved, status: 'completed', evaluation: null }],
+ next_cursor: null,
has_more: false,
})
await expectLogic(logic, () =>
@@ -444,6 +459,281 @@ describe('scoutTrialsLogic', () => {
expect(signalsScoutConfigTrialResult).toHaveBeenCalledTimes(2)
})
+ it.each([404, 503])(
+ 'loads old run details only when opened and retries only the affected run (%s)',
+ async (status) => {
+ logic.unmount()
+ jest.useFakeTimers()
+ const visibility = jest.spyOn(document, 'hidden', 'get').mockReturnValue(false)
+ const launchId = trialFixtureComparison.groups[0].launchIds[0]
+ try {
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
+ results: [trialFixtureServerComparison],
+ next_cursor: null,
+ has_more: false,
+ })
+ jest.mocked(signalsScoutConfigTrialComparisonRetrieve).mockResolvedValue(trialFixtureServerComparison)
+ logic = scoutTrialsLogic({ teamId: 2, userId: 42 })
+ await expectLogic(logic, () => {
+ logic.mount()
+ }).toFinishAllListeners()
+ await jest.advanceTimersByTimeAsync(20_000)
+ expect(signalsScoutConfigTrialResult).not.toHaveBeenCalled()
+
+ jest.mocked(signalsScoutConfigTrialResult).mockImplementation(async (_, __, params) => {
+ if (params.launch_id === launchId) {
+ throw new ApiError('Saved result unavailable', status)
+ }
+ return { ...trialFixtureResult, launch_id: params.launch_id }
+ })
+ await expectLogic(logic, () =>
+ logic.actions.selectComparison(trialFixtureComparison.configId, trialFixtureComparison.id)
+ ).toFinishAllListeners()
+ expect(logic.values.resultErrors[launchId]).toBeTruthy()
+ expect(logic.values.comparisonRows.some((row) => row.launchId === launchId)).toBe(true)
+ expect(logic.values.pollError).toBeNull()
+ const calls = jest.mocked(signalsScoutConfigTrialResult).mock.calls.length
+ await jest.advanceTimersByTimeAsync(20_000)
+ expect(signalsScoutConfigTrialResult).toHaveBeenCalledTimes(calls)
+
+ const gate = promiseResolveReject<ScoutTrialResultApi>()
+ jest.mocked(signalsScoutConfigTrialResult).mockReturnValueOnce(gate.promise)
+ logic.actions.retryResult(launchId)
+ logic.actions.retryResult(launchId)
+ expect(signalsScoutConfigTrialResult).toHaveBeenCalledTimes(calls + 1)
+ expect(logic.values.refreshingLaunchIds).toEqual([launchId])
+ await expectLogic(logic, () =>
+ gate.resolve({ ...trialFixtureResult, launch_id: launchId })
+ ).toFinishAllListeners()
+ expect(logic.values.resultErrors).toEqual({})
+ expect(logic.values.refreshingLaunchIds).toEqual([])
+
+ const saved = logic.values.results[launchId]
+ jest.mocked(signalsScoutConfigTrialResult).mockRejectedValueOnce(new Error('Connection unavailable'))
+ await expectLogic(logic, () => logic.actions.retryResult(launchId)).toFinishAllListeners()
+ expect(logic.values.results[launchId]).toEqual(saved)
+ expect(logic.values.resultErrors[launchId]).toBeTruthy()
+ expect(logic.values.pollError).toBeNull()
+ await expectLogic(logic, () => logic.actions.loadResults([])).toFinishAllListeners()
+ expect(logic.values.pollError).toBeNull()
+ } finally {
+ visibility.mockRestore()
+ jest.useRealTimers()
+ }
+ }
+ )
+
+ it('archives on the server once, hides saved browser entries after reload, and restores archived trials', async () => {
+ const comparisonId = trialFixtureServerComparison.comparison_id
+ const archived = { ...trialFixtureServerComparison, archived: true, status: 'not_started' as const }
+ logic.actions.registerServerComparison(trialFixtureServerComparison)
+ const gate = promiseResolveReject<ScoutTrialComparisonApi>()
+ jest.mocked(signalsScoutConfigTrialComparisonArchive).mockReturnValueOnce(gate.promise)
+ logic.actions.archiveComparison(comparisonId, true)
+ logic.actions.archiveComparison(comparisonId, true)
+ expect(signalsScoutConfigTrialComparisonArchive).toHaveBeenCalledTimes(1)
+ expect(logic.values.archiving).toEqual([comparisonId])
+ await expectLogic(logic, () => gate.resolve(archived)).toFinishAllListeners()
+ expect(logic.values.comparisonsForConfig).toEqual([])
+ expect(logic.values.archiving).toEqual([])
+ expect(signalsScoutConfigTrialComparisonArchive).toHaveBeenCalledWith('2', trialFixtureConfig.id, {
+ comparison_id: comparisonId,
+ archived: true,
+ })
+
+ // An older browser session may still have this trial's identifiers saved.
+ logic.actions.registerComparison(trialFixtureComparison)
+ logic.unmount()
+ logic = scoutTrialsLogic({ teamId: 2, userId: 42 })
+ await expectLogic(logic, () => {
+ logic.mount()
+ }).toFinishAllListeners()
+ expect(logic.values.comparisonsForConfig).toEqual([])
+ expect(logic.values.tracked).toEqual([])
+ expect(signalsScoutConfigTrialResult).not.toHaveBeenCalled()
+
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
+ results: [archived],
+ next_cursor: null,
+ has_more: false,
+ })
+ await expectLogic(logic, () => logic.actions.setShowArchived(true)).toFinishAllListeners()
+ expect(logic.values.comparisonsForConfig.map((item) => item.id)).toEqual([comparisonId])
+ expect(signalsScoutConfigTrialComparisonHistory).toHaveBeenLastCalledWith('2', trialFixtureConfig.id, {
+ limit: 30,
+ include_archived: true,
+ })
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
+ results: [trialFixtureServerComparison],
+ next_cursor: null,
+ has_more: false,
+ })
+ await expectLogic(logic, () => logic.actions.archiveComparison(comparisonId, false)).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.setShowArchived(false)).toFinishAllListeners()
+ expect(logic.values.comparisonsForConfig.map((item) => item.id)).toEqual([comparisonId])
+ expect(logic.values.comparisonStates[comparisonId].value?.archived).toBe(false)
+
+ await expectLogic(logic, () => logic.actions.submitComparison()).toFinishAllListeners()
+ const startedHere = logic.values.batch!
+ await expectLogic(logic, () =>
+ logic.actions.registerServerComparison({ ...logic.values.comparisonState.value!, status: 'completed' })
+ ).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.showTrialList()).toFinishAllListeners()
+ expect(logic.values.batch?.comparison.id).toBe(startedHere.comparison.id)
+ expect(logic.values.comparisonsForConfig.map((item) => item.id)).not.toContain(startedHere.comparison.id)
+ const removedIds = startedHere.comparison.groups.flatMap((group) => group.launchIds)
+ expect(logic.values.tracked.some((entry) => removedIds.includes(entry.launchId))).toBe(false)
+ })
+
+ it('pages through older trials without losing access after reload or a failed page request', async () => {
+ const cursor = 'older-trials'
+ const recent = {
+ results: Array.from({ length: 30 }, (_, index) => ({
+ ...trialFixtureServerComparison,
+ comparison_id: `recent-trial-${index}`,
+ variants: [],
+ })),
+ has_more: true,
+ next_cursor: cursor,
+ }
+ const older = { results: [trialFixtureServerComparison], has_more: false, next_cursor: null }
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockImplementation(async (_, __, params) =>
+ params?.cursor ? older : recent
+ )
+ logic.actions.registerServerComparison(trialFixtureServerComparison)
+ await expectLogic(logic, () =>
+ logic.actions.loadComparisonHistory(trialFixtureConfig.id)
+ ).toFinishAllListeners()
+ expect(logic.values.comparisonsForConfig.map((trial) => trial.id)).toEqual(
+ recent.results.map((trial) => trial.comparison_id)
+ )
+
+ const page = promiseResolveReject<ScoutTrialComparisonHistoryApi>()
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockReturnValueOnce(page.promise)
+ const calls = jest.mocked(signalsScoutConfigTrialComparisonHistory).mock.calls.length
+ logic.actions.nextComparisonHistoryPage()
+ logic.actions.nextComparisonHistoryPage()
+ expect(signalsScoutConfigTrialComparisonHistory).toHaveBeenCalledTimes(calls + 1)
+ expect(logic.values.comparisonHistoryCursors).toEqual([])
+ await expectLogic(logic, () => page.reject(new Error('Connection unavailable'))).toFinishAllListeners()
+ expect(logic.values.comparisonHistory).toEqual(recent)
+ expect(logic.values.comparisonHistoryCursors).toEqual([])
+ expect(logic.values.comparisonsForConfig).toHaveLength(30)
+
+ await expectLogic(logic, () => logic.actions.nextComparisonHistoryPage()).toFinishAllListeners()
+ expect(signalsScoutConfigTrialComparisonHistory).toHaveBeenLastCalledWith('2', trialFixtureConfig.id, {
+ limit: 30,
+ include_archived: false,
+ cursor,
+ })
+ expect(logic.values.comparisonHistoryCursors).toEqual([cursor])
+ expect(logic.values.comparisonsForConfig.map((trial) => trial.id)).toEqual([
+ trialFixtureServerComparison.comparison_id,
+ ])
+ expect(logic.values.loadErrors.comparisonHistory).toBeNull()
+ jest.mocked(signalsScoutConfigTrialComparisonRetrieve).mockResolvedValue(trialFixtureServerComparison)
+ await expectLogic(logic, () =>
+ logic.actions.selectComparison(trialFixtureConfig.id, trialFixtureServerComparison.comparison_id)
+ ).toFinishAllListeners()
+ expect(logic.values.comparisonState.value).toEqual(trialFixtureServerComparison)
+ await expectLogic(logic, () => logic.actions.showTrialList()).toFinishAllListeners()
+ expect(logic.values.comparisonHistoryCursors).toEqual([cursor])
+ await expectLogic(logic, () => logic.actions.previousComparisonHistoryPage()).toFinishAllListeners()
+ expect(logic.values.comparisonHistoryCursors).toEqual([])
+ expect(logic.values.comparisonsForConfig).toHaveLength(30)
+
+ logic.unmount()
+ logic = scoutTrialsLogic({ teamId: 2, userId: 42 })
+ await expectLogic(logic, () => {
+ logic.mount()
+ }).toFinishAllListeners()
+ expect(logic.values.comparisonHistoryCursors).toEqual([])
+ await expectLogic(logic, () => logic.actions.nextComparisonHistoryPage()).toFinishAllListeners()
+ expect(logic.values.comparisonsForConfig.map((trial) => trial.id)).toEqual([
+ trialFixtureServerComparison.comparison_id,
+ ])
+ })
+
+ it.each(['scout', 'archived filter'])(
+ 'resets pagination and ignores a stale page after changing %s',
+ async (change) => {
+ const first = { results: [trialFixtureServerComparison], has_more: true, next_cursor: 'page-2' }
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue(first)
+ await expectLogic(logic, () =>
+ logic.actions.loadComparisonHistory(trialFixtureConfig.id)
+ ).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.nextComparisonHistoryPage()).toFinishAllListeners()
+ expect(logic.values.comparisonHistoryCursors).toEqual(['page-2'])
+ const page = promiseResolveReject<ScoutTrialComparisonHistoryApi>()
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockReturnValueOnce(page.promise)
+ logic.actions.nextComparisonHistoryPage()
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
+ results: [],
+ has_more: false,
+ next_cursor: null,
+ })
+ if (change === 'scout') {
+ logic.actions.selectConfig('another-scout')
+ } else {
+ logic.actions.setShowArchived(true)
+ }
+ await expectLogic(logic, () => page.resolve(first)).toFinishAllListeners()
+ expect(logic.values.comparisonHistoryCursors).toEqual([])
+ expect(logic.values.comparisonHistory?.results).toEqual([])
+ expect(signalsScoutConfigTrialComparisonHistory).toHaveBeenLastCalledWith(
+ '2',
+ change === 'scout' ? 'another-scout' : trialFixtureConfig.id,
+ { limit: 30, include_archived: change !== 'scout' }
+ )
+ }
+ )
+
+ it('keeps an opened trial available when a pending history page finishes', async () => {
+ const first = { results: [trialFixtureServerComparison], has_more: true, next_cursor: 'page-2' }
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue(first)
+ jest.mocked(signalsScoutConfigTrialComparisonRetrieve).mockResolvedValue(trialFixtureServerComparison)
+ await expectLogic(logic, () =>
+ logic.actions.loadComparisonHistory(trialFixtureConfig.id)
+ ).toFinishAllListeners()
+ const page = promiseResolveReject<ScoutTrialComparisonHistoryApi>()
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockReturnValueOnce(page.promise)
+ logic.actions.nextComparisonHistoryPage()
+ logic.actions.selectComparison(trialFixtureConfig.id, trialFixtureServerComparison.comparison_id)
+ await expectLogic(logic, () =>
+ page.resolve({ results: [], has_more: false, next_cursor: null })
+ ).toFinishAllListeners()
+ expect(logic.values.selectedComparison?.id).toBe(trialFixtureServerComparison.comparison_id)
+ expect(logic.values.comparisonState.value).toEqual(trialFixtureServerComparison)
+ expect(logic.values.trialView).toBe('detail')
+ })
+
+ it('keeps a trial visible if archiving fails, and does not archive an active trial', async () => {
+ const comparisonId = trialFixtureServerComparison.comparison_id
+ logic.actions.registerServerComparison({ ...trialFixtureServerComparison, status: 'running' })
+ await expectLogic(logic, () => logic.actions.archiveComparison(comparisonId, true)).toFinishAllListeners()
+ expect(signalsScoutConfigTrialComparisonArchive).not.toHaveBeenCalled()
+
+ logic.actions.registerServerComparison(trialFixtureServerComparison)
+ jest.mocked(signalsScoutConfigTrialComparisonArchive).mockRejectedValueOnce(new Error('Save failed'))
+ await expectLogic(logic, () => logic.actions.archiveComparison(comparisonId, true)).toFinishAllListeners()
+ expect(logic.values.comparisonsForConfig.map((item) => item.id)).toEqual([comparisonId])
+ expect(logic.values.archiveErrors[comparisonId]).toBeTruthy()
+ expect(logic.values.archiving).toEqual([])
+
+ await expectLogic(logic, () =>
+ logic.actions.loadComparisonHistorySuccess({
+ results: [{ ...trialFixtureServerComparison, status: 'not_started', archived: true }],
+ next_cursor: null,
+ has_more: false,
+ })
+ ).toFinishAllListeners()
+ expect(logic.values.comparisonStates[comparisonId].value).toMatchObject({
+ status: 'completed',
+ archived: true,
+ })
+ expect(logic.values.comparisonsForConfig).toEqual([])
+ })
+
it('bounds concurrent result reads and preserves successful, failed, and missing launch results', async () => {
const launches = Array.from({ length: 12 }, (_, index) => `launch-${index}`)
const gate = promiseResolveReject<void>()
@@ -466,7 +756,7 @@ describe('scoutTrialsLogic', () => {
}
})
logic.actions.trackLaunches(launches.map((launchId) => ({ configId: trialFixtureConfig.id, launchId })))
- logic.actions.refreshResults()
+ logic.actions.loadResults(launches)
try {
expect(signalsScoutConfigTrialResult).toHaveBeenCalledTimes(5)
expect(logic.values.refreshing).toBe(true)
@@ -477,7 +767,7 @@ describe('scoutTrialsLogic', () => {
expect(maximumActive).toBe(5)
expect(signalsScoutConfigTrialResult).toHaveBeenCalledTimes(12)
expect(Object.keys(logic.values.results)).toEqual(launches.filter((_, index) => index !== 2 && index !== 7))
- expect(Object.keys(logic.values.resultErrors)).toEqual([launches[2]])
+ expect(Object.keys(logic.values.resultErrors)).toEqual([launches[2], launches[7]])
expect(logic.values.tracked.map(({ launchId }) => launchId)).not.toContain(launches[7])
expect(logic.values.refreshing).toBe(false)
})
@@ -491,7 +781,7 @@ describe('scoutTrialsLogic', () => {
logic.actions.trackLaunches(
Array.from({ length: 12 }, (_, index) => ({ configId: trialFixtureConfig.id, launchId: `launch-${index}` }))
)
- logic.actions.refreshResults()
+ logic.actions.loadResults(logic.values.tracked.map((entry) => entry.launchId))
logic.unmount()
try {
await expectLogic(logic, () => gate.resolve()).toFinishAllListeners()
@@ -540,11 +830,11 @@ describe('scoutTrialsLogic', () => {
}
})
- it('stops polling a missing old launch until the server confirms it in history', async () => {
+ it('does not poll a missing historical run and reloads it when opened explicitly', async () => {
const launchId = trialFixtureResult.launch_id
logic.actions.trackLaunches([{ configId: trialFixtureConfig.id, launchId }])
jest.mocked(signalsScoutConfigTrialResult).mockRejectedValueOnce(new ApiError('Not found', 404))
- await expectLogic(logic, () => logic.actions.refreshResults()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.retryResult(launchId)).toFinishAllListeners()
await expectLogic(logic, () => logic.actions.refreshResults()).toFinishAllListeners()
expect(signalsScoutConfigTrialResult).toHaveBeenCalledTimes(1)
expect(logic.values.tracked).toEqual([])
@@ -564,11 +854,15 @@ describe('scoutTrialsLogic', () => {
has_more: false,
})
}).toFinishAllListeners()
+ expect(signalsScoutConfigTrialResult).toHaveBeenCalledTimes(1)
+ expect(logic.values.pollError).toBeNull()
+ await expectLogic(logic, () => logic.actions.selectResult(launchId)).toFinishAllListeners()
expect(logic.values.results[launchId]).toEqual(trialFixtureResult)
+ expect(logic.values.resultErrors).toEqual({})
expect(logic.values.pollError).toBeNull()
})
- it('fetches a completed run found in history while an earlier result is loading', async () => {
+ it('leaves completed history unloaded until the run is opened', async () => {
let resolveOld!: (value: ScoutTrialResultApi) => void
jest.mocked(signalsScoutConfigTrialResult).mockImplementationOnce(
() =>
@@ -577,7 +871,7 @@ describe('scoutTrialsLogic', () => {
})
)
logic.actions.trackLaunches([{ configId: trialFixtureConfig.id, launchId: trialFixtureResult.launch_id }])
- logic.actions.refreshResults()
+ logic.actions.retryResult(trialFixtureResult.launch_id)
const newLaunch = '00000000-0000-4000-8000-000000000012'
logic.actions.loadHistorySuccess({
results: [
@@ -594,6 +888,9 @@ describe('scoutTrialsLogic', () => {
has_more: false,
})
await expectLogic(logic, () => resolveOld(trialFixtureResult)).toFinishAllListeners()
+ expect(logic.values.results[newLaunch]).toBeUndefined()
+ expect(signalsScoutConfigTrialResult).toHaveBeenCalledTimes(1)
+ await expectLogic(logic, () => logic.actions.selectResult(newLaunch)).toFinishAllListeners()
expect(logic.values.results[newLaunch]?.launch_id).toBe(newLaunch)
expect(signalsScoutConfigTrialResult).toHaveBeenCalledTimes(2)
})
@@ -607,23 +904,26 @@ describe('scoutTrialsLogic', () => {
})
)
logic.actions.trackLaunches([{ configId: trialFixtureConfig.id, launchId: trialFixtureResult.launch_id }])
- logic.actions.refreshResults()
+ logic.actions.retryResult(trialFixtureResult.launch_id)
const newConfig = '00000000-0000-4000-8000-000000000010'
jest.mocked(signalsScoutConfigTrialSetup).mockResolvedValue({ ...trialFixtureSetup, config_id: newConfig })
- await expectLogic(logic, () => logic.actions.selectConfig(newConfig)).toDispatchActions(['loadHistorySuccess'])
+ await expectLogic(logic, () => logic.actions.selectConfig(newConfig)).toDispatchActions([
+ 'loadComparisonHistorySuccess',
+ ])
await expectLogic(logic, () => rejectOld(new Error('Old result failed'))).toFinishAllListeners()
expect(logic.values.rows).toEqual([])
expect(logic.values.pollError).toBeNull()
})
- it('clears recovered history errors without clearing a separate result error', async () => {
+ it('keeps history failures page-wide and result failures attached only to their runs', async () => {
jest.mocked(signalsScoutConfigTrialHistory).mockRejectedValueOnce(new Error('History failed'))
await expectLogic(logic, () => logic.actions.loadHistory(trialFixtureConfig.id)).toFinishAllListeners()
expect(logic.values.pollError).toContain("Couldn't load recent runs")
await expectLogic(logic, () => logic.actions.loadHistory(trialFixtureConfig.id)).toFinishAllListeners()
expect(logic.values.pollError).toBeNull()
- logic.actions.setPollError('Result request failed')
+ const launchId = trialFixtureResult.launch_id
+ logic.actions.setResults({}, { [launchId]: 'Result request failed' })
jest.mocked(signalsScoutConfigTrialComparisonHistory).mockRejectedValueOnce(new Error('History failed'))
await expectLogic(logic, () =>
logic.actions.loadComparisonHistory(trialFixtureConfig.id)
@@ -632,7 +932,8 @@ describe('scoutTrialsLogic', () => {
await expectLogic(logic, () =>
logic.actions.loadComparisonHistory(trialFixtureConfig.id)
).toFinishAllListeners()
- expect(logic.values.pollError).toBe('Result request failed')
+ expect(logic.values.pollError).toBeNull()
+ expect(logic.values.resultErrors[launchId]).toBe('Result request failed')
})
it.each(['loadSetup', 'loadHistory', 'loadComparisonHistory'] as const)(
@@ -655,7 +956,6 @@ describe('scoutTrialsLogic', () => {
jest.mocked(signalsScoutConfigTrialSetup).mockResolvedValue({ ...trialFixtureSetup, config_id: newConfig })
await expectLogic(logic, () => logic.actions.selectConfig(newConfig)).toDispatchActions([
'loadSetupSuccess',
- 'loadHistorySuccess',
'loadComparisonHistorySuccess',
])
await expectLogic(logic, () => rejectOld(new Error('Old scout request failed'))).toFinishAllListeners()
@@ -716,8 +1016,7 @@ describe('scoutTrialsLogic', () => {
await expectLogic(logic, () => {
logic.mount()
}).toFinishAllListeners()
- logic.actions.trackLaunches([{ configId: trialFixtureConfig.id, launchId: trialFixtureResult.launch_id }])
- await expectLogic(logic, () => logic.actions.refreshResults()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.submitComparison()).toFinishAllListeners()
jest.mocked(signalsScoutConfigTrialResult).mockClear()
await jest.advanceTimersByTimeAsync(10_000)
@@ -741,7 +1040,7 @@ describe('scoutTrialsLogic', () => {
launchId: `old-launch-${index}`,
}))
)
- logic.actions.refreshResults()
+ logic.actions.loadResults(logic.values.tracked.map((entry) => entry.launchId))
const newConfig = '00000000-0000-4000-8000-000000000010'
const newLaunch = '00000000-0000-4000-8000-000000000011'
jest.mocked(signalsScoutConfigTrialSetup).mockResolvedValue({ ...trialFixtureSetup, config_id: newConfig })
@@ -764,7 +1063,11 @@ describe('scoutTrialsLogic', () => {
has_more: false,
})
- await expectLogic(logic, () => logic.actions.selectConfig(newConfig)).toDispatchActions(['loadHistorySuccess'])
+ await expectLogic(logic, () => logic.actions.selectConfig(newConfig)).toDispatchActions([
+ 'loadComparisonHistorySuccess',
+ ])
+ logic.actions.trackLaunches([{ configId: newConfig, launchId: newLaunch }])
+ logic.actions.selectResult(newLaunch)
await expectLogic(logic, () => gate.resolve()).toFinishAllListeners()
expect(signalsScoutConfigTrialResult).toHaveBeenCalledTimes(6)
@@ -782,11 +1085,17 @@ describe('scoutTrialsLogic', () => {
await expectLogic(logic, () => logic.actions.submitComparison()).toFinishAllListeners()
const tracked = logic.values.tracked
const comparison = logic.values.selectedComparison
- jest.mocked(signalsScoutConfigTrialComparisonRetrieve).mockResolvedValue({
+ const savedComparison = {
...logic.values.comparisonState.value!,
- status: 'completed',
+ status: 'completed' as const,
evaluation: trialFixtureEvaluation,
+ }
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
+ results: [savedComparison],
+ next_cursor: null,
+ has_more: false,
})
+ jest.mocked(signalsScoutConfigTrialComparisonRetrieve).mockResolvedValue(savedComparison)
logic.actions.updateEvaluation(comparison!.id, { value: trialFixtureEvaluation })
const stored = JSON.stringify(localStorage)
expect(stored).not.toContain('Private replacement prompt')
@@ -807,10 +1116,19 @@ describe('scoutTrialsLogic', () => {
expect(logic.values.selectedComparison).toEqual(comparison)
expect(logic.values.evaluationState.value?.report).toEqual(trialFixtureEvaluation.report)
expect(logic.values.comparisonState.value?.status).toBe('completed')
+ expect(signalsScoutConfigTrialComparisonRetrieve).not.toHaveBeenCalled()
+ await expectLogic(logic, () =>
+ logic.actions.selectComparison(comparison!.configId, comparison!.id)
+ ).toFinishAllListeners()
expect(signalsScoutConfigTrialComparisonRetrieve).toHaveBeenLastCalledWith('2', trialFixtureConfig.id, {
comparison_id: comparison!.id,
})
expect(signalsScoutConfigTrialEvaluationCreate).not.toHaveBeenCalled()
+ jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
+ results: [],
+ next_cursor: null,
+ has_more: false,
+ })
const otherUser = scoutTrialsLogic({ teamId: 2, userId: 43 })
await expectLogic(otherUser, () => {
otherUser.mount()
@@ -828,6 +1146,7 @@ describe('scoutTrialsLogic', () => {
})
jest.mocked(signalsScoutConfigTrialComparisonHistory).mockResolvedValue({
results: [trialFixtureServerComparison],
+ next_cursor: null,
has_more: false,
})
jest.mocked(signalsScoutConfigTrialComparisonRetrieve).mockResolvedValue(trialFixtureServerComparison)
@@ -884,6 +1203,13 @@ describe('scoutTrialsLogic', () => {
expect(signalsScoutConfigTrialComparisonResume).not.toHaveBeenCalled()
featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SCOUT_TRIALS], { [FEATURE_FLAGS.SCOUT_TRIALS]: true })
+ const archive = promiseResolveReject<ScoutTrialComparisonApi>()
+ jest.mocked(signalsScoutConfigTrialComparisonArchive).mockReturnValueOnce(archive.promise)
+ logic.actions.archiveComparison(trialFixtureComparison.id, true)
+ logic.actions.resumeComparison()
+ expect(signalsScoutConfigTrialComparisonResume).not.toHaveBeenCalled()
+ await expectLogic(logic, () => archive.reject(new Error('Save failed'))).toFinishAllListeners()
+
logic.actions.resumeComparison()
logic.actions.resumeComparison()
expect(signalsScoutConfigTrialComparisonResume).toHaveBeenCalledTimes(1)
@@ -1006,6 +1332,9 @@ describe('scoutTrialsLogic', () => {
logic.mount()
}).toFinishAllListeners()
expect(logic.values.selectedComparison?.id).toBe(next.id)
+ await expectLogic(logic, () =>
+ logic.actions.selectComparison(next.configId, next.id)
+ ).toFinishAllListeners()
expect(logic.values.evaluationState.preparedRequest).toEqual({
...previousEvaluation.request,
evaluation_id: next.id,
@@ -1094,7 +1423,7 @@ describe('scoutTrialsLogic', () => {
task_status: stopped ? 'cancelled' : 'in_progress',
}))
logic.actions.trackLaunches([{ configId: trialFixtureConfig.id, launchId }])
- await expectLogic(logic, () => logic.actions.refreshResults(true)).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.selectResult(launchId)).toFinishAllListeners()
const rowError = (): string | null | undefined =>
logic.values.rows.find((row) => row.launchId === launchId)?.error
jest.mocked(tasksRunsCancelCreate).mockRejectedValueOnce(new Error('Connection closed'))
diff --git a/products/signals/frontend/inbox/logics/scoutTrialsLogic.ts b/products/signals/frontend/inbox/logics/scoutTrialsLogic.ts
index 08c3ce327096..a9861329938c 100644
--- a/products/signals/frontend/inbox/logics/scoutTrialsLogic.ts
+++ b/products/signals/frontend/inbox/logics/scoutTrialsLogic.ts
@@ -24,6 +24,7 @@ import { downloadFile, uuid } from 'lib/utils/dom'
import {
signalsScoutConfigList,
signalsScoutConfigTrialComparisonCreate,
+ signalsScoutConfigTrialComparisonArchive,
signalsScoutConfigTrialComparisonRetrieve,
signalsScoutConfigTrialComparisonHistory,
signalsScoutConfigTrialComparisonResume,
@@ -115,10 +116,13 @@ export interface ScoutTrialsLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scoutTrialsLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
+ archiveErrors: Record<string, string>
+ archiving: string[]
batch: ScoutTrialBatch | null
cancelErrors: Record<string, string>
canceling: string[]
comparisonHistory: ScoutTrialComparisonHistoryApi | null
+ comparisonHistoryCursors: string[]
comparisonHistoryLoading: boolean
comparisonRows: ScoutTrialRow[]
comparisonState: ScoutTrialComparisonState
@@ -140,9 +144,9 @@ export interface scoutTrialsLogicValues {
pageError: string | null
pollError: string | null
refreshing: boolean
+ refreshingLaunchIds: string[]
repeats: number
resultErrors: Record<string, string>
- resultPollError: string | null
results: Record<string, ScoutTrialResultApi>
rows: ScoutTrialRow[]
scoreDisabledReason: string | null
@@ -154,6 +158,7 @@ export interface scoutTrialsLogicValues {
serverComparisonIds: string[]
setup: ScoutTrialSetupApi | null
setupLoading: boolean
+ showArchived: boolean
submitting: boolean
totalRuns: number
tracked: TrackedScoutTrial[]
@@ -167,6 +172,13 @@ export interface scoutTrialsLogicActions {
addVariant: () => {
value: true
}
+ archiveComparison: (
+ comparisonId: string,
+ archived: boolean
+ ) => {
+ archived: boolean
+ comparisonId: string
+ }
cancelRun: (launchId: string) => {
launchId: string
}
@@ -182,7 +194,14 @@ export interface scoutTrialsLogicActions {
loadComparison: (comparisonId: string) => {
comparisonId: string
}
- loadComparisonHistory: (configId: string) => string
+ loadComparisonHistory: (
+ configId: string,
+ cursors?: string[]
+ ) => {
+ configId: string
+ cursors: string[]
+ includeArchived: boolean
+ }
loadComparisonHistoryFailure: (
error: string,
errorObject?: any
@@ -192,10 +211,10 @@ export interface scoutTrialsLogicActions {
}
loadComparisonHistorySuccess: (
comparisonHistory: ScoutTrialComparisonHistoryApi | null,
- payload?: string
+ payload?: { configId: string; cursors: string[]; includeArchived: boolean }
) => {
comparisonHistory: ScoutTrialComparisonHistoryApi | null
- payload?: string
+ payload?: { configId: string; cursors: string[]; includeArchived: boolean }
}
loadConfigs: () => any
loadConfigsFailure: (
@@ -230,6 +249,9 @@ export interface scoutTrialsLogicActions {
history: ScoutTrialHistoryApi | null
payload?: string
}
+ loadResults: (launchIds: string[]) => {
+ launchIds: string[]
+ }
loadSetup: (configId: string) => string
loadSetupFailure: (
error: string,
@@ -251,6 +273,18 @@ export interface scoutTrialsLogicActions {
newScoringAttempt: () => {
value: true
}
+ nextComparisonHistoryPage: () => { value: true }
+ previousComparisonHistoryPage: () => { value: true }
+ reconcileComparisons: (
+ configId: string,
+ comparisonIds: string[]
+ ) => {
+ batchId: string | undefined
+ comparisonIds: string[]
+ configId: string
+ managedIds: string[]
+ selectedId: string | undefined
+ }
refreshResults: (force?: boolean) => {
force: boolean
}
@@ -269,6 +303,9 @@ export interface scoutTrialsLogicActions {
retryPageLoad: () => {
value: true
}
+ retryResult: (launchId: string) => {
+ launchId: string
+ }
scoreComparison: () => {
value: true
}
@@ -285,6 +322,20 @@ export interface scoutTrialsLogicActions {
selectResult: (launchId: string | null) => {
launchId: string | null
}
+ setArchiveError: (
+ comparisonId: string,
+ error: string | null
+ ) => {
+ comparisonId: string
+ error: string | null
+ }
+ setArchiving: (
+ comparisonId: string,
+ archiving: boolean
+ ) => {
+ archiving: boolean
+ comparisonId: string
+ }
setBatch: (batch: ScoutTrialBatch | null) => {
batch: ScoutTrialBatch | null
}
@@ -301,10 +352,11 @@ export interface scoutTrialsLogicActions {
setPageError: (error: string | null) => {
error: string | null
}
- setPollError: (error: string | null) => {
- error: string | null
- }
- setRefreshing: (refreshing: boolean) => {
+ setRefreshingLaunches: (
+ launchIds: string[],
+ refreshing: boolean
+ ) => {
+ launchIds: string[]
refreshing: boolean
}
setRepeats: (repeats: number) => {
@@ -317,6 +369,9 @@ export interface scoutTrialsLogicActions {
errors: Record<string, string>
results: Record<string, ScoutTrialResultApi>
}
+ setShowArchived: (showArchived: boolean) => {
+ showArchived: boolean
+ }
setSubmitting: (submitting: boolean) => {
submitting: boolean
}
@@ -365,7 +420,8 @@ export interface scoutTrialsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
trialsDisabledReason: (featureFlags: FeatureFlagsSet) => string | null
pageError: (loadErrors: ScoutTrialLoadErrors, formPageError: string | null) => string | null
- pollError: (loadErrors: ScoutTrialLoadErrors, resultPollError: string | null) => string | null
+ pollError: (loadErrors: ScoutTrialLoadErrors) => string | null
+ refreshing: (refreshingLaunchIds: string[]) => boolean
comparisonState: (
selectedComparison: ScoutTrialComparison | null,
comparisonStates: Record<string, ScoutTrialComparisonState>
@@ -374,7 +430,9 @@ export interface scoutTrialsLogicMeta {
comparisonRows: (rows: ScoutTrialRow[], selectedComparison: ScoutTrialComparison | null) => ScoutTrialRow[]
comparisonsForConfig: (
comparisons: ScoutTrialComparison[],
- selectedConfigId: string | null
+ selectedConfigId: string | null,
+ showArchived: boolean,
+ comparisonStates: Record<string, ScoutTrialComparisonState>
) => ScoutTrialComparison[]
selectedComparison: (
comparisonsForConfig: ScoutTrialComparison[],
@@ -408,7 +466,8 @@ export interface scoutTrialsLogicMeta {
resultErrors: Record<string, string>,
batch: ScoutTrialBatch | null,
comparisonStates: Record<string, ScoutTrialComparisonState>,
- cancelErrors: Record<string, string>
+ cancelErrors: Record<string, string>,
+ selectedComparison: ScoutTrialComparison | null
) => ScoutTrialRow[]
}
}
@@ -432,6 +491,30 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
update,
}),
loadComparison: (comparisonId: string) => ({ comparisonId }),
+ archiveComparison: (comparisonId: string, archived: boolean) => ({ comparisonId, archived }),
+ setArchiving: (comparisonId: string, archiving: boolean) => ({ comparisonId, archiving }),
+ setArchiveError: (comparisonId: string, error: string | null) => ({ comparisonId, error }),
+ setShowArchived: (showArchived: boolean) => ({ showArchived }),
+ loadComparisonHistory: (configId: string, cursors: string[] = values.comparisonHistoryCursors) => ({
+ configId,
+ cursors,
+ includeArchived: values.showArchived,
+ }),
+ nextComparisonHistoryPage: true,
+ previousComparisonHistoryPage: true,
+ reconcileComparisons: (configId: string, comparisonIds: string[]) => ({
+ configId,
+ comparisonIds,
+ batchId:
+ values.batch &&
+ (values.submitting ||
+ values.hasUnaccepted ||
+ comparisonIsActive(values.comparisonStates[values.batch.comparison.id]?.value?.status ?? ''))
+ ? values.batch.comparison.id
+ : undefined,
+ managedIds: values.serverComparisonIds,
+ selectedId: values.trialView === 'detail' ? values.selectedComparison?.id : undefined,
+ }),
resumeComparison: true,
registerComparison: (comparison: ScoutTrialComparison) => ({ comparison }),
selectComparison: (configId: string, comparisonId: string) => ({ configId, comparisonId }),
@@ -461,14 +544,15 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
errors,
}),
setSubmitting: (submitting: boolean) => ({ submitting }),
- setRefreshing: (refreshing: boolean) => ({ refreshing }),
+ setRefreshingLaunches: (launchIds: string[], refreshing: boolean) => ({ launchIds, refreshing }),
setPageError: (error: string | null) => ({ error }),
- setPollError: (error: string | null) => ({ error }),
retryPageLoad: true,
submitComparison: true,
newComparison: () => ({ enabled: !values.trialsDisabledReason }),
showTrialList: true,
refreshResults: (force: boolean = false) => ({ force }),
+ loadResults: (launchIds: string[]) => ({ launchIds }),
+ retryResult: (launchId: string) => ({ launchId }),
selectResult: (launchId: string | null) => ({ launchId }),
downloadResults: true,
cancelRun: (launchId: string) => ({ launchId }),
@@ -508,6 +592,11 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
let history: ScoutTrialHistoryApi
try {
history = await signalsScoutConfigTrialHistory(String(props.teamId), configId, { limit: 30 })
+ } catch (error) {
+ if (values.selectedConfigId !== configId) {
+ return values.history
+ }
+ throw error
} finally {
breakpoint()
}
@@ -518,11 +607,13 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
comparisonHistory: [
null as ScoutTrialComparisonHistoryApi | null,
{
- loadComparisonHistory: async (configId: string, breakpoint) => {
+ loadComparisonHistory: async ({ configId, cursors, includeArchived }, breakpoint) => {
let history: ScoutTrialComparisonHistoryApi
try {
history = await signalsScoutConfigTrialComparisonHistory(String(props.teamId), configId, {
limit: 30,
+ include_archived: includeArchived,
+ ...(cursors.length ? { cursor: cursors[cursors.length - 1] } : {}),
})
} finally {
breakpoint()
@@ -533,6 +624,36 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
],
})),
reducers({
+ showArchived: [false, { setShowArchived: (_, { showArchived }) => showArchived }],
+ comparisonHistoryCursors: [
+ [] as string[],
+ {
+ selectConfig: () => [],
+ setShowArchived: () => [],
+ loadComparisonHistorySuccess: (state, { payload }) => payload?.cursors ?? state,
+ },
+ ],
+ archiving: [
+ [] as string[],
+ {
+ setArchiving: (state, { comparisonId, archiving }) =>
+ archiving ? [...state, comparisonId] : state.filter((id) => id !== comparisonId),
+ },
+ ],
+ archiveErrors: [
+ {} as Record<string, string>,
+ {
+ setArchiveError: (state, { comparisonId, error }) => {
+ const next = { ...state }
+ if (error) {
+ next[comparisonId] = error
+ } else {
+ delete next[comparisonId]
+ }
+ return next
+ },
+ },
+ ],
comparisonStates: [
{} as Record<string, ScoutTrialComparisonState>,
{
@@ -568,6 +689,15 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
{
registerComparison: (state, { comparison }) =>
[...state.filter((item) => item.id !== comparison.id), comparison].slice(-100),
+ reconcileComparisons: (state, { configId, comparisonIds, batchId, managedIds, selectedId }) =>
+ state.filter(
+ (comparison) =>
+ comparison.configId !== configId ||
+ comparisonIds.includes(comparison.id) ||
+ !managedIds.includes(comparison.id) ||
+ comparison.id === batchId ||
+ comparison.id === selectedId
+ ),
},
],
selectedComparisonIds: [
@@ -629,9 +759,25 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
setResults: (state, { results }) => ({ ...state, ...results }),
},
],
- resultErrors: [{} as Record<string, string>, { setResults: (_, { errors }) => errors }],
+ resultErrors: [
+ {} as Record<string, string>,
+ {
+ setResults: (state, { results, errors }) => ({
+ ...Object.fromEntries(Object.entries(state).filter(([id]) => !(id in results))),
+ ...errors,
+ }),
+ untrackLaunches: (state, { launchIds }) =>
+ Object.fromEntries(Object.entries(state).filter(([id]) => !launchIds.includes(id))),
+ },
+ ],
submitting: [false, { setSubmitting: (_, { submitting }) => submitting }],
- refreshing: [false, { setRefreshing: (_, { refreshing }) => refreshing }],
+ refreshingLaunchIds: [
+ [] as string[],
+ {
+ setRefreshingLaunches: (state, { launchIds, refreshing }) =>
+ refreshing ? [...new Set([...state, ...launchIds])] : state.filter((id) => !launchIds.includes(id)),
+ },
+ ],
canceling: [
[] as string[],
{
@@ -683,13 +829,6 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
selectConfig: (state) => ({ ...EMPTY_LOAD_ERRORS, configs: state.configs }),
},
],
- resultPollError: [
- null as string | null,
- {
- setPollError: (_, { error }) => error,
- selectConfig: () => null,
- },
- ],
selectedLaunchId: [
null as string | null,
{
@@ -715,10 +854,10 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
errors.configs ?? errors.setup ?? error,
],
pollError: [
- (s) => [s.loadErrors, s.resultPollError],
- (errors: ScoutTrialLoadErrors, error: string | null): string | null =>
- errors.history ?? errors.comparisonHistory ?? error,
+ (s) => [s.loadErrors],
+ (errors: ScoutTrialLoadErrors): string | null => errors.history ?? errors.comparisonHistory,
],
+ refreshing: [(s) => [s.refreshingLaunchIds], (launchIds: string[]): boolean => launchIds.length > 0],
comparisonState: [
(s) => [s.selectedComparison, s.comparisonStates],
(
@@ -739,9 +878,20 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
},
],
comparisonsForConfig: [
- (s) => [s.comparisons, s.selectedConfigId],
- (comparisons: ScoutTrialComparison[], configId: string | null): ScoutTrialComparison[] =>
- comparisons.filter((comparison) => comparison.configId === configId).reverse(),
+ (s) => [s.comparisons, s.selectedConfigId, s.showArchived, s.comparisonStates],
+ (
+ comparisons: ScoutTrialComparison[],
+ configId: string | null,
+ showArchived: boolean,
+ states: Record<string, ScoutTrialComparisonState>
+ ): ScoutTrialComparison[] =>
+ comparisons
+ .filter(
+ (comparison) =>
+ comparison.configId === configId &&
+ (showArchived || !states[comparison.id]?.value?.archived)
+ )
+ .reverse(),
],
selectedComparison: [
(s) => [s.comparisonsForConfig, s.selectedComparisonIds, s.selectedConfigId],
@@ -826,6 +976,7 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
s.batch,
s.comparisonStates,
s.cancelErrors,
+ s.selectedComparison,
],
(
configId: string | null,
@@ -835,12 +986,14 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
errors: Record<string, string>,
batch: ScoutTrialBatch | null,
comparisonStates: Record<string, ScoutTrialComparisonState>,
- cancelErrors: Record<string, string>
+ cancelErrors: Record<string, string>,
+ selectedComparison: ScoutTrialComparison | null
): ScoutTrialRow[] => {
const relevantHistory = history?.results ?? []
const ids = [
...new Set([
...(batch?.submissions.map((entry) => entry.request.launch_id) ?? []),
+ ...(selectedComparison?.groups.flatMap((group) => group.launchIds) ?? []),
...relevantHistory.map((entry) => entry.launch_id),
...tracked
.filter((entry) => entry.configId === configId)
@@ -889,10 +1042,83 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
}),
listeners(({ actions, values, props, cache }) => ({
retryPageLoad: () => {
- if (values.loadErrors.setup && !values.loadErrors.configs && values.selectedConfigId) {
- actions.loadSetup(values.selectedConfigId)
- } else {
+ if (values.loadErrors.configs || !values.selectedConfigId) {
actions.loadConfigs()
+ return
+ }
+ if (values.loadErrors.setup) {
+ actions.loadSetup(values.selectedConfigId)
+ }
+ if (values.loadErrors.history) {
+ actions.loadHistory(values.selectedConfigId)
+ }
+ if (values.loadErrors.comparisonHistory) {
+ actions.loadComparisonHistory(values.selectedConfigId)
+ }
+ },
+ setShowArchived: () => {
+ if (values.selectedConfigId) {
+ actions.loadComparisonHistory(values.selectedConfigId)
+ }
+ },
+ nextComparisonHistoryPage: () => {
+ const cursor = values.comparisonHistory?.next_cursor
+ if (values.selectedConfigId && cursor && !values.comparisonHistoryLoading) {
+ actions.loadComparisonHistory(values.selectedConfigId, [...values.comparisonHistoryCursors, cursor])
+ }
+ },
+ previousComparisonHistoryPage: () => {
+ if (values.selectedConfigId && values.comparisonHistoryCursors.length && !values.comparisonHistoryLoading) {
+ actions.loadComparisonHistory(values.selectedConfigId, values.comparisonHistoryCursors.slice(0, -1))
+ }
+ },
+ archiveComparison: async ({ comparisonId, archived }) => {
+ const comparison = values.comparisons.find((item) => item.id === comparisonId)
+ const state = values.comparisonStates[comparisonId]
+ if (
+ !comparison ||
+ values.archiving.includes(comparisonId) ||
+ state?.loading ||
+ state?.resuming ||
+ !state?.value ||
+ (archived && !['completed', 'failed'].includes(state.value.status))
+ ) {
+ return
+ }
+ actions.setArchiving(comparisonId, true)
+ actions.setArchiveError(comparisonId, null)
+ const manager = cache.disposables
+ const context = getContext()
+ try {
+ const result = await signalsScoutConfigTrialComparisonArchive(
+ String(props.teamId),
+ comparison.configId,
+ { comparison_id: comparisonId, archived }
+ )
+ if (!manager.isDisposed && getContext() === context) {
+ actions.registerServerComparison(result)
+ if (archived && !values.showArchived) {
+ actions.untrackLaunches(comparison.groups.flatMap((group) => group.launchIds))
+ if (values.selectedComparisonIds[comparison.configId] === comparisonId) {
+ actions.showTrialList()
+ }
+ }
+ if (values.selectedConfigId === comparison.configId) {
+ actions.loadComparisonHistory(comparison.configId)
+ }
+ }
+ } catch (error) {
+ if (!manager.isDisposed && getContext() === context) {
+ actions.setArchiveError(
+ comparisonId,
+ readableErrorMessage(error) ||
+ `Couldn't ${archived ? 'archive' : 'restore'} this trial. Try again.`
+ )
+ }
+ } finally {
+ if (!manager.isDisposed && getContext() === context) {
+ actions.setArchiving(comparisonId, false)
+ }
}
},
registerServerComparison: ({ comparison }) => {
@@ -903,11 +1129,13 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
error: null,
notStarted: false,
})
- actions.trackLaunches(
- identifiers.groups.flatMap((group) =>
- group.launchIds.map((launchId) => ({ configId: identifiers.configId, launchId }))
+ if (!comparison.archived || values.showArchived) {
+ actions.trackLaunches(
+ identifiers.groups.flatMap((group) =>
+ group.launchIds.map((launchId) => ({ configId: identifiers.configId, launchId }))
+ )
)
- )
+ }
if (comparison.evaluation) {
actions.updateEvaluation(comparison.comparison_id, {
value: comparison.evaluation,
@@ -921,6 +1149,9 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
submissions: values.batch.submissions.map((entry) => ({ ...entry, accepted: true })),
})
}
+ if (values.trialView === 'detail' && values.selectedComparison?.id === comparison.comparison_id) {
+ actions.refreshResults()
+ }
},
loadComparisonHistorySuccess: ({ comparisonHistory }) => {
if (!comparisonHistory || !values.selectedConfigId) {
@@ -931,15 +1162,23 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
const current = values.comparisonStates[comparison.comparison_id]?.value
actions.registerServerComparison(
comparison.status === 'not_started' && current && current.status !== 'not_started'
- ? current
+ ? { ...current, archived: comparison.archived }
: comparison
)
}
+ const comparisonIds = comparisonHistory.results.map((comparison) => comparison.comparison_id)
+ const previousComparisons = values.comparisons
+ actions.reconcileComparisons(values.selectedConfigId, comparisonIds)
+ const keptIds = new Set(values.comparisons.map((comparison) => comparison.id))
+ const removedLaunchIds = previousComparisons
+ .filter((comparison) => comparison.configId === values.selectedConfigId && !keptIds.has(comparison.id))
+ .flatMap((comparison) => comparison.groups.flatMap((group) => group.launchIds))
+ actions.untrackLaunches(removedLaunchIds)
},
loadComparison: async ({ comparisonId }) => {
const comparison = values.comparisons.find((item) => item.id === comparisonId)
const state = values.comparisonStates[comparisonId]
- if (!comparison || state?.loading || state?.resuming) {
+ if (!comparison || state?.loading || state?.resuming || values.archiving.includes(comparisonId)) {
return
}
actions.updateComparisonState(comparisonId, { loading: true, error: null })
@@ -979,6 +1218,8 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
values.trialsDisabledReason ||
!comparison ||
!values.managedComparison ||
+ state.value?.archived ||
+ values.archiving.includes(comparison.id) ||
state.loading ||
state.resuming ||
values.submitting
@@ -1037,16 +1278,7 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
},
selectConfig: ({ configId }) => {
actions.loadSetup(configId)
- actions.loadHistory(configId)
actions.loadComparisonHistory(configId)
- if (values.selectedComparison) {
- if (values.managedComparison) {
- actions.loadComparison(values.selectedComparison.id)
- } else {
- actions.loadEvaluation(values.selectedComparison.id)
- }
- }
- actions.refreshResults()
},
selectComparison: ({ comparisonId }) => {
const comparison = values.comparisons.find((item) => item.id === comparisonId)
@@ -1226,6 +1458,14 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
actions.refreshResults()
}
},
+ selectResult: ({ launchId }) => {
+ if (launchId) {
+ actions.retryResult(launchId)
+ }
+ },
+ retryResult: ({ launchId }) => {
+ actions.loadResults([launchId])
+ },
addVariant: () => {
const baseline = values.variants[0]
if (baseline && values.variants.length < MAX_TRIAL_VARIANTS) {
@@ -1310,52 +1550,51 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
if (stillMounted()) {
actions.setSubmitting(false)
actions.refreshResults()
- actions.loadHistory(batch.configId)
actions.loadComparisonHistory(batch.configId)
}
}
},
- refreshResults: async ({ force }) => {
- if (cache.refreshing) {
- cache.refreshPending = true
- cache.refreshForce = cache.refreshForce || force
+ refreshResults: ({ force }) => {
+ if (values.trialView !== 'detail' || !values.selectedComparison) {
return
}
- cache.refreshPending = false
- cache.refreshForce = false
- if (!values.selectedConfigId) {
- return
- }
- const configId = values.selectedConfigId
- const pendingLaunchIds = new Set(
- Object.values(values.comparisonStates).flatMap((state) =>
- state.value && comparisonIsActive(state.value.status)
- ? state.value.variants.flatMap((variant) => variant.launch_ids)
- : []
- )
+ const comparison = values.selectedComparison
+ const active = !!values.comparisonState.value && comparisonIsActive(values.comparisonState.value.status)
+ const trackedIds = new Set(
+ values.tracked.filter((entry) => entry.configId === comparison.configId).map((entry) => entry.launchId)
)
- const entries = values.tracked.filter((entry) => {
- const result = values.results[entry.launchId]
- return (
- entry.configId === configId &&
- (force ||
- !result ||
- result.status === 'unknown' ||
- (result.status === 'not_started' && pendingLaunchIds.has(entry.launchId)) ||
- trialIsActive(result.status) ||
- trialTaskIsActive(result.task_status))
- )
- })
- if (!entries.length) {
+ const launchIds = comparison.groups
+ .flatMap((group) => group.launchIds)
+ .filter((launchId) => {
+ if (!trackedIds.has(launchId)) {
+ return false
+ }
+ const result = values.results[launchId]
+ return (
+ force ||
+ (!result && (!values.resultErrors[launchId] || active)) ||
+ (result &&
+ (trialIsActive(result.status) ||
+ trialTaskIsActive(result.task_status) ||
+ (active && ['unknown', 'not_started'].includes(result.status))))
+ )
+ })
+ actions.loadResults(launchIds)
+ },
+ loadResults: async ({ launchIds }) => {
+ const configId = values.selectedConfigId
+ const entries = [...new Set(launchIds)].filter((id) => !values.refreshingLaunchIds.includes(id))
+ if (!configId || !entries.length) {
return
}
- cache.refreshing = true
- actions.setRefreshing(true)
+ actions.setRefreshingLaunches(entries, true)
const manager = cache.disposables
const context = getContext()
- const concurrency = new ConcurrencyController(TRIAL_RESULT_POLL_CONCURRENCY)
+ const concurrency: ConcurrencyController =
+ cache.resultConcurrency ??
+ (cache.resultConcurrency = new ConcurrencyController(TRIAL_RESULT_POLL_CONCURRENCY))
const responses = await Promise.allSettled(
- entries.map((entry, index) =>
+ entries.map((launchId, index) =>
concurrency.run({
priority: index,
fn: async () => {
@@ -1367,13 +1606,12 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
return null
}
return signalsScoutConfigTrialResult(String(props.teamId), configId, {
- launch_id: entry.launchId,
+ launch_id: launchId,
})
},
})
)
)
- cache.refreshing = false
if (manager.isDisposed || getContext() !== context) {
return
}
@@ -1383,15 +1621,15 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
responses.forEach((response, index) => {
if (response.status === 'fulfilled') {
if (response.value) {
- results[entries[index].launchId] = response.value
+ results[entries[index]] = response.value
}
} else {
if (response.reason instanceof ApiError && response.reason.status === 404) {
- missingLaunchIds.push(entries[index].launchId)
+ missingLaunchIds.push(entries[index])
+ errors[entries[index]] = 'This run is no longer available.'
return
}
- errors[entries[index].launchId] =
- 'Status unavailable. Refresh to check whether this run was accepted.'
+ errors[entries[index]] = "Couldn't load this run. Retry to get its latest status."
}
})
// A saved server comparison or history can restore these IDs if the launch appears later.
@@ -1399,20 +1637,10 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
actions.untrackLaunches(missingLaunchIds)
}
actions.setResults(results, errors)
- actions.setRefreshing(false)
- if (values.selectedConfigId === configId) {
- actions.setPollError(
- Object.keys(errors).length
- ? 'Some run statuses could not be loaded. Existing results stay visible.'
- : null
- )
- }
- if (values.selectedConfigId !== configId || cache.refreshPending) {
- actions.refreshResults(cache.refreshForce)
- }
+ actions.setRefreshingLaunches(entries, false)
},
downloadResults: () => {
- const results = values.rows.flatMap((row) => {
+ const results = values.comparisonRows.flatMap((row) => {
const result = values.results[row.launchId]
return result ? [{ variant: row.variant, ...result }] : []
})
@@ -1441,7 +1669,7 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
} finally {
if (!manager.isDisposed && getContext() === context) {
actions.setCanceling(launchId, false)
- actions.refreshResults()
+ actions.retryResult(launchId)
}
}
},
@@ -1461,6 +1689,9 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
) {
actions.loadComparisonHistory(values.selectedConfigId)
}
+ if (values.trialView !== 'detail') {
+ return
+ }
const evaluation = values.evaluationState.value
const comparison = values.comparisonState
const managedActive = !!comparison.value && comparisonIsActive(comparison.value.status)
@@ -1483,18 +1714,11 @@ export const scoutTrialsLogic: LogicWrapper<scoutTrialsLogicType> = kea<scoutTri
}
if (
managedActive ||
- values.rows.some(
- (row) =>
- trialIsActive(row.status) ||
- (row.status === 'unknown' &&
- values.tracked.some((entry) => entry.launchId === row.launchId)) ||
- trialTaskIsActive(row.result?.task_status)
+ values.comparisonRows.some(
+ (row) => trialIsActive(row.status) || trialTaskIsActive(row.result?.task_status)
)
) {
actions.refreshResults()
- if (values.selectedConfigId && !values.historyLoading) {
- actions.loadHistory(values.selectedConfigId)
- }
}
}, TRIAL_POLL_INTERVAL_MS)
return () => window.clearInterval(poll)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 709360a76fad..194392963d55 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -98296,6 +98296,8 @@ export namespace Schemas {
* * `failed` - failed
* * `unknown` - unknown */
status: ScoutTrialComparisonStatusEnum;
+ /** Whether this finished trial is hidden from the default history. */
+ archived: boolean;
/**
* Sanitized comparison error, if any.
* @nullable
@@ -98305,11 +98307,23 @@ export namespace Schemas {
evaluation: ScoutTrialEvaluation | null;
}
+ export interface ScoutTrialComparisonArchiveRequest {
+ /** Saved comparison identity. */
+ comparison_id: string;
+ /** Hide a finished trial from history, or restore it without rerunning it. */
+ archived: boolean;
+ }
+
export interface ScoutTrialComparisonHistory {
/** This operator's most recent saved comparisons. */
results: ScoutTrialComparison[];
/** Whether more comparisons exist than the requested limit. */
has_more: boolean;
+ /**
+ * Cursor for the next page, or null on the last page.
+ * @nullable
+ */
+ next_cursor: string | null;
}
export interface ScoutTrialComparisonQuery {
@@ -126648,6 +126662,16 @@ export namespace Schemas {
};
export type SignalsScoutConfigTrialComparisonHistoryParams = {
+ /**
+ * Cursor returned by the previous history page. Omit to read the newest trials.
+ * @minLength 1
+ * @pattern ^[0-9]{19}-[0-9a-f-]{36}\.json$
+ */
+ cursor?: string;
+ /**
+ * Include archived trials in the history.
+ */
+ include_archived?: boolean;
/**
* Maximum number of recent private runs to return.
* @minimum 1