Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(aio): separate the trace view from the trace page (#127705)

Carlos Marchalcf5a6ac71ffc
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 867a8a706384..f31545b06a97 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9791,29 +9791,29 @@ snapshots:
scenes-app-ai-observability-trace-view-trace-clusters-chip--outlier-only--light:
hash: v1.k794b7964.7fb34c00afcd35d9ee68f4b715bc558966d3a25d95bd0b89370f1b47d61c0fe4.OMnpT-y_Me0S92srt0iYGNFFvnczxucni9d4GiK01rY
scenes-app-ai-observability-trace-view-trace-header--default--dark:
- hash: v1.k794b7964.89f74988daa805a5decedf40f47256dc0776cf10499f7927bccec49753e659b8.BAtU5Cxiu3j-JRB9Z_iy032Q7TVs-L0M01FCCizn3n0
+ hash: v1.k794b7964.c147a391dd794e7b389702ed9e6c7a738ef2189ef54ea975d625a82b1e64991a.sfix7RSizlqNdH_bCbsR3ZiZnDVO7y_hW2YcVO41gRM
scenes-app-ai-observability-trace-view-trace-header--default--light:
- hash: v1.k794b7964.f3720db8274ecdff7dfbd9cf3169b84b0a949c3b4231c009dabd014d116b46e1.lbPNx31DLkeINRl7ge6N1JDf_qtiHu7snOXRZvpMfH8
+ hash: v1.k794b7964.1c571a7699e28280840a4a17b987f1c37c2eb86c7e958a0aaf4ba3528a482797.XZF2o7dGrkLpmsUjuczQTDjBG_QdQwZthA6Tq-m62co
scenes-app-ai-observability-trace-view-trace-header--errored--dark:
- hash: v1.k794b7964.be74b48b9dd1bc8dc63725b475cc6de8133e6ec3a8e99a26c40e3bb7a1847c9b.KLWPm-WdZjT7u4J7EETQRamQieR3a-RxxMCWo_cl1ps
+ hash: v1.k794b7964.158763e282799781d90cc5fdc50c2ff9b024ff520d104814824c619c9985037b.AFIxKHX6N3qwl29b1z3-PkK9587pjIP_k-q0QKMkQKM
scenes-app-ai-observability-trace-view-trace-header--errored--light:
- hash: v1.k794b7964.231b1a427d9e84ee1c8d77025a0369227a80ba33006fd72d8066efc86caddcaf.23SGisFFQgEXte1lfQB7ZpNH7WjAvH1CleqGu7hxGXQ
+ hash: v1.k794b7964.d5f529b017815acb1ebb9574f158ba7f125210f01a492ec0e1c1793d3d552218.C3M8ObMcwOFWzDFvX1hkAWjday-8dCOdkxLJU4AtDHc
scenes-app-ai-observability-trace-view-trace-header--export-in-progress--dark:
- hash: v1.k794b7964.efdf0242122a7640787ccc32dea5d3eb18a285a64564863e3014507d9c6afe88.9UDr6dhnk6vvdVquH9F8Edyqi9VYcR-efLxL4q0DJls
+ hash: v1.k794b7964.57c93cae2eef4eee189f48880adc2b22b1c1a3b88dadd4a0ac07a1d0a6526cf3.UptFxwVnwWfGrxl5_1vOFsZz9tgWPUuSb8_evEdSjh0
scenes-app-ai-observability-trace-view-trace-header--export-in-progress--light:
- hash: v1.k794b7964.fab26bb7450c4f15793c92fb26e837d57d7d3ffb692357870b14623f912454a7.y5_Fe2kmCx087B2ZDBxxw5irnIFWj-nyvmnsbSAycVU
+ hash: v1.k794b7964.f40e96fc673c00ea5224003a9c29fdcee8ff7db093387dd9fbee0346e90d474d.n9vOY-54g3oEWRmYP3K51gbjx1-OGDs8Ra06-tAI3og
scenes-app-ai-observability-trace-view-trace-header--narrow--dark:
- hash: v1.k794b7964.15b07befce84c1e640f043985ed7100796cca9568dc2f0c743e5a44ff4f0ef8a.olwGhKEQ2CIA95Tue208-OL5Cwm-x8CIwAI8QlBWMzs
+ hash: v1.k794b7964.ea52b401ffc33beb9f082516bf764a2731bd65284027cb5cef1b9ee04157b39a.LsqLoMh2PKAYes9ihiMfV1RsqVRHgZMxSbw5S3JT-9s
scenes-app-ai-observability-trace-view-trace-header--narrow--light:
- hash: v1.k794b7964.cb8d46a7f55c0856582a1311b0e8c64adef666ac44869e5237f174ac4d6aa45a.GLFGItfsLLj9-QKMZsTX6s_I85fIsYIn8kQMNcIYbMc
+ hash: v1.k794b7964.6bc90881d4596b3c892811a66f67c395f86799caf26f327dfe2a44945085cbb7.Edb7kJq3DRne4_k7BrkP_BrCettDLuCURrJGSZDBPLg
scenes-app-ai-observability-trace-view-trace-header--with-export--dark:
- hash: v1.k794b7964.36bc76078cc9b7c8ede2871815fd443b8ff0f6248d4e9a15c1dd92949c10b3ed.Z9IN5h7wCNsvU-DtunWxueiEY6KpNXXbgHsUGnM1FQ4
+ hash: v1.k794b7964.412edd0fd0487ad65c586eef9982a8df72ae5ba4a8cd5d699b140c5aeeb1d9b5.A-Yowqo_MogMzkgjQNPJcW_nVeucgwEGTIy515lBuk8
scenes-app-ai-observability-trace-view-trace-header--with-export--light:
- hash: v1.k794b7964.9770434c61f3d1e6b2d2b5aa0f88abca9cb3ba0eb5166c4eb093b69d53bbe2f2.LWvtcqnui_ROvD-O4xvyuSYhlB5Oek5y1uX9qs7_hrE
+ hash: v1.k794b7964.d5d608523adc04cd94b2b6127564adede8b7a27ba93ed629a91a351c12415797.DcYDxy5gkejL1ri_qZMc5sqJoU2rsmSst9SwodqdItU
scenes-app-ai-observability-trace-view-trace-header--with-search--dark:
- hash: v1.k794b7964.aa0454ec525f326773af3ab8881a60f981feedb06714be27b9b44a594e0fdf42.84mnlZI9H7SWkfSDjNvp-sAYDTdT7lY2vi8RNNJFEXg
+ hash: v1.k794b7964.bb8b7faaef569161d5b2788f30aa0727ec872283ed6a03fa5d0ce5bf0eb0eb06.APtzVe9PIqbFv-svcGxEKA1LXDeduuxpObWKAVW0tho
scenes-app-ai-observability-trace-view-trace-header--with-search--light:
- hash: v1.k794b7964.6aa55cf290ef829c19219427567d7beac78cf49270e189658db3a429567bbe41.qs3xFQxD-qunCuupDH25kZaQ9FbU8XRGtdeGjGULYyg
+ hash: v1.k794b7964.f52ffb4ec43d3a8f03e6182c7a8edc5e45db0ff42a13464b63f0d951635553a9.H6gSB6cfOm9KR5-6USwbJSlE-gEySVYc0-J41CZnpKY
scenes-app-ai-observability-trace-view-trace-mode-tabs--default--dark:
hash: v1.k794b7964.438ee912f36d4f19ccec0b12f645b823068e4a5103daef99effe519602b07c07.757Ls8z7uxMrtEqvXV0u69Mo0onygkWWCfZvys0zLw0
scenes-app-ai-observability-trace-view-trace-mode-tabs--default--light:
@@ -9959,17 +9959,17 @@ snapshots:
scenes-app-ai-observability-trace-view-trace-tree--with-search-matches--light:
hash: v1.k794b7964.8371437af66a899465e8b6af209192d8faf8908b085b3ac845c286fdd571a1c0.-QUndAyEEy3bilMOkmUg1mKqV2a9wXYtwqUv6lq-zMc
scenes-app-ai-observability-trace-view-trace-view--error-trace--dark:
- hash: v1.k794b7964.a7a017f670fee5a7a317358423030502d723c5007e4d21269b3a770ad2c41d98.asJhLo955-GX6O0pOjoZa2fe6hmagfvftM6Zg1hyPs0
+ hash: v1.k794b7964.7085c7f7bd764554d0489f7230d4820206118611d1465728b7755b0f8e2683d1._7qbxWnsgMZ_ZQ8zzgw0UOspO_fFlB6pS-tZXRotPt4
scenes-app-ai-observability-trace-view-trace-view--error-trace--light:
- hash: v1.k794b7964.e270fb50d9b25527217554014b199492777859542b04a8d042a84af8bb4f1af9.d7X6D7Ca5PURuOGuUKYZRqdTDLWoWieWf7PZatmx8mM
+ hash: v1.k794b7964.1b21679eff548b599eb2dea532ea2b690c4b7f9992d8dd71a4e2f618f49974c9.1o-nlOKjZhVJHdS-d9UqTP51HA7OcgbUlkadg8s06EU
scenes-app-ai-observability-trace-view-trace-view--feedback-mode--dark:
- hash: v1.k794b7964.bb41fbe5af1874cab474d95cbd6e482dcc409f33a4d242c35067b274f8b1e825.moBcWoLtmtLN7cxIP6kBIFLNC-xJh7jcx_oRZiadn-Q
+ hash: v1.k794b7964.f0f8abade6242178a102106e1ff1beb32e1245ad5d6282a4bd5a35abfa97212f.aCTxPd846zEcV61n-alopbaqQ8P0E4If_r7DLaXWYA8
scenes-app-ai-observability-trace-view-trace-view--feedback-mode--light:
- hash: v1.k794b7964.b746663160e505d2795ed3b5fed2a156b66ac7fa0dc1298d68d5b9db217d2bf1.bj--bzmipGXl1BVlQAdKzqy1wnR2jyKUSHwpB8qJrL0
+ hash: v1.k794b7964.c925b0ebfcbb3da6332350bb47fa803e840a3031f94b8cf3b7abe54001a1fd70.pnt2DBUbAt513gy6lz0MDRd4U8crb7uzj392lDPbaI4
scenes-app-ai-observability-trace-view-trace-view--generation-selected--dark:
- hash: v1.k794b7964.2b838c9c5d74d37d53a38bc014fe11cda3f30c81a9f17ef606ad611559adbf47.qdaDN1liUiB-RAhjDxtSF6O_D14dZ5rXPm8HZ_znxe0
+ hash: v1.k794b7964.bae531b1be9da9f5dfb662955e73095ae96716ad166795e671f16408cfdfa24d.iRrceUDV3xYj9RwrBCgkz6s3UgcjB1oOdJb8ncy-P8E
scenes-app-ai-observability-trace-view-trace-view--generation-selected--light:
- hash: v1.k794b7964.98f2a3cd0f6222c771537a759a42def9863b9ef8d73fe23ec001f51a2ba802a7.8SlzXtnh-4JF3o7LK6MCNnqVMpuopxcWvHFql9K3fDQ
+ hash: v1.k794b7964.dd2cba6d414bdb3bfc61f3515871cb83c3cc9afd01b1d387b77195eebcc8134a.-ZL-40uvP_v5zFegNnOLCJw2rfoXHHbJrMMm8OxCMYc
scenes-app-ai-observability-trace-view-trace-view--load-error--dark:
hash: v1.k794b7964.c4e963947f61276470d35e280b1b69130365cde0f3153efba7bfbab805e496de.B2FhLvOWBsI-x3axjIDbfrTFGaYKLtFR32l7sn4SCfI
scenes-app-ai-observability-trace-view-trace-view--load-error--light:
@@ -9979,17 +9979,17 @@ snapshots:
scenes-app-ai-observability-trace-view-trace-view--loading--light:
hash: v1.k794b7964.1f54d609e54318c9e0f9f1899ee8ca7bf4b0a15097de855b21c6d27806fb0025.gnPyfTsQdjTlj7UtrOYn-fH_b-Z--AipIH1rgB9In_0
scenes-app-ai-observability-trace-view-trace-view--narrow--dark:
- hash: v1.k794b7964.0bdfbd16ff5058a5cb5e6e7cb5fb24c60d98bc7d1da087c8f0e5a6657e332f68.kQOfyJ9W0ommwX4utpmmw9VJuy-rG1xIkpLuvguWqaU
+ hash: v1.k794b7964.801f111cd35a020c086c3982d3b6e403cff4de19b0fcbae2890c180f4c82397c.zU-YYPUGzkW4ux-1kwS0tqB0r51Tjccd52ZDQfjfvFA
scenes-app-ai-observability-trace-view-trace-view--narrow--light:
- hash: v1.k794b7964.a4c03d19df8e5a72720a1f57f8c91535316408ecf84efacb98014211ad4ec0aa.A62LUD6CSYHsJMZ6HdQtL3JlP9iwdCWDxKdO7iEvyJk
+ hash: v1.k794b7964.4056324a3875075c5f2b8f24545adfcb3101e1bfbae33038d01db1b7a977e469.EZ_OB-orxz36DKcj4ENVcKptjXoW682WdmUdiEzHCwo
scenes-app-ai-observability-trace-view-trace-view--narrow-with-evals--dark:
- hash: v1.k794b7964.7747245cf10534fe286eedc8ae887974259f2590424d27b641c992bf2019f8b8.p7-8vtKWvsVWw3MtrmL7XlTm2XQKn5C36b_aXDnb__w
+ hash: v1.k794b7964.e5cb56730db786da8c7e5754b9750c98e49245b6df039d4c4437e46c2761fb38.UIy_T1r79C6gxovu4a9wPfzhX_MA_mUfeManOd3Fxd8
scenes-app-ai-observability-trace-view-trace-view--narrow-with-evals--light:
- hash: v1.k794b7964.deed35be58a19c835f77779ff3dd3a7b4377db16f08c34f5b98d8c991e81daa6.8SNGKdqWOS_EJ_cTk2P0uV27XuApGA2ytDMRv5xF1bo
+ hash: v1.k794b7964.0530822f7f324be82e6d20dd8e83593df0711024c97435a3fe0b02fece25923d.YCzyVwrI7LMYPYMIgvGLDf1ICnJ29rUg_X0jgf0R8AE
scenes-app-ai-observability-trace-view-trace-view--narrow-with-search--dark:
- hash: v1.k794b7964.1a9ad3c396cd4cd85e2ccf9414ca097d584d24ab3a0c9e424b359a477b52fbd7.ECvtkMxbgMzC6EhPYXiGy3hPuWtqBJDW7quriUElzRM
+ hash: v1.k794b7964.252600a05962ea926448b04eb9fc4b1a432c531fd88f3254b41b145d88f7ab3d.Ng7Br730lmymLy7a-GEPlmrRiWhuHIhDCpi809MysQw
scenes-app-ai-observability-trace-view-trace-view--narrow-with-search--light:
- hash: v1.k794b7964.335a89fc73ced2da70b9f367314ed5a04c44600c210afee3be5598680aea7f3b.5RcI8Up5p2NaMVeQOEe9B6u7A2XWjPxw12qeIfMjCfk
+ hash: v1.k794b7964.2778ab294ce6a667d188f092a9b3915b14dc504086f2b12159040d5e28d29023.9Ck0DKzlj72tvhiq9KvZ2jQbj14Op9fZyPH7bVvA-tk
scenes-app-ai-observability-trace-view-trace-view--sample-anthropic-thinking-tool-use--dark:
hash: v1.k794b7964.ee72ae95c2c0db21361b7924fb3f7db28af93dae0f3773ad4530f847f95fc20c.1m0893IlRbuhUW5V-caBPubusOcO8QdDfOSfYt_iA5k
scenes-app-ai-observability-trace-view-trace-view--sample-anthropic-thinking-tool-use--light:
@@ -10007,17 +10007,17 @@ snapshots:
scenes-app-ai-observability-trace-view-trace-view--sample-open-ai-agents-with-evals--light:
hash: v1.k794b7964.0defbf16466852328781c98a0b1bad727292512e3d6ef94a34ef89a7cc7af7c8.YxnGetMJ8rP0TaFE_BGBDK33bYPoEi7QBgsYACaJnRs
scenes-app-ai-observability-trace-view-trace-view--span-selected--dark:
- hash: v1.k794b7964.2eda684b13b77907811e478364247d42f405f1a3a5a5b8b0c885da4a26ec2c8c.Y29Dsf8fflTBD9WKMRfcHJv2iIIw_tDadCpigb08wCg
+ hash: v1.k794b7964.5661cb373b0a885e9fcae9aae48e1a2f2e4c1878e978d479eb21c2afa4c56b33.MRr4zuk2ZEYYgCjUapLRG4_yvUduKdK4-jxb3OwL-CM
scenes-app-ai-observability-trace-view-trace-view--span-selected--light:
- hash: v1.k794b7964.5cb050703adb3429d626b8c13791afbc37d0c597ecc5e437413ebf1ba3c26d48.AAk8JpRWDqzxJ0P1qRHQ4uXpoin-1GpUkH3jOuFwGQw
+ hash: v1.k794b7964.cce518d901220cf3987ffecc01a12863a52ebcfbbc85a7e57c66412269e5ecd4.BDrwhtzMs2xy21QD2YQhRspMwVDx0it-wBv_v8X_BwY
scenes-app-ai-observability-trace-view-trace-view--thread-mode--dark:
- hash: v1.k794b7964.c06a09c1a192d8997436eeb67ed5e9b8e096c6e50ebd5586adf753169d6773da.3WbhibXmzj1h1EhUMK9HT-RXjaoKuMiMnvpBNnO4HaU
+ hash: v1.k794b7964.a67a33e56d46e1cce8d4e8f8c1acdbce48cb95aef40a3565bf00cec07285df2d.TTwODTDJcqX0WWEM23lHDrYrwt3mc11OczHUbTDGW_o
scenes-app-ai-observability-trace-view-trace-view--thread-mode--light:
- hash: v1.k794b7964.29eaac860520162781edf45dd9e837eff72d0ad9c06f09dbe8324cb933dcc0f5.E1YiXFqcbzLehe0E6kRY50oYceH0z4xrefFgJfUTZ6E
+ hash: v1.k794b7964.7e7b6476eebb5463219b494da41ce168004b0195ff5740ba96331b4c39b2cfc2.8PFv02RIXoQVHtiuL0q-q4dP4F3g7-wIeI02zBMG86I
scenes-app-ai-observability-trace-view-trace-view--timeline-mode--dark:
- hash: v1.k794b7964.0f5cb624ec3c0c87561188fde23b2c9122baef519a827c8ba67af101028357c6.nBIRz6Sa8jFZHNY3rpINjOsVEzlMpx_dOVk7L3vDzUQ
+ hash: v1.k794b7964.257916db753723724422e8e079f222b696e115fa68d5af3299ecabad144a6b2b.tHk4yi8qag5eR66lnJKE1IC8sjCTjMNq5qAmCsTfcyY
scenes-app-ai-observability-trace-view-trace-view--timeline-mode--light:
- hash: v1.k794b7964.f32260b02fe481ec1e82b0bea5c59409638d650a38d0294ba6b9a500343bdd4f.Gjx8RyUGipWJc6o34aYnvTY4Tg0RZMPRrWWHXlKbcMU
+ hash: v1.k794b7964.d75461acbb67383146529c1f9cac861fb7be369d2c551e445611aadbf8db8e70.ZBRYpdhZNMGd22yuvV8JqVPJYQXKgZz5TLSlM5-VTqQ
scenes-app-ai-observability-trace-view-trace-view-switch--on-new-view--dark:
hash: v1.k794b7964.705e0647746424a98de2bbf79737ac43b3f60b57ae45b8f0e5d0cb5f01226aad.vSallcE6n-MHVAkWEOsfs2D1X--pp40NBjawl5otiOk
scenes-app-ai-observability-trace-view-trace-view-switch--on-new-view--light:
diff --git a/products/ai_observability/frontend/aiObservabilityTraceLogic.test.ts b/products/ai_observability/frontend/aiObservabilityTraceLogic.test.ts
index b85da87ade92..5bef1cc2dec4 100644
--- a/products/ai_observability/frontend/aiObservabilityTraceLogic.test.ts
+++ b/products/ai_observability/frontend/aiObservabilityTraceLogic.test.ts
@@ -12,6 +12,7 @@ import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { DisplayOption, TraceViewMode, aiObservabilityTraceLogic } from './aiObservabilityTraceLogic'
+import { traceViewPreferenceLogic } from './redesign/trace/traceViewPreferenceLogic'
const blankScene = (): any => ({ scene: { component: () => null, logic: null } })
const scenes: any = { AIObservabilityTrace: blankScene }
@@ -80,6 +81,23 @@ describe('aiObservabilityTraceLogic', () => {
expect(router.values.searchParams.filters).toEqual(filters)
})
+ it('carries the step selected on the timeline to the new view', async () => {
+ const preferenceLogic = traceViewPreferenceLogic()
+ preferenceLogic.mount()
+ const traceUrl = combineUrl(urls.aiObservabilityTrace('trace-1', { event: 'stale-step' }), {
+ back_to: 'traces',
+ })
+ router.actions.push(addProjectIdIfMissing(traceUrl.url, MOCK_TEAM_ID))
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setEventId('timeline-step')
+ preferenceLogic.actions.switchView('new')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.searchParams).toMatchObject({ event: 'timeline-step', back_to: 'traces' })
+ expect(logic.values.eventId).toBe('timeline-step')
+ })
+
it('handles trace ID with event and timestamp parameters', async () => {
const traceIdWithColon = 'session-summary:group:16-16:81008d53ff0a708b:da6c0390-409f-485c-aab3-5e910bcf8b33'
const eventId = 'event123'
diff --git a/products/ai_observability/frontend/aiObservabilityTraceLogic.ts b/products/ai_observability/frontend/aiObservabilityTraceLogic.ts
index 575cec5e89ec..cec72eed0b3c 100644
--- a/products/ai_observability/frontend/aiObservabilityTraceLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilityTraceLogic.ts
@@ -35,6 +35,7 @@ import type { BranchPRMatchApi } from 'products/engineering_analytics/frontend/g
import type { FeatureFlagsSet } from '../../../frontend/src/lib/logic/featureFlagLogic'
import { aiObservabilitySharedLogic } from './aiObservabilitySharedLogic'
import { buildAiObservabilityStorageConfig } from './preferenceStorage'
+import { traceViewPreferenceLogic } from './redesign/trace/traceViewPreferenceLogic'
export enum DisplayOption {
ExpandAll = 'expand_all',
@@ -171,6 +172,9 @@ export interface aiObservabilityTraceLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiObservabilityTraceLogicActions {
+ switchView: (view: import('./redesign/trace/types').TraceViewChoice) => {
+ view: import('./redesign/trace/types').TraceViewChoice
+ } // traceViewPreferenceLogic
applySearchResults: (
inputMatches: boolean[],
outputMatches: boolean[]
@@ -379,6 +383,7 @@ export const aiObservabilityTraceLogic = kea<aiObservabilityTraceLogicType>([
aiObservabilitySharedLogic,
['dateFilter', 'propertyFilters', 'shouldFilterTestAccounts', 'shouldFilterSupportTraces'],
],
+ actions: [traceViewPreferenceLogic, ['switchView']],
})),
actions({
@@ -838,6 +843,14 @@ export const aiObservabilityTraceLogic = kea<aiObservabilityTraceLogicType>([
url.searchParams.set('line', lineNumber.toString())
copyToClipboard(url.toString(), 'permalink')
},
+ switchView: ({ view }) => {
+ // The timeline selects a step without writing the URL, and the new view reads its step from the URL.
+ const { eventId } = values
+ const { pathname, searchParams, hashParams } = router.values.currentLocation
+ if (view === 'new' && eventId && searchParams.event !== eventId) {
+ router.actions.replace(pathname, { ...searchParams, event: eventId }, hashParams)
+ }
+ },
})),
subscriptions(({ actions, values }) => ({
diff --git a/products/ai_observability/frontend/redesign/trace/TraceScene.tsx b/products/ai_observability/frontend/redesign/trace/TraceScene.tsx
index b2f5c4594d6d..c0a4e91570fd 100644
--- a/products/ai_observability/frontend/redesign/trace/TraceScene.tsx
+++ b/products/ai_observability/frontend/redesign/trace/TraceScene.tsx
@@ -1,213 +1,19 @@
-import { useActions, useValues } from 'kea'
+import { useValues } from 'kea'
-import { aiObservabilityTraceLogic } from '../../aiObservabilityTraceLogic'
-import { SaveToDatasetButton } from '../../datasets/SaveToDatasetButton'
-import { traceViewAdapterLogic, traceViewAdapterLogicValues } from './adapter/traceViewAdapterLogic'
-import { TraceView, TraceViewProps, TraceViewReadyProps } from './components/TraceView'
-import { traceExportLogic } from './traceExportLogic'
-import { FeedbackEntry, MatchDirection, NodeDetailTab, SummaryItemKind, TraceMode } from './types'
+import { TraceViewContainer } from './adapter/TraceViewContainer'
+import { TRACE_PAGE_HOST_ID, tracePageLogic } from './tracePageLogic'
-type ReadyValues = Pick<
- traceViewAdapterLogicValues,
- | 'header'
- | 'summary'
- | 'clustersChip'
- | 'mode'
- | 'tree'
- | 'selectedNodeId'
- | 'detailData'
- | 'detailTab'
- | 'datasetItemSource'
- | 'canViewInThread'
- | 'thread'
- | 'timeline'
- | 'evalsChip'
- | 'evalOutcomesByNode'
- | 'gitBranch'
- | 'searchBox'
- | 'matchingNodeIds'
- | 'highlightQuery'
- | 'matchStepCount'
- | 'summaryState'
- | 'summaryRequesting'
- | 'summaryRequestError'
- | 'summaryConsentGiven'
- | 'feedbackChip'
- | 'feedbackCount'
- | 'feedbackCountByNodeId'
- | 'feedbackMode'
- | 'selectedStepFeedback'
-> & { traceExportLoading: boolean }
-
-interface ReadyActions {
- setMode: (mode: TraceMode) => void
- selectNode: (id: string) => void
- selectAndShowSpans: (id: string) => void
- setDetailTab: (tab: NodeDetailTab) => void
- viewInThread: () => void
- prefetchNode: (id: string) => void
- exportTrace: () => void
- showFailingEvals: () => void
- setQuery: (query: string) => void
- stepMatch: (direction: MatchDirection) => void
- summarize: () => void
- regenerateSummary: () => void
- loadSummary: () => void
- summaryStepClicked: (nodeId: string, kind: SummaryItemKind) => void
- showFeedback: (nodeId: string | null, entry: FeedbackEntry) => void
- retryTraceFeedback: () => void
-}
-
-function toReadyProps(values: ReadyValues, actions: ReadyActions): TraceViewReadyProps | null {
- if (!values.summary) {
+export function TraceScene(): JSX.Element | null {
+ const { traceId, timestampHint, backLink } = useValues(tracePageLogic)
+ if (!traceId) {
return null
}
- return {
- header: {
- ...values.header,
- exportAction: { loading: values.traceExportLoading, onExport: actions.exportTrace },
- },
- summary: {
- ...values.summary,
- clusters: values.clustersChip,
- evals: values.evalsChip ? { chip: values.evalsChip, onClick: actions.showFailingEvals } : null,
- feedback: values.feedbackChip
- ? { chip: values.feedbackChip, onClick: () => actions.showFeedback(null, 'chip') }
- : null,
- git: values.gitBranch,
- },
- mode: values.mode,
- onModeChange: actions.setMode,
- tree: values.tree,
- selectedNodeId: values.selectedNodeId,
- onSelectNode: actions.selectNode,
- onPrefetchNode: actions.prefetchNode,
- onSelectFromView: actions.selectAndShowSpans,
- detail: values.detailData
- ? {
- ...values.detailData,
- tab: values.detailTab,
- onTabChange: actions.setDetailTab,
- onViewInThread: values.canViewInThread ? actions.viewInThread : null,
- actions: values.datasetItemSource ? <SaveToDatasetButton {...values.datasetItemSource} /> : null,
- stepFeedback: values.selectedStepFeedback
- ? {
- feedback: values.selectedStepFeedback,
- onOpen: () => actions.showFeedback(values.selectedNodeId, 'step'),
- }
- : null,
- }
- : null,
- thread: values.thread,
- timeline: values.timeline,
- evalOutcomes: values.evalOutcomesByNode,
- search: { ...values.searchBox, onQueryChange: actions.setQuery, onStep: actions.stepMatch },
- matchingNodeIds: values.matchingNodeIds,
- highlightQuery: values.highlightQuery,
- matchStepCount: values.matchStepCount,
- summaryMode: {
- state: values.summaryState,
- requesting: values.summaryRequesting,
- requestError: values.summaryRequestError,
- consentGiven: values.summaryConsentGiven,
- onRequest: actions.summarize,
- onRegenerate: actions.regenerateSummary,
- onReload: actions.loadSummary,
- onSelectStep: actions.summaryStepClicked,
- },
- feedbackMode: values.feedbackMode,
- onRetryFeedback: actions.retryTraceFeedback,
- feedbackCount: values.feedbackCount,
- feedbackCountByNodeId: values.feedbackCountByNodeId,
- }
-}
-
-export function TraceScene(): JSX.Element {
- const { traceId, dateRange } = useValues(aiObservabilityTraceLogic)
- const logicProps = { traceId, timestampHint: dateRange?.dateFrom ?? null }
- const logic = traceViewAdapterLogic(logicProps)
- // Every kea value getter is a hook, so read them all on every render, whatever the status.
- const {
- status,
- errorMessage,
- backLink,
- header,
- summary,
- clustersChip,
- mode,
- tree,
- selectedNodeId,
- detailData,
- detailTab,
- datasetItemSource,
- canViewInThread,
- thread,
- timeline,
- evalsChip,
- evalOutcomesByNode,
- gitBranch,
- searchBox,
- matchingNodeIds,
- highlightQuery,
- matchStepCount,
- summaryState,
- summaryRequesting,
- summaryRequestError,
- summaryConsentGiven,
- feedbackChip,
- feedbackCount,
- feedbackCountByNodeId,
- feedbackMode,
- selectedStepFeedback,
- } = useValues(logic)
- const actions = useActions(logic)
- const exportLogic = traceExportLogic(logicProps)
- const { traceExportLoading } = useValues(exportLogic)
- const { exportTrace } = useActions(exportLogic)
-
- const readyProps =
- status === 'ready'
- ? toReadyProps(
- {
- header,
- summary,
- clustersChip,
- mode,
- tree,
- selectedNodeId,
- detailData,
- detailTab,
- datasetItemSource,
- canViewInThread,
- thread,
- timeline,
- evalsChip,
- evalOutcomesByNode,
- gitBranch,
- searchBox,
- matchingNodeIds,
- highlightQuery,
- matchStepCount,
- summaryState,
- summaryRequesting,
- summaryRequestError,
- summaryConsentGiven,
- feedbackChip,
- feedbackCount,
- feedbackCountByNodeId,
- feedbackMode,
- selectedStepFeedback,
- traceExportLoading,
- },
- { ...actions, exportTrace }
- )
- : null
-
- const props: TraceViewProps = readyProps
- ? { status: 'ready', ...readyProps }
- : status === 'error'
- ? { status: 'error', errorMessage, backLink }
- : { status: 'loading' }
-
- return <TraceView {...props} />
+ return (
+ <TraceViewContainer
+ hostId={TRACE_PAGE_HOST_ID}
+ traceId={traceId}
+ timestampHint={timestampHint}
+ backLink={backLink}
+ />
+ )
}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/TraceViewContainer.tsx b/products/ai_observability/frontend/redesign/trace/adapter/TraceViewContainer.tsx
new file mode 100644
index 000000000000..fcb4443089fb
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/TraceViewContainer.tsx
@@ -0,0 +1,218 @@
+import { useActions, useValues } from 'kea'
+
+import { SaveToDatasetButton } from '../../../datasets/SaveToDatasetButton'
+import { TraceView, TraceViewProps, TraceViewReadyProps } from '../components/TraceView'
+import { traceExportLogic } from '../traceExportLogic'
+import { traceViewModelLogic, traceViewModelLogicValues } from '../traceViewModelLogic'
+import { FeedbackEntry, LabeledLink, MatchDirection, NodeDetailTab, SummaryItemKind, TraceMode } from '../types'
+
+export interface TraceViewContainerProps {
+ hostId: string
+ traceId: string
+ timestampHint: string | null
+ backLink: LabeledLink | null
+}
+
+type ReadyValues = Pick<
+ traceViewModelLogicValues,
+ | 'header'
+ | 'summary'
+ | 'clustersChip'
+ | 'mode'
+ | 'tree'
+ | 'selectedNodeId'
+ | 'detailData'
+ | 'detailTab'
+ | 'datasetItemSource'
+ | 'canViewInThread'
+ | 'thread'
+ | 'timeline'
+ | 'evalsChip'
+ | 'evalOutcomesByNode'
+ | 'gitBranch'
+ | 'searchBox'
+ | 'matchingNodeIds'
+ | 'highlightQuery'
+ | 'matchStepCount'
+ | 'summaryState'
+ | 'summaryRequesting'
+ | 'summaryRequestError'
+ | 'summaryConsentGiven'
+ | 'feedbackChip'
+ | 'feedbackCount'
+ | 'feedbackCountByNodeId'
+ | 'feedbackMode'
+ | 'selectedStepFeedback'
+> & { traceExportLoading: boolean; backLink: LabeledLink | null }
+
+interface ReadyActions {
+ setMode: (mode: TraceMode) => void
+ selectNode: (id: string) => void
+ selectAndShowSpans: (id: string) => void
+ setDetailTab: (tab: NodeDetailTab) => void
+ viewInThread: () => void
+ prefetchNode: (id: string) => void
+ exportTrace: () => void
+ showFailingEvals: () => void
+ setQuery: (query: string) => void
+ stepMatch: (direction: MatchDirection) => void
+ summarize: () => void
+ regenerateSummary: () => void
+ loadSummary: () => void
+ summaryStepClicked: (nodeId: string, kind: SummaryItemKind) => void
+ showFeedback: (nodeId: string | null, entry: FeedbackEntry) => void
+ retryTraceFeedback: () => void
+}
+
+function toReadyProps(values: ReadyValues, actions: ReadyActions): TraceViewReadyProps | null {
+ if (!values.summary) {
+ return null
+ }
+ return {
+ header: {
+ ...values.header,
+ backLink: values.backLink,
+ exportAction: { loading: values.traceExportLoading, onExport: actions.exportTrace },
+ },
+ summary: {
+ ...values.summary,
+ clusters: values.clustersChip,
+ evals: values.evalsChip ? { chip: values.evalsChip, onClick: actions.showFailingEvals } : null,
+ feedback: values.feedbackChip
+ ? { chip: values.feedbackChip, onClick: () => actions.showFeedback(null, 'chip') }
+ : null,
+ git: values.gitBranch,
+ },
+ mode: values.mode,
+ onModeChange: actions.setMode,
+ tree: values.tree,
+ selectedNodeId: values.selectedNodeId,
+ onSelectNode: actions.selectNode,
+ onPrefetchNode: actions.prefetchNode,
+ onSelectFromView: actions.selectAndShowSpans,
+ detail: values.detailData
+ ? {
+ ...values.detailData,
+ tab: values.detailTab,
+ onTabChange: actions.setDetailTab,
+ onViewInThread: values.canViewInThread ? actions.viewInThread : null,
+ actions: values.datasetItemSource ? <SaveToDatasetButton {...values.datasetItemSource} /> : null,
+ stepFeedback: values.selectedStepFeedback
+ ? {
+ feedback: values.selectedStepFeedback,
+ onOpen: () => actions.showFeedback(values.selectedNodeId, 'step'),
+ }
+ : null,
+ }
+ : null,
+ thread: values.thread,
+ timeline: values.timeline,
+ evalOutcomes: values.evalOutcomesByNode,
+ search: { ...values.searchBox, onQueryChange: actions.setQuery, onStep: actions.stepMatch },
+ matchingNodeIds: values.matchingNodeIds,
+ highlightQuery: values.highlightQuery,
+ matchStepCount: values.matchStepCount,
+ summaryMode: {
+ state: values.summaryState,
+ requesting: values.summaryRequesting,
+ requestError: values.summaryRequestError,
+ consentGiven: values.summaryConsentGiven,
+ onRequest: actions.summarize,
+ onRegenerate: actions.regenerateSummary,
+ onReload: actions.loadSummary,
+ onSelectStep: actions.summaryStepClicked,
+ },
+ feedbackMode: values.feedbackMode,
+ onRetryFeedback: actions.retryTraceFeedback,
+ feedbackCount: values.feedbackCount,
+ feedbackCountByNodeId: values.feedbackCountByNodeId,
+ }
+}
+
+export function TraceViewContainer({ hostId, traceId, timestampHint, backLink }: TraceViewContainerProps): JSX.Element {
+ const logic = traceViewModelLogic({ hostId, traceId, timestampHint })
+ // Every kea value getter is a hook, so read them all on every render, whatever the status.
+ const {
+ status,
+ errorMessage,
+ header,
+ summary,
+ clustersChip,
+ mode,
+ tree,
+ selectedNodeId,
+ detailData,
+ detailTab,
+ datasetItemSource,
+ canViewInThread,
+ thread,
+ timeline,
+ evalsChip,
+ evalOutcomesByNode,
+ gitBranch,
+ searchBox,
+ matchingNodeIds,
+ highlightQuery,
+ matchStepCount,
+ summaryState,
+ summaryRequesting,
+ summaryRequestError,
+ summaryConsentGiven,
+ feedbackChip,
+ feedbackCount,
+ feedbackCountByNodeId,
+ feedbackMode,
+ selectedStepFeedback,
+ } = useValues(logic)
+ const actions = useActions(logic)
+ const exportLogic = traceExportLogic({ traceId, timestampHint })
+ const { traceExportLoading } = useValues(exportLogic)
+ const { exportTrace } = useActions(exportLogic)
+
+ const readyProps =
+ status === 'ready'
+ ? toReadyProps(
+ {
+ header,
+ summary,
+ clustersChip,
+ mode,
+ tree,
+ selectedNodeId,
+ detailData,
+ detailTab,
+ datasetItemSource,
+ canViewInThread,
+ thread,
+ timeline,
+ evalsChip,
+ evalOutcomesByNode,
+ gitBranch,
+ searchBox,
+ matchingNodeIds,
+ highlightQuery,
+ matchStepCount,
+ summaryState,
+ summaryRequesting,
+ summaryRequestError,
+ summaryConsentGiven,
+ feedbackChip,
+ feedbackCount,
+ feedbackCountByNodeId,
+ feedbackMode,
+ selectedStepFeedback,
+ traceExportLoading,
+ backLink,
+ },
+ { ...actions, exportTrace }
+ )
+ : null
+
+ const props: TraceViewProps = readyProps
+ ? { status: 'ready', ...readyProps }
+ : status === 'error'
+ ? { status: 'error', errorMessage, backLink }
+ : { status: 'loading' }
+
+ return <TraceView {...props} />
+}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toBackLink.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/toBackLink.test.ts
new file mode 100644
index 000000000000..746d101951d8
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toBackLink.test.ts
@@ -0,0 +1,28 @@
+import { toBackLink } from './toBackLink'
+
+describe('toBackLink', () => {
+ it.each([
+ [
+ 'the traces list by default, keeping its filters but not the search',
+ { date_from: '-7d', event: 'gen-1', search: 'invoice' },
+ '/ai-observability/traces?date_from=-7d',
+ ],
+ [
+ 'the generations list when opened from it',
+ { back_to: 'generations', date_from: '-7d', tab: 'evals', search: 'invoice' },
+ '/ai-observability/generations?date_from=-7d',
+ ],
+ [
+ 'the reviews tab when opened from reviews',
+ { back_to: 'reviews' },
+ '/ai-observability/reviews?human_reviews_tab=reviews',
+ ],
+ [
+ 'the review queue when opened from one',
+ { back_to: 'reviews', queue_id: 'queue-1', search: 'invoice' },
+ '/ai-observability/reviews?queue_id=queue-1',
+ ],
+ ])('goes back to %s', (_name, searchParams, expected) => {
+ expect(toBackLink(searchParams).href).toBe(expected)
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toHeader.ts b/products/ai_observability/frontend/redesign/trace/adapter/toBackLink.ts
similarity index 54%
rename from products/ai_observability/frontend/redesign/trace/adapter/toHeader.ts
rename to products/ai_observability/frontend/redesign/trace/adapter/toBackLink.ts
index 30b8c4d40147..a43928abe181 100644
--- a/products/ai_observability/frontend/redesign/trace/adapter/toHeader.ts
+++ b/products/ai_observability/frontend/redesign/trace/adapter/toBackLink.ts
@@ -3,32 +3,15 @@ import { combineUrl } from 'kea-router'
import { urls } from 'scenes/urls'
import { sanitizeTraceUrlSearchParams } from '../../../utils'
-import { TraceHeaderProps } from '../components/TraceHeader'
import { LabeledLink } from '../types'
-export interface TraceNeighbours {
- olderTraceId: string | null
- olderTimestamp: string | null
- newerTraceId: string | null
- newerTimestamp: string | null
-}
-
type SearchParams = Record<string, unknown>
-// The lists read `search` as their own search term, and another trace starts with an empty search.
+// The lists read `search` as their own search term.
function listParams(searchParams: SearchParams): SearchParams {
return sanitizeTraceUrlSearchParams(searchParams, { removeSearch: true })
}
-function neighbourHref(traceId: string | null, timestamp: string | null, searchParams: SearchParams): string | null {
- return traceId
- ? combineUrl(urls.aiObservabilityTrace(traceId), {
- ...listParams(searchParams),
- timestamp: timestamp ?? undefined,
- }).url
- : null
-}
-
// Matches the legacy scene: a link opened from a review queue returns to that queue, other links to the reviews tab.
function reviewsBackHref(searchParams: SearchParams): string {
const inQueue = typeof searchParams.queue_id === 'string' && searchParams.queue_id !== ''
@@ -50,17 +33,3 @@ export function toBackLink(searchParams: SearchParams): LabeledLink {
}
return { label: 'Back to traces', href: combineUrl(urls.aiObservabilityTraces(), listParams(searchParams)).url }
}
-
-export function toHeader(
- title: { name: string; hasError: boolean },
- neighbours: TraceNeighbours,
- searchParams: SearchParams
-): TraceHeaderProps {
- return {
- name: title.name,
- hasError: title.hasError,
- olderHref: neighbourHref(neighbours.olderTraceId, neighbours.olderTimestamp, searchParams),
- newerHref: neighbourHref(neighbours.newerTraceId, neighbours.newerTimestamp, searchParams),
- backLink: toBackLink(searchParams),
- }
-}
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toHeader.test.ts b/products/ai_observability/frontend/redesign/trace/adapter/toHeader.test.ts
deleted file mode 100644
index 82b0740bb570..000000000000
--- a/products/ai_observability/frontend/redesign/trace/adapter/toHeader.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { TraceNeighbours, toHeader } from './toHeader'
-
-const title = { name: 'answer-billing-question', hasError: false }
-
-const noNeighbours: TraceNeighbours = {
- olderTraceId: null,
- olderTimestamp: null,
- newerTraceId: null,
- newerTimestamp: null,
-}
-
-describe('toHeader', () => {
- it('links neighbours with their timestamps and the list context without the search, and leaves missing neighbours null', () => {
- const header = toHeader(
- title,
- { ...noNeighbours, olderTraceId: 'trace-0', olderTimestamp: '2026-09-01T10:00:00Z' },
- { date_from: '-7d', event: 'gen-1', line: '4', back_to: 'generations', search: 'invoice' }
- )
- expect(header.olderHref).toBe(
- '/ai-observability/traces/trace-0?date_from=-7d&timestamp=2026-09-01T10%3A00%3A00Z'
- )
- expect(header.newerHref).toBeNull()
- })
-
- it.each([
- [
- 'the traces list by default, keeping its filters but not the search',
- { date_from: '-7d', event: 'gen-1', search: 'invoice' },
- '/ai-observability/traces?date_from=-7d',
- ],
- [
- 'the generations list when opened from it',
- { back_to: 'generations', date_from: '-7d', tab: 'evals', search: 'invoice' },
- '/ai-observability/generations?date_from=-7d',
- ],
- [
- 'the reviews tab when opened from reviews',
- { back_to: 'reviews' },
- '/ai-observability/reviews?human_reviews_tab=reviews',
- ],
- [
- 'the review queue when opened from one',
- { back_to: 'reviews', queue_id: 'queue-1', search: 'invoice' },
- '/ai-observability/reviews?queue_id=queue-1',
- ],
- ])('goes back to %s', (_name, searchParams, expected) => {
- expect(toHeader(title, noNeighbours, searchParams).backLink.href).toBe(expected)
- })
-})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/traceSceneWiring.test.tsx b/products/ai_observability/frontend/redesign/trace/adapter/traceSceneWiring.test.tsx
index d31175fe6c01..12474b0cda9d 100644
--- a/products/ai_observability/frontend/redesign/trace/adapter/traceSceneWiring.test.tsx
+++ b/products/ai_observability/frontend/redesign/trace/adapter/traceSceneWiring.test.tsx
@@ -1,11 +1,14 @@
import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'
import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { addProjectIdIfMissing } from 'lib/utils/kea-router'
import { urls } from 'scenes/urls'
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { useMocks } from '~/mocks/jest'
import { performQuery } from '~/queries/query'
import { initKeaTests } from '~/test/init'
@@ -31,6 +34,7 @@ import {
const FLAG = FEATURE_FLAGS.AI_OBSERVABILITY_TRACE_REDESIGN
const DATASETS_FLAG = FEATURE_FLAGS.LLM_ANALYTICS_DATASETS
const ENGINEERING_ANALYTICS_FLAG = FEATURE_FLAGS.ENGINEERING_ANALYTICS
+const TRACE_NAVIGATION_FLAG = FEATURE_FLAGS.LLM_ANALYTICS_TRACE_NAVIGATION
jest.mock('~/queries/query', () => ({ ...jest.requireActual('~/queries/query'), performQuery: jest.fn() }))
jest.mock('../../../utils', () => ({
@@ -87,7 +91,10 @@ const generation = makeEvent({
},
})
-function renderNewView(flags: Record<string, boolean> = {}): ReturnType<typeof render> {
+function renderNewView(
+ flags: Record<string, boolean> = {},
+ params: Record<string, string> = {}
+): ReturnType<typeof render> {
initKeaTests()
featureFlagLogic.mount()
featureFlagLogic.actions.setFeatureFlags(
@@ -98,7 +105,7 @@ function renderNewView(flags: Record<string, boolean> = {}): ReturnType<typeof r
jest.mocked(performQuery).mockReset()
jest.mocked(performQuery).mockResolvedValue({ results: [] })
aiObservabilityTraceLogic.mount()
- router.actions.push(urls.aiObservabilityTrace('trace-1'))
+ router.actions.push(urls.aiObservabilityTrace('trace-1', params))
return render(<TraceScene />)
}
@@ -107,7 +114,10 @@ describe('TraceScene', () => {
clusters = []
})
- afterEach(cleanup)
+ afterEach(() => {
+ cleanup()
+ resumeKeaLoadersErrors()
+ })
describe('the new view', () => {
beforeEach(() => {
@@ -124,12 +134,128 @@ describe('TraceScene', () => {
})
})
- it('opens on the default node without the legacy trace query', async () => {
- const { findAllByText, findByText } = renderNewView()
+ it('opens on the default node without the legacy trace or neighbours queries', async () => {
+ const apiQuery = jest.spyOn(api, 'query').mockResolvedValue({ results: [] })
+ const { findAllByText, findByText } = renderNewView({ [TRACE_NAVIGATION_FLAG]: true })
expect((await findAllByText('answer-billing-question')).length).toBeGreaterThan(0)
expect(await findByText('Two seats were added.')).toBeTruthy()
+ await expectLogic(aiObservabilityTraceLogic).toFinishAllListeners()
expect(jest.mocked(performQuery).mock.calls.some(([query]) => query.kind === 'TraceQuery')).toBe(false)
+ expect(apiQuery.mock.calls.some(([query]) => query.kind === 'TraceNeighborsQuery')).toBe(false)
+ apiQuery.mockRestore()
+ })
+
+ it('starts another trace with an empty search, its own timestamp and Spans', async () => {
+ const timestampHints: Record<string, string | null> = {}
+ useMocks({
+ get: {
+ [TRACE_URL]: ({ params, request }) => {
+ const traceId = decodeIdSegment(String(params.id))
+ timestampHints[traceId] = new URL(request.url).searchParams.get('timestamp_hint')
+ return [
+ 200,
+ makeTraceResource({
+ defaultNodeId: 'gen-2',
+ name: traceId === 'trace-2' ? 'answer-refund-question' : 'answer-billing-question',
+ }),
+ ]
+ },
+ },
+ })
+ const { container, findAllByText, findByText } = renderNewView({}, { search: 'invoice' })
+ const treeRow = (): Element | null => container.querySelector('[data-attr="trace-view-tree-node"]')
+ const searchInput = (): HTMLInputElement | null =>
+ container.querySelector<HTMLInputElement>('input[data-attr="trace-view-search-input"]')
+
+ fireEvent.click(await findByText('Thread'))
+ await waitFor(() => expect(treeRow()).toBeNull())
+ expect(searchInput()?.value).toBe('invoice')
+
+ router.actions.push(urls.aiObservabilityTrace('trace-2', { timestamp: '2026-09-02T08:00:00Z' }))
+
+ expect((await findAllByText('answer-refund-question')).length).toBeGreaterThan(0)
+ expect(timestampHints['trace-2']).toBe('2026-09-02T08:00:00Z')
+ expect(searchInput()?.value).toBe('')
+ expect(treeRow()).not.toBeNull()
+ })
+
+ it.each([
+ [
+ 'the header',
+ 200,
+ (view: ReturnType<typeof render>): Promise<HTMLElement> =>
+ view.findByLabelText('Back to generations', { selector: '[data-attr="trace-view-back"]' }),
+ ],
+ [
+ 'the error screen',
+ 500,
+ (view: ReturnType<typeof render>): Promise<HTMLElement> => view.findByText('Back to generations'),
+ ],
+ ])('links back to the list the trace came from on %s', async (_name, status, findBackLink) => {
+ silenceKeaLoadersErrors()
+ useMocks({
+ get: {
+ [TRACE_URL]: () =>
+ status === 200 ? [200, makeTraceResource()] : [status, { detail: 'Server error.' }],
+ },
+ })
+
+ const link = (await findBackLink(renderNewView({}, { back_to: 'generations' }))).closest('a')
+
+ expect(link?.getAttribute('href')?.endsWith(urls.aiObservabilityGenerations())).toBe(true)
+ })
+
+ it('selects the step named in the URL', async () => {
+ const { container } = renderNewView({}, { event: 'span-1' })
+
+ await waitFor(() =>
+ expect(
+ container.querySelector('[data-attr="trace-view-tree-node"][aria-current="true"]')?.textContent
+ ).toContain('span-1')
+ )
+ })
+
+ it('opens Summary from a tab=summary link', async () => {
+ useMocks({
+ get: {
+ [SUMMARY_URL]: () => [
+ 200,
+ {
+ status: 'ready',
+ content: {
+ title: 'Invoice question answered',
+ bullets: [{ text: 'Context is retrieved first.', nodeId: 'span-1' }],
+ notes: [],
+ flow: 'retrieve → answer',
+ model: 'gpt-4.1-mini',
+ generatedAt: '2026-09-01T10:20:00Z',
+ },
+ failure: null,
+ },
+ ],
+ },
+ })
+ const { findByText } = renderNewView({}, { tab: 'summary' })
+
+ expect(await findByText('Context is retrieved first.')).toBeTruthy()
+ })
+
+ it('seeds the search box from the URL', async () => {
+ const { container, findByText } = renderNewView({}, { search: 'invoice' })
+
+ expect(await findByText('1 match')).toBeTruthy()
+ expect(container.querySelector<HTMLInputElement>('input[data-attr="trace-view-search-input"]')?.value).toBe(
+ 'invoice'
+ )
+ })
+
+ it('writes a clicked step to the URL', async () => {
+ const { findByText } = renderNewView()
+
+ fireEvent.click(await findByText('span-1'))
+
+ await waitFor(() => expect(router.values.searchParams.event).toBe('span-1'))
})
it('starts reading a step when the pointer rests on its row', async () => {
diff --git a/products/ai_observability/frontend/redesign/trace/components/TraceHeader.stories.tsx b/products/ai_observability/frontend/redesign/trace/components/TraceHeader.stories.tsx
index 695361e98123..cd5f12d4c001 100644
--- a/products/ai_observability/frontend/redesign/trace/components/TraceHeader.stories.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/TraceHeader.stories.tsx
@@ -9,8 +9,6 @@ const meta: Meta<typeof TraceHeader> = {
args: {
name: 'answer-billing-question',
hasError: false,
- olderHref: '/older',
- newerHref: null,
backLink: { label: 'Back to traces', href: '/traces' },
},
}
diff --git a/products/ai_observability/frontend/redesign/trace/components/TraceHeader.tsx b/products/ai_observability/frontend/redesign/trace/components/TraceHeader.tsx
index fa20e4821068..b226c8b5f18d 100644
--- a/products/ai_observability/frontend/redesign/trace/components/TraceHeader.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/TraceHeader.tsx
@@ -3,45 +3,35 @@ import { LemonButton } from '@posthog/lemon-ui'
import { LabeledLink } from '../types'
import { TraceExportButton, TraceExportButtonProps } from './TraceExportButton'
-import { TraceNeighbourLinks } from './TraceNeighbourLinks'
import { TraceSearchBox, TraceSearchBoxProps } from './TraceSearchBox'
import { TraceStatusBadge } from './TraceStatusBadge'
export interface TraceHeaderProps {
name: string
hasError: boolean
- olderHref: string | null
- newerHref: string | null
- backLink: LabeledLink
+ backLink: LabeledLink | null
search?: TraceSearchBoxProps | null
exportAction?: TraceExportButtonProps
}
-export function TraceHeader({
- name,
- hasError,
- olderHref,
- newerHref,
- backLink,
- search = null,
- exportAction,
-}: TraceHeaderProps): JSX.Element {
+export function TraceHeader({ name, hasError, backLink, search = null, exportAction }: TraceHeaderProps): JSX.Element {
return (
<header className="flex flex-wrap items-center gap-2">
- <LemonButton
- size="small"
- icon={<IconArrowLeft />}
- to={backLink.href}
- tooltip={backLink.label}
- aria-label={backLink.label}
- data-attr="trace-view-back"
- />
+ {backLink ? (
+ <LemonButton
+ size="small"
+ icon={<IconArrowLeft />}
+ to={backLink.href}
+ tooltip={backLink.label}
+ aria-label={backLink.label}
+ data-attr="trace-view-back"
+ />
+ ) : null}
<h1 className="m-0 min-w-0 truncate text-lg font-semibold">{name}</h1>
<TraceStatusBadge hasError={hasError} />
<div className="ml-auto flex min-w-0 flex-wrap items-center gap-2">
{search ? <TraceSearchBox {...search} /> : null}
{exportAction ? <TraceExportButton {...exportAction} /> : null}
- <TraceNeighbourLinks olderHref={olderHref} newerHref={newerHref} />
</div>
</header>
)
diff --git a/products/ai_observability/frontend/redesign/trace/components/TraceNeighbourLinks.tsx b/products/ai_observability/frontend/redesign/trace/components/TraceNeighbourLinks.tsx
deleted file mode 100644
index d4b6cbcf940b..000000000000
--- a/products/ai_observability/frontend/redesign/trace/components/TraceNeighbourLinks.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { IconChevronDown } from '@posthog/icons'
-import { LemonButton } from '@posthog/lemon-ui'
-
-export interface TraceNeighbourLinksProps {
- olderHref: string | null
- newerHref: string | null
-}
-
-export function TraceNeighbourLinks({ olderHref, newerHref }: TraceNeighbourLinksProps): JSX.Element {
- return (
- <div className="flex gap-1">
- <LemonButton
- size="small"
- icon={<IconChevronDown className="rotate-180" />}
- to={newerHref ?? undefined}
- disabledReason={newerHref ? undefined : 'No newer trace'}
- tooltip="Newer trace"
- aria-label="Newer trace"
- data-attr="trace-view-newer-trace"
- />
- <LemonButton
- size="small"
- icon={<IconChevronDown />}
- to={olderHref ?? undefined}
- disabledReason={olderHref ? undefined : 'No older trace'}
- tooltip="Older trace"
- aria-label="Older trace"
- data-attr="trace-view-older-trace"
- />
- </div>
- )
-}
diff --git a/products/ai_observability/frontend/redesign/trace/components/TraceView.tsx b/products/ai_observability/frontend/redesign/trace/components/TraceView.tsx
index 3511b69616b9..390d964f7ef4 100644
--- a/products/ai_observability/frontend/redesign/trace/components/TraceView.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/TraceView.tsx
@@ -46,7 +46,7 @@ const FEEDBACK_LOADING: FeedbackModeState = { status: 'loading' }
export type TraceViewProps =
| { status: 'loading' }
- | { status: 'error'; errorMessage: string; backLink: LabeledLink }
+ | { status: 'error'; errorMessage: string; backLink: LabeledLink | null }
| ({ status: 'ready' } & TraceViewReadyProps)
export function TraceView(props: TraceViewProps): JSX.Element {
diff --git a/products/ai_observability/frontend/redesign/trace/components/TraceViewError.tsx b/products/ai_observability/frontend/redesign/trace/components/TraceViewError.tsx
index aaff6d018174..2ed63e886003 100644
--- a/products/ai_observability/frontend/redesign/trace/components/TraceViewError.tsx
+++ b/products/ai_observability/frontend/redesign/trace/components/TraceViewError.tsx
@@ -5,7 +5,7 @@ import { LabeledLink } from '../types'
export interface TraceViewErrorProps {
message: string
- backLink: LabeledLink
+ backLink: LabeledLink | null
}
export function TraceViewError({ message, backLink }: TraceViewErrorProps): JSX.Element {
@@ -13,9 +13,11 @@ export function TraceViewError({ message, backLink }: TraceViewErrorProps): JSX.
<div className="flex flex-col items-start gap-2 py-8">
<h2 className="m-0 text-lg font-semibold">We couldn't load this trace</h2>
<p className="m-0 text-secondary">{message}</p>
- <LemonButton type="secondary" icon={<IconArrowLeft />} to={backLink.href}>
- {backLink.label}
- </LemonButton>
+ {backLink ? (
+ <LemonButton type="secondary" icon={<IconArrowLeft />} to={backLink.href}>
+ {backLink.label}
+ </LemonButton>
+ ) : null}
</div>
)
}
diff --git a/products/ai_observability/frontend/redesign/trace/sampleFixtures/anthropicMessagesThinkingToolUse.ts b/products/ai_observability/frontend/redesign/trace/sampleFixtures/anthropicMessagesThinkingToolUse.ts
index dbb73f800d2d..73c066a11462 100644
--- a/products/ai_observability/frontend/redesign/trace/sampleFixtures/anthropicMessagesThinkingToolUse.ts
+++ b/products/ai_observability/frontend/redesign/trace/sampleFixtures/anthropicMessagesThinkingToolUse.ts
@@ -145,8 +145,6 @@ export const anthropicMessagesThinkingToolUse: SampleTraceFixture = {
header: {
name: 'run-budget-rollup',
hasError: false,
- olderHref: '/older',
- newerHref: '/newer',
backLink: { label: 'Back to traces', href: '/traces' },
},
summary: {
diff --git a/products/ai_observability/frontend/redesign/trace/sampleFixtures/claudeCodePluginSession.ts b/products/ai_observability/frontend/redesign/trace/sampleFixtures/claudeCodePluginSession.ts
index 63ef546fc193..7cdf3683f8e4 100644
--- a/products/ai_observability/frontend/redesign/trace/sampleFixtures/claudeCodePluginSession.ts
+++ b/products/ai_observability/frontend/redesign/trace/sampleFixtures/claudeCodePluginSession.ts
@@ -322,8 +322,6 @@ export const claudeCodePluginSession: SampleTraceFixture = {
header: {
name: 'seo fixes',
hasError: false,
- olderHref: '/older',
- newerHref: null,
backLink: { label: 'Back to traces', href: '/traces' },
},
summary: {
diff --git a/products/ai_observability/frontend/redesign/trace/sampleFixtures/langchainCerebrasImageError.ts b/products/ai_observability/frontend/redesign/trace/sampleFixtures/langchainCerebrasImageError.ts
index ab5a663f228e..cfce4079a20e 100644
--- a/products/ai_observability/frontend/redesign/trace/sampleFixtures/langchainCerebrasImageError.ts
+++ b/products/ai_observability/frontend/redesign/trace/sampleFixtures/langchainCerebrasImageError.ts
@@ -121,8 +121,6 @@ export const langchainCerebrasImageError: SampleTraceFixture = {
header: {
name: 'scan_package',
hasError: true,
- olderHref: '/older',
- newerHref: '/newer',
backLink: { label: 'Back to traces', href: '/traces' },
},
summary: {
diff --git a/products/ai_observability/frontend/redesign/trace/sampleFixtures/openaiAgentsWithEvals.ts b/products/ai_observability/frontend/redesign/trace/sampleFixtures/openaiAgentsWithEvals.ts
index c46ebbdd3ff1..738729d23189 100644
--- a/products/ai_observability/frontend/redesign/trace/sampleFixtures/openaiAgentsWithEvals.ts
+++ b/products/ai_observability/frontend/redesign/trace/sampleFixtures/openaiAgentsWithEvals.ts
@@ -244,8 +244,6 @@ export const openaiAgentsWithEvals: SampleTraceFixture = {
header: {
name: 'Trip Planning',
hasError: false,
- olderHref: '/older',
- newerHref: '/newer',
backLink: { label: 'Back to traces', href: '/traces' },
},
summary: {
diff --git a/products/ai_observability/frontend/redesign/trace/storyFixtures.tsx b/products/ai_observability/frontend/redesign/trace/storyFixtures.tsx
index f8fbf0661b26..207e1d32a791 100644
--- a/products/ai_observability/frontend/redesign/trace/storyFixtures.tsx
+++ b/products/ai_observability/frontend/redesign/trace/storyFixtures.tsx
@@ -380,8 +380,6 @@ export const FIXTURE_TRACE: SampleTraceFixture = {
header: {
name: 'answer-billing-question',
hasError: false,
- olderHref: '/older',
- newerHref: '/newer',
backLink: { label: 'Back to traces', href: '/traces' },
exportAction: { loading: false, onExport: () => {} },
},
diff --git a/products/ai_observability/frontend/redesign/trace/tracePageLogic.test.ts b/products/ai_observability/frontend/redesign/trace/tracePageLogic.test.ts
new file mode 100644
index 000000000000..3b9511d95f9b
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/tracePageLogic.test.ts
@@ -0,0 +1,157 @@
+import { decodeParams, router } from 'kea-router'
+
+import { urls } from 'scenes/urls'
+
+import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
+import { initKeaTests } from '~/test/init'
+
+import { TRACE_PAGE_HOST_ID, tracePageLogic } from './tracePageLogic'
+import { traceViewHostLogic } from './traceViewHostLogic'
+
+describe('tracePageLogic', () => {
+ let logic: ReturnType<typeof tracePageLogic.build>
+ let host: ReturnType<typeof traceViewHostLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ host = traceViewHostLogic({ hostId: TRACE_PAGE_HOST_ID })
+ host.mount()
+ logic = tracePageLogic()
+ logic.mount()
+ })
+
+ const open = (search: string, id = 'trace-1'): void => {
+ const pathname = `${urls.aiObservabilityTraces()}/${id}`
+ // The raw search string reaches the logic as it does on a page load, before kea-router parses it.
+ router.actions.locationChanged({
+ method: 'POP',
+ pathname,
+ search,
+ searchParams: decodeParams(search, '?'),
+ hash: '',
+ hashParams: {},
+ url: `${pathname}${search}`,
+ })
+ }
+
+ it.each([
+ ['event', '?event=gen-1', { requestedStepId: 'gen-1', openingMode: null }],
+ ['tab=summary', '?tab=summary', { requestedStepId: null, openingMode: 'summary' }],
+ ['another tab', '?tab=conversation', { requestedStepId: null, openingMode: null }],
+ ['search', '?search=refund', { seedQuery: 'refund' }],
+ ['a numeric search keeps its text', '?search=1.50', { seedQuery: '1.50' }],
+ ])('reads %s from the URL', (_name, search, expected) => {
+ open(search)
+
+ expect(logic.values.traceId).toBe('trace-1')
+ expect(host.values).toMatchObject(expected)
+ })
+
+ it('decodes an encoded trace id', () => {
+ open('', 'a%2Fb')
+
+ expect(logic.values.traceId).toBe('a/b')
+ })
+
+ it.each([
+ ['timestamp', '?timestamp=2026-01-01T12:00:00Z', '2026-01-01T12:00:00Z'],
+ [
+ 'a timestamp whose plus sign decoded to a space',
+ '?timestamp=2026-01-01T12:00:00 00:00',
+ '2026-01-01T12:00:00+00:00',
+ ],
+ ['exception_ts', '?exception_ts=2026-01-01T12:00:00Z', '2026-01-01T11:40:00.000Z'],
+ ])('derives the timestamp hint from %s', (_name, search, expected) => {
+ open(search)
+
+ expect(logic.values.timestampHint).toBe(expected)
+ })
+
+ it('keeps the hint for the same trace and drops it for another', () => {
+ open('?timestamp=2026-01-01T12:00:00Z')
+ open('?event=gen-1')
+ expect(logic.values.timestampHint).toBe('2026-01-01T12:00:00Z')
+
+ open('', 'trace-2')
+ expect(logic.values.timestampHint).toBeNull()
+ })
+
+ it('resets mode and step tab for another trace, not for the first trace or the same one', () => {
+ host.actions.setMode('thread')
+ host.actions.setDetailTab('raw')
+
+ open('')
+ open('?event=gen-1')
+ expect(host.values).toMatchObject({ mode: 'thread', detailTab: 'raw' })
+
+ open('', 'trace-2')
+ expect(host.values).toMatchObject({ mode: 'spans', detailTab: 'messages' })
+ })
+
+ it.each([
+ ['a requested step', (): void => host.actions.requestStep('gen-2'), { event: 'gen-2' }],
+ ['a published query', (): void => host.actions.publishQuery('x'), { search: 'x' }],
+ ])('writes %s to the URL and keeps the other params and the hash', (_name, write, expected) => {
+ open('?back_to=generations')
+ router.actions.replace(router.values.location.pathname, router.values.searchParams, { panel: 'discussion' })
+
+ write()
+
+ expect(router.values.searchParams).toMatchObject({ ...expected, back_to: 'generations' })
+ expect(router.values.hashParams).toEqual({ panel: 'discussion' })
+ })
+
+ it.each(['1.50', '2e3'])('keeps the raw search %s when a step is written', (query) => {
+ open(`?search=${query}`)
+
+ host.actions.requestStep('gen-2')
+
+ expect(new URLSearchParams(router.values.location.search).get('search')).toBe(query)
+ expect(host.values.seedQuery).toBe(query)
+ })
+
+ it.each([
+ ['a step the URL already omits', '', (): void => host.actions.requestStep(null)],
+ ['a query the URL already holds', '?search=1.50', (): void => host.actions.publishQuery('1.50')],
+ ])('does not write the URL for %s', (_name, search, write) => {
+ open(search)
+ const replace = jest.spyOn(router.actions, 'replace')
+
+ write()
+
+ expect(replace).not.toHaveBeenCalled()
+ replace.mockRestore()
+ })
+
+ it.each(['1.50', '[draft]'])('keeps the typed search %s when the browser restores its URL', (query) => {
+ open('')
+ host.actions.publishQuery(query)
+
+ // Back and forward decode the URL again, as a page load does.
+ open(router.values.location.search)
+
+ expect(host.values.seedQuery).toBe(query)
+ })
+
+ it('derives the back link from the URL', () => {
+ open('?back_to=reviews')
+
+ expect(logic.values.backLink.label).toBe('Back to reviews')
+ })
+
+ // Regression: an override left behind on unmount keeps the nav collapsed on every other page.
+ it.each([
+ ['expanded', false],
+ ['collapsed', true],
+ ])('collapses the nav while open and restores it %s on close', (_name, collapsedBefore) => {
+ logic.unmount()
+ panelLayoutLogic.mount()
+ panelLayoutLogic.actions.setLayoutNavCollapsedDesktop(collapsedBefore)
+
+ logic = tracePageLogic()
+ logic.mount()
+ expect(panelLayoutLogic.values.isLayoutNavCollapsed).toBe(true)
+ logic.unmount()
+ expect(panelLayoutLogic.values.isLayoutNavCollapsed).toBe(collapsedBefore)
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/tracePageLogic.ts b/products/ai_observability/frontend/redesign/trace/tracePageLogic.ts
new file mode 100644
index 000000000000..2285893aca55
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/tracePageLogic.ts
@@ -0,0 +1,190 @@
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ beforeUnmount,
+ connect,
+ kea,
+ listeners,
+ path,
+ reducers,
+ selectors,
+} from 'kea'
+import { router, urlToAction } from 'kea-router'
+
+import { dayjs } from 'lib/dayjs'
+import { tryDecodeURIComponent } from 'lib/utils/url'
+import { urls } from 'scenes/urls'
+
+import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
+
+import { toBackLink } from './adapter/toBackLink'
+import { traceViewHostLogic } from './traceViewHostLogic'
+import type { LabeledLink } from './types'
+
+export const TRACE_PAGE_HOST_ID = 'trace-page'
+
+const EXCEPTION_LOOKUP_WINDOW_MINUTES = 20
+
+const LAYOUT_NAV_OVERRIDE_OWNER = 'ai-trace-page'
+
+// kea-router reads a numeric param as a number, which turns a typed `1.50` into `1.5`. It also pads a value shaped like
+// a JSON array or object with one space, so it reads that value back as a string.
+function searchParamFromUrl(): string {
+ const value = new URLSearchParams(router.values.location.search).get('search') ?? ''
+ return /^(\[.*\]|\{.*\}) +$/.test(value) ? value.slice(0, -1) : value
+}
+
+function replaceUrlParams(changes: Record<string, string | undefined>): void {
+ router.actions.replace(
+ router.values.location.pathname,
+ { ...router.values.searchParams, search: searchParamFromUrl() || undefined, ...changes },
+ router.values.hashParams
+ )
+}
+
+// An unencoded `+` in a URL query decodes to a space, so `+00:00` arrives as ` 00:00`.
+function parseUrlDate(value: string): string | null {
+ const raw = String(value).trim()
+ if (dayjs(raw).isValid()) {
+ return raw
+ }
+ const repaired = raw.replace(/ (\d{2}:?\d{2})$/, '+$1')
+ return dayjs(repaired).isValid() ? repaired : null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface tracePageLogicValues {
+ backLink: LabeledLink
+ timestampHint: string | null
+ traceId: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface tracePageLogicActions {
+ setLayoutNavCollapsedOverride: (
+ owner: string,
+ collapsed: boolean | null
+ ) => {
+ collapsed: boolean | null
+ owner: string
+ } // panelLayoutLogic
+ publishQuery: (query: string) => {
+ query: string
+ } // traceViewHostLogic
+ requestStep: (stepId: string | null) => {
+ stepId: string | null
+ } // traceViewHostLogic
+ setDetailTab: (tab: import('./types').NodeDetailTab) => {
+ tab: import('./types').NodeDetailTab
+ } // traceViewHostLogic
+ setMode: (mode: import('./types').TraceMode) => {
+ mode: import('./types').TraceMode
+ } // traceViewHostLogic
+ setOpeningMode: (mode: import('./types').TraceOpeningMode) => {
+ mode: import('./types').TraceOpeningMode
+ } // traceViewHostLogic
+ setSeedQuery: (query: string) => {
+ query: string
+ } // traceViewHostLogic
+ setTimestampHint: (timestampHint: string | null) => {
+ timestampHint: string | null
+ }
+ setTraceId: (traceId: string) => {
+ traceId: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface tracePageLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ backLink: (searchParams: Record<string, any>) => LabeledLink
+ }
+}
+
+export type tracePageLogicType = MakeLogicType<
+ tracePageLogicValues,
+ tracePageLogicActions,
+ Record<string, any>,
+ tracePageLogicMeta
+>
+
+export const tracePageLogic = kea<tracePageLogicType>([
+ path(['products', 'ai_observability', 'frontend', 'redesign', 'trace', 'tracePageLogic']),
+ connect(() => ({
+ actions: [
+ traceViewHostLogic({ hostId: TRACE_PAGE_HOST_ID }),
+ ['setMode', 'setDetailTab', 'requestStep', 'publishQuery', 'setOpeningMode', 'setSeedQuery'],
+ panelLayoutLogic,
+ ['setLayoutNavCollapsedOverride'],
+ ],
+ })),
+ actions({
+ setTraceId: (traceId: string) => ({ traceId }),
+ setTimestampHint: (timestampHint: string | null) => ({ timestampHint }),
+ }),
+ reducers({
+ traceId: [
+ '',
+ {
+ setTraceId: (_, { traceId }) => traceId,
+ },
+ ],
+ timestampHint: [
+ null as string | null,
+ {
+ setTimestampHint: (_, { timestampHint }) => timestampHint,
+ },
+ ],
+ }),
+ selectors({
+ backLink: [
+ () => [router.selectors.searchParams],
+ (searchParams: Record<string, unknown>): LabeledLink => toBackLink(searchParams),
+ ],
+ }),
+ listeners(() => ({
+ requestStep: ({ stepId }) => {
+ if ((router.values.searchParams.event ?? null) !== stepId) {
+ replaceUrlParams({ event: stepId ?? undefined })
+ }
+ },
+ publishQuery: ({ query }) => {
+ if (searchParamFromUrl() !== query) {
+ replaceUrlParams({ search: query || undefined })
+ }
+ },
+ })),
+ urlToAction(({ actions, values }) => ({
+ [`${urls.aiObservabilityTraces()}/:id`]: ({ id }, { event, timestamp, exception_ts, tab }) => {
+ const traceId = tryDecodeURIComponent(id ?? '')
+ const isNewTrace = traceId !== values.traceId
+ // The page opens each trace from the start. Only a host that steps through traces carries these over.
+ if (isNewTrace && values.traceId) {
+ actions.setMode('spans')
+ actions.setDetailTab('messages')
+ }
+ actions.setTraceId(traceId)
+ actions.requestStep(event || null)
+ actions.setOpeningMode(tab === 'summary' ? 'summary' : null)
+ actions.setSeedQuery(searchParamFromUrl())
+ const dateFrom = timestamp ? parseUrlDate(timestamp) : null
+ const exceptionDate = exception_ts ? parseUrlDate(exception_ts) : null
+ if (dateFrom) {
+ actions.setTimestampHint(dateFrom)
+ } else if (exceptionDate) {
+ actions.setTimestampHint(
+ dayjs(exceptionDate).subtract(EXCEPTION_LOOKUP_WINDOW_MINUTES, 'minutes').toISOString()
+ )
+ } else if (isNewTrace) {
+ actions.setTimestampHint(null)
+ }
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.setLayoutNavCollapsedOverride(LAYOUT_NAV_OVERRIDE_OWNER, true)
+ }),
+ beforeUnmount(({ actions }) => {
+ actions.setLayoutNavCollapsedOverride(LAYOUT_NAV_OVERRIDE_OWNER, null)
+ }),
+])
diff --git a/products/ai_observability/frontend/redesign/trace/traceViewHostLogic.test.ts b/products/ai_observability/frontend/redesign/trace/traceViewHostLogic.test.ts
new file mode 100644
index 000000000000..ad8582a64e33
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/traceViewHostLogic.test.ts
@@ -0,0 +1,42 @@
+import { initKeaTests } from '~/test/init'
+
+import { traceViewHostLogic } from './traceViewHostLogic'
+
+describe('traceViewHostLogic', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ it('starts with the spans mode and messages tab', () => {
+ const logic = traceViewHostLogic({ hostId: 'a' })
+ logic.mount()
+
+ expect(logic.values.mode).toBe('spans')
+ expect(logic.values.detailTab).toBe('messages')
+ expect(logic.values.requestedStepId).toBeNull()
+ expect(logic.values.openingMode).toBeNull()
+ expect(logic.values.seedQuery).toBe('')
+ })
+
+ it('does not share state between hosts', () => {
+ const first = traceViewHostLogic({ hostId: 'first' })
+ const second = traceViewHostLogic({ hostId: 'second' })
+ first.mount()
+ second.mount()
+
+ first.actions.setMode('feedback')
+
+ expect(first.values.mode).toBe('feedback')
+ expect(second.values.mode).toBe('spans')
+ })
+
+ it('publishQuery changes no state', () => {
+ const logic = traceViewHostLogic({ hostId: 'a' })
+ logic.mount()
+ const before = { ...logic.values }
+
+ logic.actions.publishQuery('abc')
+
+ expect(logic.values).toEqual(before)
+ })
+})
diff --git a/products/ai_observability/frontend/redesign/trace/traceViewHostLogic.ts b/products/ai_observability/frontend/redesign/trace/traceViewHostLogic.ts
new file mode 100644
index 000000000000..256b22a8c581
--- /dev/null
+++ b/products/ai_observability/frontend/redesign/trace/traceViewHostLogic.ts
@@ -0,0 +1,96 @@
+import { MakeLogicType, actions, kea, key, path, props, reducers } from 'kea'
+
+import type { NodeDetailTab, TraceMode, TraceOpeningMode } from './types'
+
+export interface TraceViewHostLogicProps {
+ hostId: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceViewHostLogicValues {
+ detailTab: NodeDetailTab
+ mode: TraceMode
+ openingMode: TraceOpeningMode
+ requestedStepId: string | null
+ seedQuery: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceViewHostLogicActions {
+ publishQuery: (query: string) => {
+ query: string
+ }
+ requestStep: (stepId: string | null) => {
+ stepId: string | null
+ }
+ setDetailTab: (tab: NodeDetailTab) => {
+ tab: NodeDetailTab
+ }
+ setMode: (mode: TraceMode) => {
+ mode: TraceMode
+ }
+ setOpeningMode: (mode: TraceOpeningMode) => {
+ mode: TraceOpeningMode
+ }
+ setSeedQuery: (query: string) => {
+ query: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceViewHostLogicMeta {
+ key: string
+}
+
+export type traceViewHostLogicType = MakeLogicType<
+ traceViewHostLogicValues,
+ traceViewHostLogicActions,
+ TraceViewHostLogicProps,
+ traceViewHostLogicMeta
+>
+
+export const traceViewHostLogic = kea<traceViewHostLogicType>([
+ path((key) => ['products', 'ai_observability', 'frontend', 'redesign', 'trace', 'traceViewHostLogic', key]),
+ props({} as TraceViewHostLogicProps),
+ key((props) => props.hostId),
+ actions({
+ setMode: (mode: TraceMode) => ({ mode }),
+ setDetailTab: (tab: NodeDetailTab) => ({ tab }),
+ requestStep: (stepId: string | null) => ({ stepId }),
+ setOpeningMode: (mode: TraceOpeningMode) => ({ mode }),
+ setSeedQuery: (query: string) => ({ query }),
+ publishQuery: (query: string) => ({ query }),
+ }),
+ reducers({
+ mode: [
+ 'spans' as TraceMode,
+ {
+ setMode: (_, { mode }) => mode,
+ },
+ ],
+ detailTab: [
+ 'messages' as NodeDetailTab,
+ {
+ setDetailTab: (_, { tab }) => tab,
+ },
+ ],
+ requestedStepId: [
+ null as string | null,
+ {
+ requestStep: (_, { stepId }) => stepId,
+ },
+ ],
+ openingMode: [
+ null as TraceOpeningMode,
+ {
+ setOpeningMode: (_, { mode }) => mode,
+ },
+ ],
+ seedQuery: [
+ '',
+ {
+ setSeedQuery: (_, { query }) => query,
+ },
+ ],
+ }),
+])
diff --git a/products/ai_observability/frontend/redesign/trace/traceViewLogic.test.ts b/products/ai_observability/frontend/redesign/trace/traceViewLogic.test.ts
index 63b933bca5c1..bd85e0b0dd81 100644
--- a/products/ai_observability/frontend/redesign/trace/traceViewLogic.test.ts
+++ b/products/ai_observability/frontend/redesign/trace/traceViewLogic.test.ts
@@ -5,7 +5,6 @@ import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
-import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -98,19 +97,6 @@ describe('traceViewLogic', () => {
return logic
}
- // Regression: an override left behind on unmount keeps the nav collapsed on every other page.
- it.each([
- ['expanded', false],
- ['collapsed', true],
- ])('collapses the nav while open and restores it %s on close', async (_name, collapsedBefore) => {
- panelLayoutLogic.mount()
- panelLayoutLogic.actions.setLayoutNavCollapsedDesktop(collapsedBefore)
- const logic = await mountedLogic()
- expect(panelLayoutLogic.values.isLayoutNavCollapsed).toBe(true)
- logic.unmount()
- expect(panelLayoutLogic.values.isLayoutNavCollapsed).toBe(collapsedBefore)
- })
-
it('loads the trace by its encoded id with the link timestamp as the hint and derives the summary', async () => {
const logic = traceViewLogic({ traceId: 'a/b', timestampHint: '2026-09-01T10:15:00Z' })
logic.mount()
diff --git a/products/ai_observability/frontend/redesign/trace/traceViewLogic.ts b/products/ai_observability/frontend/redesign/trace/traceViewLogic.ts
index d8dd5053f6d2..3808c28b1754 100644
--- a/products/ai_observability/frontend/redesign/trace/traceViewLogic.ts
+++ b/products/ai_observability/frontend/redesign/trace/traceViewLogic.ts
@@ -1,25 +1,10 @@
-import {
- MakeLogicType,
- actions,
- afterMount,
- beforeUnmount,
- connect,
- kea,
- key,
- listeners,
- path,
- props,
- reducers,
- selectors,
-} from 'kea'
+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
import { ApiConfig, ApiError } from 'lib/api'
import { urls } from 'scenes/urls'
-import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
-
import {
aiObservabilityTracesEvaluationsRetrieve,
aiObservabilityTracesNodesRetrieve,
@@ -73,13 +58,6 @@ export interface traceViewLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceViewLogicActions {
- setLayoutNavCollapsedOverride: (
- owner: string,
- collapsed: boolean | null
- ) => {
- collapsed: boolean | null
- owner: string
- } // panelLayoutLogic
loadEvaluationResults: () => any
loadEvaluationResultsFailure: (
error: string,
@@ -181,8 +159,6 @@ function toLoadFailure(error: unknown): LoadFailure {
return error instanceof ApiError && error.status === 404 ? 'not_found' : 'failed'
}
-const layoutNavOverrideOwner = (props: TraceViewLogicProps): string => `ai-trace-${props.traceId}`
-
export function elapsedMs(since: number): number {
return Math.round(performance.now() - since)
}
@@ -191,7 +167,6 @@ export const traceViewLogic = kea<traceViewLogicType>([
path((key) => ['products', 'ai_observability', 'frontend', 'redesign', 'trace', 'traceViewLogic', key]),
props({} as TraceViewLogicProps),
key((props) => props.traceId),
- connect(() => ({ actions: [panelLayoutLogic, ['setLayoutNavCollapsedOverride']] })),
actions({
loadNode: (nodeId: string, trigger: NodeLoadTrigger) => ({ nodeId, trigger }),
nodeRequested: (nodeId: string, trigger: NodeLoadTrigger) => ({ nodeId, trigger }),
@@ -384,13 +359,9 @@ export const traceViewLogic = kea<traceViewLogicType>([
loadNodeFailure: ({ nodeId }) => endRead(nodeId),
}
}),
- afterMount(({ actions, props }) => {
+ afterMount(({ actions }) => {
actions.loadTrace()
actions.loadEvaluationResults()
- actions.setLayoutNavCollapsedOverride(layoutNavOverrideOwner(props), true)
- }),
- beforeUnmount(({ actions, props }) => {
- actions.setLayoutNavCollapsedOverride(layoutNavOverrideOwner(props), null)
}),
// Without a hint the backend reads ai_events only, so an early read of a node from a trace past the ai_events
// retention misses. The node stays loading and is read again once the trace's timestamp is known.
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.test.ts b/products/ai_observability/frontend/redesign/trace/traceViewModelLogic.test.ts
similarity index 82%
rename from products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.test.ts
rename to products/ai_observability/frontend/redesign/trace/traceViewModelLogic.test.ts
index 183152a1b379..91d7df37dbd4 100644
--- a/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.test.ts
+++ b/products/ai_observability/frontend/redesign/trace/traceViewModelLogic.test.ts
@@ -1,19 +1,15 @@
import { waitFor } from '@testing-library/react'
-import { decodeParams, router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { urls } from 'scenes/urls'
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { useMocks } from '~/mocks/jest'
import { performQuery } from '~/queries/query'
import { initKeaTests } from '~/test/init'
-import { aiObservabilityTraceLogic } from '../../../aiObservabilityTraceLogic'
-import type { TraceApi, TraceEvaluationResultsApi } from '../../../generated/api.schemas'
-import { traceSummaryLogic } from '../traceSummaryLogic'
+import type { TraceApi, TraceEvaluationResultsApi } from '../../generated/api.schemas'
import {
decodeIdSegment,
makeEvaluationResults,
@@ -21,8 +17,11 @@ import {
makeNodeDetail,
makeTraceCluster,
makeTraceResource,
-} from './testFixtures'
-import { traceViewAdapterLogic } from './traceViewAdapterLogic'
+} from './adapter/testFixtures'
+import { traceSummaryLogic } from './traceSummaryLogic'
+import { traceViewHostLogic } from './traceViewHostLogic'
+import { traceViewModelLogic } from './traceViewModelLogic'
+import type { TraceOpeningMode } from './types'
jest.mock('~/queries/query', () => ({ ...jest.requireActual('~/queries/query'), performQuery: jest.fn() }))
@@ -34,6 +33,7 @@ const CREATED_AT = '2026-09-01T10:15:00Z'
const FEEDBACK_URL = '/api/projects/:team_id/ai_observability/traces/:id/feedback/'
const SEARCH_URL = '/api/projects/:team_id/ai_observability/traces/:id/search/'
const SUMMARY_URL = '/api/projects/:team_id/ai_observability/traces/:id/summary/'
+const HOST_ID = 'test-host'
const answeredGeneration = makeNodeDetail({
id: 'gen-2',
@@ -44,8 +44,15 @@ const answeredGeneration = makeNodeDetail({
ioKeys: { input: '$ai_input', output: '$ai_output_choices' },
})
-describe('traceViewAdapterLogic', () => {
- let logic: ReturnType<typeof traceViewAdapterLogic.build>
+interface HostState {
+ requestedStepId?: string
+ openingMode?: TraceOpeningMode
+ seedQuery?: string
+}
+
+describe('traceViewModelLogic', () => {
+ let logic: ReturnType<typeof traceViewModelLogic.build>
+ let host: ReturnType<typeof traceViewHostLogic.build>
let traceResource: TraceApi
let traceGate: Promise<void>
let nodeRequests: string[]
@@ -57,10 +64,21 @@ describe('traceViewAdapterLogic', () => {
let summaryRequests: number
let evaluations: TraceEvaluationResultsApi
- function mountAt(params: Record<string, string> = {}): void {
- router.actions.push(urls.aiObservabilityTrace('trace-1', params))
- logic = traceViewAdapterLogic({ traceId: 'trace-1', timestampHint: null })
+ function mountAt({ requestedStepId, openingMode, seedQuery }: HostState = {}): void {
+ host = traceViewHostLogic({ hostId: HOST_ID })
+ host.mount()
+ host.actions.requestStep(requestedStepId ?? null)
+ host.actions.setOpeningMode(openingMode ?? null)
+ host.actions.setSeedQuery(seedQuery ?? '')
+ logic = traceViewModelLogic({ hostId: HOST_ID, traceId: 'trace-1', timestampHint: null })
+ logic.mount()
+ }
+
+ function stepTo(traceId: string): void {
+ const previous = logic
+ logic = traceViewModelLogic({ hostId: HOST_ID, traceId, timestampHint: null })
logic.mount()
+ previous.unmount()
}
beforeEach(() => {
@@ -119,7 +137,7 @@ describe('traceViewAdapterLogic', () => {
if (nodeId === 'gen-2') {
return [200, answeredGeneration]
}
- const known = ['trace-1', 'span-1', 'gen-1'].includes(nodeId)
+ const known = ['trace-1', 'trace-2', 'span-1', 'gen-1'].includes(nodeId)
return known ? [200, makeNodeDetail({ id: nodeId })] : [404, { detail: 'Node not found.' }]
},
},
@@ -127,12 +145,12 @@ describe('traceViewAdapterLogic', () => {
initKeaTests()
jest.mocked(performQuery).mockReset()
jest.mocked(performQuery).mockResolvedValue({ results: [] })
- aiObservabilityTraceLogic.mount()
})
afterEach(() => {
resumeKeaLoadersErrors()
logic.unmount()
+ host.unmount()
resumeKeaLoadersErrors()
jest.restoreAllMocks()
})
@@ -142,7 +160,7 @@ describe('traceViewAdapterLogic', () => {
traceGate = new Promise<void>((resolve) => {
releaseTrace = resolve
})
- mountAt({ event: 'span-1' })
+ mountAt({ requestedStepId: 'span-1' })
await waitFor(() => expect(nodeRequests).toEqual(['span-1']))
expect(logic.values.status).toBe('loading')
@@ -155,27 +173,19 @@ describe('traceViewAdapterLogic', () => {
})
it.each([
- ['a node in the tree', { event: 'span-1' }, 'span-1'],
- ['an SDK id through its alias', { event: 'sdk-gen-1' }, 'gen-1'],
- ['a stale id as the root', { event: 'missing' }, 'trace-1'],
+ ['a node in the tree', { requestedStepId: 'span-1' }, 'span-1'],
+ ['an SDK id through its alias', { requestedStepId: 'sdk-gen-1' }, 'gen-1'],
+ ['a stale id as the root', { requestedStepId: 'missing' }, 'trace-1'],
['no id as the default node', {}, 'gen-1'],
- ['a trace-level link as the root', { tab: 'summary' }, 'trace-1'],
- ])('selects %s', async (_name, params: Record<string, string>, expected) => {
+ ['a trace-level link as the root', { openingMode: 'summary' }, 'trace-1'],
+ ] as const)('selects %s', async (_name, state: HostState, expected) => {
traceResource = makeTraceResource({ defaultNodeId: 'gen-1', nodeIdsByAlias: { 'sdk-gen-1': 'gen-1' } })
- mountAt(params)
+ mountAt(state)
await expectLogic(logic).toFinishAllListeners().toMatchValues({ selectedNodeId: expected })
expect(logic.values.detailData?.content.kind).not.toBe('error')
})
- it('asks for the neighbours once the trace arrives', async () => {
- mountAt()
-
- await expectLogic(logic).toDispatchActions([
- aiObservabilityTraceLogic.actionCreators.loadNeighbors('trace-1', '2026-09-01T10:15:00Z'),
- ])
- })
-
it('asks for the clusters with the trace start once the trace arrives', async () => {
let releaseTrace = (): void => {}
traceGate = new Promise<void>((resolve) => {
@@ -271,7 +281,7 @@ describe('traceViewAdapterLogic', () => {
'reads a failed node again when %s picks it again',
async (select) => {
failingNodeId = 'span-1'
- mountAt({ event: 'span-1' })
+ mountAt({ requestedStepId: 'span-1' })
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.detailData?.content.kind).toBe('error')
@@ -376,67 +386,34 @@ describe('traceViewAdapterLogic', () => {
})
})
- it('reads the search from the link and keeps the list it came from', async () => {
- mountAt({ search: 'invoice', back_to: 'generations' })
+ it('takes the search from the host, then follows its changes', async () => {
+ mountAt({ seedQuery: 'invoice' })
await expectLogic(logic)
.toFinishAllListeners()
- .toMatchValues({
- searchBox: expect.objectContaining({ query: 'invoice', status: 'ready', total: 3 }),
- backLink: expect.objectContaining({ label: 'Back to generations' }),
- })
+ .toMatchValues({ searchBox: expect.objectContaining({ query: 'invoice', status: 'ready', total: 3 }) })
+
+ host.actions.setSeedQuery('refund')
+
+ expect(logic.values.query).toBe('refund')
})
- it('writes the settled search to the URL once, keeping the selection and the other params', async () => {
- mountAt({ back_to: 'generations', timestamp: '2026-09-01T10:15:00Z' })
+ it('publishes only the settled search to the host', async () => {
+ mountAt()
await expectLogic(logic).toFinishAllListeners()
- logic.actions.selectNode('gen-1')
- const replace = jest.spyOn(router.actions, 'replace')
await expectLogic(logic, () => {
logic.actions.setQuery('two')
logic.actions.setQuery('two words + 50%')
})
- .toDispatchActions(['setQuery', 'setQuery'])
+ .toDispatchActions(['setQuery'])
.toFinishAllListeners()
- .toNotHaveDispatchedActions(['setQuery'])
-
- expect(replace).toHaveBeenCalledTimes(1)
- expect(router.values.searchParams).toEqual({
- back_to: 'generations',
- timestamp: '2026-09-01T10:15:00Z',
- search: 'two words + 50%',
- event: 'gen-1',
- })
- expect(logic.values.selectedNodeId).toBe('gen-1')
- })
-
- it.each(['1.50', '[draft]'])('keeps the typed search %s when the browser restores its URL', async (query) => {
- mountAt()
- await expectLogic(logic).toFinishAllListeners()
- logic.actions.setQuery(query)
- await expectLogic(logic).toFinishAllListeners()
-
- const { pathname, search } = router.values.location
-
- // Back and forward decode the URL again, as a page load does.
- await expectLogic(logic, () => {
- router.actions.locationChanged({
- method: 'POP',
- pathname,
- search,
- searchParams: decodeParams(search, '?'),
- hash: '',
- hashParams: {},
- url: `${pathname}${search}`,
- })
- }).toFinishAllListeners()
-
- expect(logic.values.query).toBe(query)
+ .toNotHaveDispatchedActions([host.actionCreators.publishQuery('two')])
+ .toDispatchActions([host.actionCreators.publishQuery('two words + 50%')])
})
it('steps to the next match from another mode and shows it in spans', async () => {
- mountAt({ search: 'invoice' })
+ mountAt({ seedQuery: 'invoice' })
await expectLogic(logic).toFinishAllListeners()
logic.actions.setMode('thread')
@@ -447,22 +424,8 @@ describe('traceViewAdapterLogic', () => {
})
})
- it('keeps the selection in the URL while a search is active', async () => {
- mountAt()
- await expectLogic(logic).toFinishAllListeners()
- logic.actions.selectNode('gen-1')
- logic.actions.setQuery('invoice')
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.stepMatch('next')
- expect(router.values.searchParams).toMatchObject({ search: 'invoice', event: 'gen-2' })
-
- logic.actions.selectNode('span-1')
- expect(router.values.searchParams).toMatchObject({ search: 'invoice', event: 'span-1' })
- })
-
it('steps to the first match from a mode that does not show the selected step', async () => {
- mountAt({ search: 'invoice' })
+ mountAt({ seedQuery: 'invoice' })
await expectLogic(logic).toFinishAllListeners()
logic.actions.selectNode('gen-1')
logic.actions.setMode('thread')
@@ -475,7 +438,7 @@ describe('traceViewAdapterLogic', () => {
it('drops the previous matches when a newer search fails', async () => {
silenceKeaLoadersErrors()
- mountAt({ search: 'invoice' })
+ mountAt({ seedQuery: 'invoice' })
await expectLogic(logic).toFinishAllListeners()
searchStatus = 504
@@ -521,19 +484,57 @@ describe('traceViewAdapterLogic', () => {
})
it('a trace-level summary link opens the Summary mode without requesting a summary', async () => {
- mountAt({ tab: 'summary' })
+ mountAt({ openingMode: 'summary' })
const summary = traceSummaryLogic({ traceId: 'trace-1' })
- await expectLogic(summary).toDispatchActions([summary.actionCreators.openSummary('link'), 'loadSummarySuccess'])
+ await expectLogic(summary)
+ .toDispatchActions([summary.actionCreators.openSummary('link')])
+ .toNotHaveDispatchedActions([summary.actionCreators.openSummary('tab')])
+ .toDispatchActions(['loadSummarySuccess'])
expect(logic.values).toMatchObject({ mode: 'summary', summaryState: { status: 'none' } })
expect(summaryRequests).toBe(0)
})
it('a summary link that names a step opens that step instead of the Summary mode', async () => {
- mountAt({ tab: 'summary', event: 'gen-1' })
+ mountAt({ openingMode: 'summary', requestedStepId: 'gen-1' })
await expectLogic(logic).toFinishAllListeners().toMatchValues({ mode: 'spans', selectedNodeId: 'gen-1' })
expect(traceSummaryLogic({ traceId: 'trace-1' }).values.isOpen).toBe(false)
})
+
+ it('opens the summary of a new trace when the mode carries over', async () => {
+ mountAt()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setMode('summary')
+
+ stepTo('trace-2')
+
+ const summary = traceSummaryLogic({ traceId: 'trace-2' })
+ await expectLogic(summary).toDispatchActions([summary.actionCreators.openSummary('tab'), 'loadSummarySuccess'])
+ expect(summary.values.isOpen).toBe(true)
+ expect(summaryRequests).toBe(0)
+ })
+
+ it('keeps mode and step tab when the trace changes', async () => {
+ mountAt()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setMode('timeline')
+ logic.actions.setDetailTab('evals')
+
+ stepTo('trace-2')
+
+ expect(logic.values).toMatchObject({ mode: 'timeline', detailTab: 'evals' })
+ })
+
+ it('starts the next trace without the search query', async () => {
+ mountAt()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setQuery('invoice')
+ await expectLogic(logic).toFinishAllListeners()
+
+ stepTo('trace-2')
+
+ expect(logic.values.query).toBe('')
+ })
})
diff --git a/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.ts b/products/ai_observability/frontend/redesign/trace/traceViewModelLogic.ts
similarity index 72%
rename from products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.ts
rename to products/ai_observability/frontend/redesign/trace/traceViewModelLogic.ts
index 81195fa3a841..971ad1bc05c6 100644
--- a/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.ts
+++ b/products/ai_observability/frontend/redesign/trace/traceViewModelLogic.ts
@@ -1,18 +1,13 @@
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
-import { router, urlToAction } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { tryDecodeURIComponent } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
-import { urls } from 'scenes/urls'
import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'
-import { aiObservabilityTraceLogic } from '../../../aiObservabilityTraceLogic'
-import type { SaveToDatasetButtonProps } from '../../../datasets/SaveToDatasetButton'
import type {
TraceApi,
TraceClusterApi,
@@ -22,18 +17,28 @@ import type {
TracePullRequestApi,
TraceSearchResultsApi,
TraceTimelineRowApi,
-} from '../../../generated/api.schemas'
-import { GitBranchChipProps } from '../components/GitBranchChip'
-import { TraceClustersChipProps } from '../components/TraceClustersChip'
-import { TraceHeaderProps } from '../components/TraceHeader'
-import type { TraceSearchBoxData } from '../components/TraceSearchBox'
-import { TraceSummaryBarProps } from '../components/TraceSummaryBar'
-import { traceClustersLogic } from '../traceClustersLogic'
-import { traceFeedbackLogic } from '../traceFeedbackLogic'
-import { traceGitPullRequestLogic } from '../traceGitPullRequestLogic'
-import { SEARCH_DEBOUNCE_MS, traceSearchLogic } from '../traceSearchLogic'
-import { traceSummaryLogic } from '../traceSummaryLogic'
-import { TraceViewStatus, traceViewLogic } from '../traceViewLogic'
+} from '../../generated/api.schemas'
+import { toClustersChip } from './adapter/toClustersChip'
+import { toDatasetItemSource } from './adapter/toDatasetItemSource'
+import { firstFailingNodeId, toEvalOutcomesByNode, toEvalsChip } from './adapter/toEvalSummary'
+import { stepFeedbackOf, toFeedbackChip, toFeedbackMode, toStepFeedback } from './adapter/toFeedback'
+import { toGitPullRequestLink } from './adapter/toGitPullRequestLink'
+import { NodeDetailData, toNodeDetail } from './adapter/toNodeDetail'
+import { steppedMatchId, toMatchingNodeIds, toSearchBox } from './adapter/toSearch'
+import { toThread } from './adapter/toThread'
+import { findTreeNode } from './adapter/toTraceTree'
+import { GitBranchChipProps } from './components/GitBranchChip'
+import { TraceClustersChipProps } from './components/TraceClustersChip'
+import { TraceHeaderProps } from './components/TraceHeader'
+import type { TraceSearchBoxData } from './components/TraceSearchBox'
+import { TraceSummaryBarProps } from './components/TraceSummaryBar'
+import { traceClustersLogic } from './traceClustersLogic'
+import { traceFeedbackLogic } from './traceFeedbackLogic'
+import { traceGitPullRequestLogic } from './traceGitPullRequestLogic'
+import { SEARCH_DEBOUNCE_MS, traceSearchLogic } from './traceSearchLogic'
+import { traceSummaryLogic } from './traceSummaryLogic'
+import { traceViewHostLogic } from './traceViewHostLogic'
+import { TraceViewStatus, traceViewLogic } from './traceViewLogic'
import {
ConversationState,
EvalRollupOutcome,
@@ -41,7 +46,6 @@ import {
FeedbackChipData,
FeedbackEntry,
FeedbackModeState,
- LabeledLink,
MatchDirection,
NodeDetailTab,
NodeLoad,
@@ -50,43 +54,21 @@ import {
SummaryModeState,
SummaryRequestError,
TraceMode,
+ TraceOpeningMode,
TraceSearchFailure,
TraceSearchStatus,
-} from '../types'
-import { toClustersChip } from './toClustersChip'
-import { toDatasetItemSource } from './toDatasetItemSource'
-import { firstFailingNodeId, toEvalOutcomesByNode, toEvalsChip } from './toEvalSummary'
-import { stepFeedbackOf, toFeedbackChip, toFeedbackMode, toStepFeedback } from './toFeedback'
-import { toGitPullRequestLink } from './toGitPullRequestLink'
-import { toBackLink, toHeader } from './toHeader'
-import { NodeDetailData, toNodeDetail } from './toNodeDetail'
-import { steppedMatchId, toMatchingNodeIds, toSearchBox } from './toSearch'
-import { toThread } from './toThread'
-import { findTreeNode } from './toTraceTree'
+} from './types'
-// kea-router reads a numeric param as a number, which turns a typed `1.50` into `1.5`. It also pads a value shaped like
-// a JSON array or object with one space, so it reads that value back as a string.
-function searchParamFromUrl(): string {
- const value = new URLSearchParams(router.values.location.search).get('search') ?? ''
- return /^(\[.*\]|\{.*\}) +$/.test(value) ? value.slice(0, -1) : value
-}
-
-export interface TraceViewAdapterLogicProps {
+export interface TraceViewModelLogicProps {
+ hostId: string
traceId: string
timestampHint: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface traceViewAdapterLogicValues {
+export interface traceViewModelLogicValues {
summaryConsentGiven: boolean // aiConsentLogic
- eventId: string | null // aiObservabilityTraceLogic
- initialTab: string | null // aiObservabilityTraceLogic
- newerTimestamp: string | null // aiObservabilityTraceLogic
- newerTraceId: string | null // aiObservabilityTraceLogic
- olderTimestamp: string | null // aiObservabilityTraceLogic
- olderTraceId: string | null // aiObservabilityTraceLogic
featureFlags: FeatureFlagsSet // featureFlagLogic
- searchParams: Record<string, any> // router
currentTeamId: number | null // teamLogic
clusters: TraceClusterApi[] | null // traceClustersLogic
traceFeedback: TraceFeedbackApi | null // traceFeedbackLogic
@@ -96,9 +78,15 @@ export interface traceViewAdapterLogicValues {
searchFailure: TraceSearchFailure | null // traceSearchLogic
searchResults: TraceSearchResultsApi | null // traceSearchLogic
searchStatus: TraceSearchStatus // traceSearchLogic
+ summaryIsOpen: boolean // traceSummaryLogic
summaryRequestError: SummaryRequestError | null // traceSummaryLogic
summaryRequesting: boolean // traceSummaryLogic
summaryState: SummaryModeState // traceSummaryLogic
+ detailTab: NodeDetailTab // traceViewHostLogic
+ mode: TraceMode // traceViewHostLogic
+ openingMode: TraceOpeningMode // traceViewHostLogic
+ requestedStepId: string | null // traceViewHostLogic
+ seedQuery: string // traceViewHostLogic
createdAt: string | null // traceViewLogic
defaultNodeId: string // traceViewLogic
errorMessage: string // traceViewLogic
@@ -119,12 +107,10 @@ export interface traceViewAdapterLogicValues {
traceHasError: boolean // traceViewLogic
traceName: string // traceViewLogic
tree: TraceNodeApi[] // traceViewLogic
- backLink: LabeledLink
canViewInThread: boolean
clustersChip: TraceClustersChipProps | null
- datasetItemSource: SaveToDatasetButtonProps | null
+ datasetItemSource: ReturnType<typeof toDatasetItemSource>
detailData: NodeDetailData | null
- detailTab: NodeDetailTab
evalOutcomesByNode: Record<string, EvalRollupOutcome>
evalsChip: EvalsChipData | null
feedbackChip: FeedbackChipData | null
@@ -133,11 +119,10 @@ export interface traceViewAdapterLogicValues {
feedbackFocusNodeId: string | null
feedbackMode: FeedbackModeState
gitBranch: GitBranchChipProps | null
- header: TraceHeaderProps
+ header: Pick<TraceHeaderProps, 'hasError' | 'name'>
highlightQuery: string | null
matchStepCount: number
matchingNodeIds: ReadonlySet<string> | null
- mode: TraceMode
readySearchResults: TraceSearchResultsApi | null
searchBox: TraceSearchBoxData
selectedNodeId: string
@@ -151,17 +136,7 @@ export interface traceViewAdapterLogicValues {
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface traceViewAdapterLogicActions {
- loadNeighbors: (
- traceId: string,
- timestamp: string
- ) => {
- timestamp: string
- traceId: string
- } // aiObservabilityTraceLogic
- setEventId: (eventId: string | null) => {
- eventId: string | null
- } // aiObservabilityTraceLogic
+export interface traceViewModelLogicActions {
loadClusters: (createdAt: string) => string // traceClustersLogic
retryTraceFeedback: () => {
value: true
@@ -173,18 +148,30 @@ export interface traceViewAdapterLogicActions {
value: true
} // traceSummaryLogic
loadSummary: (_?: void | undefined) => void // traceSummaryLogic
- openSummary: (openedFrom: import('../traceSummaryLogic').SummaryOpenedFrom) => {
- openedFrom: import('../traceSummaryLogic').SummaryOpenedFrom
+ openSummary: (openedFrom: import('./traceSummaryLogic').SummaryOpenedFrom) => {
+ openedFrom: import('./traceSummaryLogic').SummaryOpenedFrom
} // traceSummaryLogic
requestSummary: (
- args_0: import('../traceSummaryLogic').SummaryRequest
- ) => import('../traceSummaryLogic').SummaryRequest // traceSummaryLogic
+ args_0: import('./traceSummaryLogic').SummaryRequest
+ ) => import('./traceSummaryLogic').SummaryRequest // traceSummaryLogic
+ publishQuery: (query: string) => {
+ query: string
+ } // traceViewHostLogic
+ requestStep: (stepId: string | null) => {
+ stepId: string | null
+ } // traceViewHostLogic
+ setHostDetailTab: (tab: NodeDetailTab) => {
+ tab: NodeDetailTab
+ } // traceViewHostLogic
+ setHostMode: (mode: TraceMode) => {
+ mode: TraceMode
+ } // traceViewHostLogic
loadNode: (
nodeId: string,
- trigger: import('../types').NodeLoadTrigger
+ trigger: import('./types').NodeLoadTrigger
) => {
nodeId: string
- trigger: import('../types').NodeLoadTrigger
+ trigger: import('./types').NodeLoadTrigger
} // traceViewLogic
loadTraceSuccess: (
trace: TraceApi,
@@ -243,12 +230,12 @@ export interface traceViewAdapterLogicActions {
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface traceViewAdapterLogicMeta {
+export interface traceViewModelLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
selectedNodeId: (
- eventId: string | null,
- initialTab: string | null,
+ requestedStepId: string | null,
+ openingMode: TraceOpeningMode,
tree: TraceNodeApi[],
status: TraceViewStatus,
defaultNodeId: string,
@@ -258,16 +245,7 @@ export interface traceViewAdapterLogicMeta {
selectedTreeNode: (tree: TraceNodeApi[], selectedNodeId: string) => TraceNodeApi | null
selectedNodeLoad: (selectedNodeId: string, nodes: Record<string, NodeLoad>) => NodeLoad
threadNodeLoad: (threadNodeIds: string[], nodes: Record<string, NodeLoad>) => NodeLoad | null
- backLink: (searchParams: Record<string, any>) => LabeledLink
- header: (
- traceName: string,
- traceHasError: boolean,
- olderTraceId: string | null,
- olderTimestamp: string | null,
- newerTraceId: string | null,
- newerTimestamp: string | null,
- searchParams: Record<string, any>
- ) => TraceHeaderProps
+ header: (traceName: string, traceHasError: boolean) => Pick<TraceHeaderProps, 'hasError' | 'name'>
detailData: (
selectedTreeNode: TraceNodeApi | null,
selectedNodeLoad: NodeLoad,
@@ -284,7 +262,7 @@ export interface traceViewAdapterLogicMeta {
selectedNodeLoad: NodeLoad,
createdAt: string | null,
traceId: string
- ) => SaveToDatasetButtonProps | null
+ ) => ReturnType<typeof toDatasetItemSource>
thread: (
status: TraceViewStatus,
threadNodeLoad: NodeLoad | null,
@@ -329,22 +307,22 @@ export interface traceViewAdapterLogicMeta {
}
}
-export type traceViewAdapterLogicType = MakeLogicType<
- traceViewAdapterLogicValues,
- traceViewAdapterLogicActions,
- TraceViewAdapterLogicProps,
- traceViewAdapterLogicMeta
+export type traceViewModelLogicType = MakeLogicType<
+ traceViewModelLogicValues,
+ traceViewModelLogicActions,
+ TraceViewModelLogicProps,
+ traceViewModelLogicMeta
>
const LOADING: NodeLoad = { status: 'loading' }
// Skimming the tree with the pointer must not start a read for every row it crosses.
const PREFETCH_DELAY_MS = 75
-export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([
- path((key) => ['products', 'ai_observability', 'frontend', 'redesign', 'trace', 'traceViewAdapterLogic', key]),
- props({} as TraceViewAdapterLogicProps),
- key((props) => props.traceId),
- connect((props: TraceViewAdapterLogicProps) => ({
+export const traceViewModelLogic = kea<traceViewModelLogicType>([
+ path((key) => ['products', 'ai_observability', 'frontend', 'redesign', 'trace', 'traceViewModelLogic', key]),
+ props({} as TraceViewModelLogicProps),
+ key((props) => `${props.hostId}/${props.traceId}`),
+ connect((props: TraceViewModelLogicProps) => ({
values: [
traceViewLogic({ traceId: props.traceId, timestampHint: props.timestampHint }),
[
@@ -366,12 +344,10 @@ export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([
'evaluationResultsFailed',
'trace',
],
- aiObservabilityTraceLogic,
- ['eventId', 'initialTab', 'olderTraceId', 'olderTimestamp', 'newerTraceId', 'newerTimestamp'],
+ traceViewHostLogic({ hostId: props.hostId }),
+ ['mode', 'detailTab', 'requestedStepId', 'openingMode', 'seedQuery'],
teamLogic,
['currentTeamId'],
- router,
- ['searchParams'],
featureFlagLogic,
['featureFlags'],
traceClustersLogic({ traceId: props.traceId }),
@@ -381,15 +357,20 @@ export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([
traceSearchLogic({ traceId: props.traceId, timestampHint: props.timestampHint }),
['query', 'searchResults', 'searchStatus', 'searchFailure'],
traceSummaryLogic({ traceId: props.traceId }),
- ['state as summaryState', 'requesting as summaryRequesting', 'requestError as summaryRequestError'],
+ [
+ 'state as summaryState',
+ 'requesting as summaryRequesting',
+ 'requestError as summaryRequestError',
+ 'isOpen as summaryIsOpen',
+ ],
aiConsentLogic,
['dataProcessingAccepted as summaryConsentGiven'],
traceGitPullRequestLogic({ traceId: props.traceId, timestampHint: props.timestampHint }),
['pullRequest'],
],
actions: [
- aiObservabilityTraceLogic,
- ['setEventId', 'loadNeighbors'],
+ traceViewHostLogic({ hostId: props.hostId }),
+ ['setMode as setHostMode', 'setDetailTab as setHostDetailTab', 'requestStep', 'publishQuery'],
traceViewLogic({ traceId: props.traceId, timestampHint: props.timestampHint }),
['loadNode', 'loadTraceSuccess'],
traceClustersLogic({ traceId: props.traceId }),
@@ -418,17 +399,6 @@ export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([
summaryStepClicked: (nodeId: string, kind: SummaryItemKind) => ({ nodeId, kind }),
}),
reducers({
- mode: [
- 'spans' as TraceMode,
- {
- setMode: (_, { mode }) => mode,
- selectAndShowSpans: () => 'spans',
- viewInThread: () => 'thread',
- showFeedback: () => 'feedback',
- openSummaryFromLink: () => 'summary',
- },
- ],
- detailTab: ['messages' as NodeDetailTab, { setDetailTab: (_, { tab }) => tab }],
feedbackFocusNodeId: [
null as string | null,
{
@@ -442,10 +412,18 @@ export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([
}),
selectors({
selectedNodeId: [
- (s, p) => [s.eventId, s.initialTab, s.tree, s.status, s.defaultNodeId, s.nodeIdsByAlias, p.traceId],
+ (s, p) => [
+ s.requestedStepId,
+ s.openingMode,
+ s.tree,
+ s.status,
+ s.defaultNodeId,
+ s.nodeIdsByAlias,
+ p.traceId,
+ ],
(
- eventId: string | null,
- initialTab: string | null,
+ requestedStepId: string | null,
+ openingMode: TraceOpeningMode,
tree: TraceNodeApi[],
status: TraceViewStatus,
defaultNodeId: string,
@@ -453,16 +431,16 @@ export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([
traceId: string
): string => {
if (status !== 'ready') {
- return eventId ?? traceId
+ return requestedStepId ?? traceId
}
- if (!eventId) {
- // Trace-level links from clusters and sessions ask for the trace itself with tab=summary.
- return initialTab === 'summary' ? traceId : defaultNodeId
+ if (!requestedStepId) {
+ // Trace-level links from clusters and sessions ask for the trace itself in the Summary mode.
+ return openingMode === 'summary' ? traceId : defaultNodeId
}
- if (findTreeNode(tree, eventId)) {
- return eventId
+ if (findTreeNode(tree, requestedStepId)) {
+ return requestedStepId
}
- return nodeIdsByAlias[eventId] ?? traceId
+ return nodeIdsByAlias[requestedStepId] ?? traceId
},
],
selectedTreeNode: [
@@ -479,34 +457,12 @@ export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([
(threadNodeIds: string[], nodes: Record<string, NodeLoad>): NodeLoad | null =>
threadNodeIds[0] ? (nodes[threadNodeIds[0]] ?? LOADING) : null,
],
- backLink: [
- (s) => [s.searchParams],
- (searchParams: Record<string, unknown>): LabeledLink => toBackLink(searchParams),
- ],
header: [
- (s) => [
- s.traceName,
- s.traceHasError,
- s.olderTraceId,
- s.olderTimestamp,
- s.newerTraceId,
- s.newerTimestamp,
- s.searchParams,
- ],
- (
- traceName: string,
- traceHasError: boolean,
- olderTraceId: string | null,
- olderTimestamp: string | null,
- newerTraceId: string | null,
- newerTimestamp: string | null,
- searchParams: Record<string, unknown>
- ): TraceHeaderProps =>
- toHeader(
- { name: traceName, hasError: traceHasError },
- { olderTraceId, olderTimestamp, newerTraceId, newerTimestamp },
- searchParams
- ),
+ (s) => [s.traceName, s.traceHasError],
+ (traceName: string, traceHasError: boolean): Pick<TraceHeaderProps, 'name' | 'hasError'> => ({
+ name: traceName,
+ hasError: traceHasError,
+ }),
],
detailData: [
(s) => [
@@ -551,7 +507,7 @@ export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([
load: NodeLoad,
createdAt: string | null,
traceId: string
- ): SaveToDatasetButtonProps | null =>
+ ): ReturnType<typeof toDatasetItemSource> =>
featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_DATASETS] && createdAt
? toDatasetItemSource({ traceId, createdAt, load })
: null,
@@ -671,25 +627,13 @@ export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([
(query: string, status: TraceSearchStatus): string | null => (status === 'ready' ? query.trim() : null),
],
}),
- listeners(({ actions, values, selectors, props }) => {
+ listeners(({ actions, values, props }) => {
// The click's read starts before the selection moves, so the selectedNodeId subscription's navigation read
// for the same id is deduped and the load event reports a click. Selecting the node that is already
// selected changes no value and the subscription does not fire, so this read also retries a failed node.
- // The legacy logic resets its selection from the URL on every location change, so a URL that carries the
- // search carries the selection too. Each change also records a product intent there.
- const writeUrl = (query: string): void => {
- router.actions.replace(
- urls.aiObservabilityTrace(props.traceId),
- { ...values.searchParams, search: query || undefined, event: values.eventId ?? undefined },
- router.values.hashParams
- )
- }
const select = ({ id }: { id: string }): void => {
actions.loadNode(id, 'selection')
- actions.setEventId(id)
- if (values.query.trim() && values.searchParams.event !== id) {
- writeUrl(values.query)
- }
+ actions.requestStep(id)
}
const captureFeedbackViewed = (entry: FeedbackEntry | 'tab'): void => {
posthog.capture('llma trace view feedback viewed', {
@@ -699,38 +643,32 @@ export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([
unanswered: values.traceFeedback?.unanswered.length ?? null,
})
}
- const syncSummary = (previousMode: TraceMode): void => {
- const wasOpen = previousMode === 'summary'
- if (values.mode === 'summary' && !wasOpen) {
- actions.openSummary('tab')
- } else if (values.mode !== 'summary' && wasOpen) {
- actions.closeSummary()
- }
- }
const requestSummary = (regenerate: boolean): void => {
actions.requestSummary({ regenerate, timestampHint: values.createdAt })
}
return {
- viewInThread: (_, __, ___, previousState) => syncSummary(selectors.mode(previousState)),
+ viewInThread: () => actions.setHostMode('thread'),
selectNode: select,
- selectAndShowSpans: (payload, __, ___, previousState) => {
+ selectAndShowSpans: (payload) => {
select(payload)
- syncSummary(selectors.mode(previousState))
+ actions.setHostMode('spans')
},
prefetchNode: async ({ id }, breakpoint) => {
await breakpoint(PREFETCH_DELAY_MS)
actions.loadNode(id, 'prefetch')
},
loadTraceSuccess: ({ trace }) => {
- actions.loadNeighbors(props.traceId, trace.createdAt)
actions.loadClusters(trace.createdAt)
- // Cluster and session pages link to a trace with tab=summary. The mode opens without generating.
+ // Cluster and session pages link to a trace in the Summary mode. The mode opens without generating.
// A link that also names a step opens that step, because the Summary mode covers the whole trace.
- if (values.initialTab === 'summary' && values.mode !== 'summary' && !values.eventId) {
+ if (values.openingMode === 'summary' && values.mode !== 'summary' && !values.requestedStepId) {
actions.openSummaryFromLink()
}
},
- openSummaryFromLink: () => actions.openSummary('link'),
+ openSummaryFromLink: () => {
+ actions.openSummary('link')
+ actions.setHostMode('summary')
+ },
summarize: () => requestSummary(false),
regenerateSummary: () => requestSummary(true),
summaryStepClicked: ({ nodeId, kind }) => {
@@ -744,39 +682,42 @@ export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([
actions.selectAndShowSpans(id)
}
},
- // The URL follows the debounced query rather than each keystroke.
+ // The host follows the debounced query rather than each keystroke.
setQuery: async ({ query }, breakpoint) => {
await breakpoint(SEARCH_DEBOUNCE_MS)
- if (searchParamFromUrl() !== query) {
- writeUrl(query)
- }
+ actions.publishQuery(query)
},
showFailingEvals: () => {
actions.selectAndShowSpans(firstFailingNodeId(values.tree, values.evalOutcomesByNode) ?? props.traceId)
actions.setDetailTab('evals')
},
- showFeedback: ({ entry }, __, ___, previousState) => {
+ showFeedback: ({ entry }) => {
captureFeedbackViewed(entry)
- syncSummary(selectors.mode(previousState))
+ actions.setHostMode('feedback')
},
- setMode: ({ mode }, __, ___, previousState) => {
- const previousMode = selectors.mode(previousState)
- syncSummary(previousMode)
+ setMode: ({ mode }) => {
+ const previousMode = values.mode
+ actions.setHostMode(mode)
if (mode === 'feedback' && previousMode !== 'feedback') {
captureFeedbackViewed('tab')
}
},
+ setDetailTab: ({ tab }) => actions.setHostDetailTab(tab),
}
}),
- urlToAction(({ actions, values, props }) => ({
- [`${urls.aiObservabilityTraces()}/:id`]: ({ id }) => {
- const query = searchParamFromUrl()
- if (tryDecodeURIComponent(id ?? '') === props.traceId && query !== values.query) {
- actions.setQuery(query)
+ subscriptions(({ actions, values }) => ({
+ selectedNodeId: (selectedNodeId: string) => actions.loadNode(selectedNodeId, 'navigation'),
+ mode: (mode: TraceMode) => {
+ if (mode === 'summary' && !values.summaryIsOpen) {
+ actions.openSummary('tab')
+ } else if (mode !== 'summary' && values.summaryIsOpen) {
+ actions.closeSummary()
+ }
+ },
+ seedQuery: (seedQuery: string) => {
+ if (seedQuery !== values.query) {
+ actions.setQuery(seedQuery)
}
},
- })),
- subscriptions(({ actions }) => ({
- selectedNodeId: (selectedNodeId: string) => actions.loadNode(selectedNodeId, 'navigation'),
})),
])
diff --git a/products/ai_observability/frontend/redesign/trace/types.ts b/products/ai_observability/frontend/redesign/trace/types.ts
index 6eaf429ca548..87d6399e2d36 100644
--- a/products/ai_observability/frontend/redesign/trace/types.ts
+++ b/products/ai_observability/frontend/redesign/trace/types.ts
@@ -13,6 +13,7 @@ import type {
export type TraceNodeKind = TraceNodeApi['kind']
export type TraceMode = 'spans' | 'thread' | 'timeline' | 'summary' | 'feedback'
+export type TraceOpeningMode = 'summary' | null
export type TraceViewChoice = 'new' | 'legacy'