@langwatch/server 3.1.0-beta.21 → 3.1.0-beta.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/__init__.py +36 -0
  2. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/_logger.py +165 -0
  3. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/batch_clustering.py +153 -0
  4. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/build_response.py +77 -0
  5. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/constants.py +7 -0
  6. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/incremental_clustering.py +325 -0
  7. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/topic_naming.py +432 -0
  8. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/types.py +42 -0
  9. package/langevals/evaluators/topic_clustering/langevals_topic_clustering/utils.py +191 -0
  10. package/langevals/evaluators/topic_clustering/pyproject.toml +52 -0
  11. package/langevals/evaluators/topic_clustering/tests/test_topic_clustering.py +239 -0
  12. package/langevals/evaluators/topic_clustering/tests/test_topic_clustering_integration.py +97 -0
  13. package/langevals/evaluators/topic_clustering/tests/test_topic_naming.py +72 -0
  14. package/langevals/langevals/pytest_plugins/pass_rate_plugin.py +7 -1
  15. package/langevals/langevals/server.py +28 -0
  16. package/langevals/pyproject.toml +3 -0
  17. package/langevals/uv.lock +119 -20
  18. package/langwatch/dist/client/assets/{AnnotationsTable-BDAkYaz6.js → AnnotationsTable-uS_9SQ-g.js} +2 -2
  19. package/langwatch/dist/client/assets/{BatchEvaluationSummary-DMaQM_VB.js → BatchEvaluationSummary-DtFd8yKJ.js} +2 -2
  20. package/langwatch/dist/client/assets/{BudgetEditDrawer-CHaqmdIl.js → BudgetEditDrawer-CHEPz0hH.js} +2 -2
  21. package/langwatch/dist/client/assets/{ChartCard-D14PUg_d.js → ChartCard-s5fMPo7b.js} +2 -2
  22. package/langwatch/dist/client/assets/{ChatWindow-CRDnlP-Q.js → ChatWindow-C0XSteVJ.js} +2 -2
  23. package/langwatch/dist/client/assets/ChatWindow-DFEmNXQL.js +1 -0
  24. package/langwatch/dist/client/assets/{ConfirmDialog-CXIhncvW.js → ConfirmDialog-M94yLNvP.js} +2 -2
  25. package/langwatch/dist/client/assets/{ContactSalesBlock-CijLBwRC.js → ContactSalesBlock-CnnuZ8iI.js} +2 -2
  26. package/langwatch/dist/client/assets/{DSPyExperiment-B1YOL2m8.js → DSPyExperiment-CMA6lrlx.js} +2 -2
  27. package/langwatch/dist/client/assets/{FilterDisplay-BB0xWrLn.js → FilterDisplay-0S3NqCkq.js} +2 -2
  28. package/langwatch/dist/client/assets/{FormatMoney-w9vr_h0X.js → FormatMoney-CCygtAHg.js} +2 -2
  29. package/langwatch/dist/client/assets/{FoundryDrawer-CdJDXtpz.js → FoundryDrawer-B35xZ26C.js} +2 -2
  30. package/langwatch/dist/client/assets/{GatewayErrorPanel-DvE9U2dS.js → GatewayErrorPanel-BsaYQEie.js} +2 -2
  31. package/langwatch/dist/client/assets/{GatewayLayout-lv1p_6B5.js → GatewayLayout-LvwwrwMf.js} +2 -2
  32. package/langwatch/dist/client/assets/{GraphsLayout-BJ68J9e-.js → GraphsLayout-DJ-HI9N1.js} +2 -2
  33. package/langwatch/dist/client/assets/{GroupBindingInputRow-DebZBCnD.js → GroupBindingInputRow-CV-fBkX9.js} +2 -2
  34. package/langwatch/dist/client/assets/{MessagesTable-B6lYde-x.js → MessagesTable-9taaKCOZ.js} +2 -2
  35. package/langwatch/dist/client/assets/{NavigationFooter-CiOVzDUh.js → NavigationFooter-Dzvauw3l.js} +2 -2
  36. package/langwatch/dist/client/assets/{NoDataInfoBlock-quSW_MRm.js → NoDataInfoBlock-CLKl_wlX.js} +2 -2
  37. package/langwatch/dist/client/assets/{OpsPageShell-DJ1WlI6-.js → OpsPageShell-C_mTziRS.js} +2 -2
  38. package/langwatch/dist/client/assets/{OptimizationStudio-BlozXjcN.js → OptimizationStudio-D2zpsmJj.js} +8 -12
  39. package/langwatch/dist/client/assets/{PreconditionsField-BOfcWvmZ.js → PreconditionsField-WXB8kcTK.js} +2 -2
  40. package/langwatch/dist/client/assets/{SettingsLayout-CLCGxMAe.js → SettingsLayout--1gdEuhv.js} +2 -2
  41. package/langwatch/dist/client/assets/{SubscriptionPage-J8b2Zaj6.js → SubscriptionPage-B0ox_4kM.js} +2 -2
  42. package/langwatch/dist/client/assets/{VirtualKeySecretReveal-DR1VDLy7.js → VirtualKeySecretReveal-CRbI1dKQ.js} +2 -2
  43. package/langwatch/dist/client/assets/{WithPermissionGuard-DD8uo3UK.js → WithPermissionGuard-B4Jo8E5-.js} +2 -2
  44. package/langwatch/dist/client/assets/{__...path__-BZVaIayJ.js → __...path__-BF2zkD84.js} +2 -2
  45. package/langwatch/dist/client/assets/{_experiment_-B1aT-wS3.js → _experiment_-D02aoVQk.js} +2 -2
  46. package/langwatch/dist/client/assets/{_id_-oI_eq-I_.js → _id_-Ch8YmTiM.js} +2 -2
  47. package/langwatch/dist/client/assets/{_id_-DAqPuO73.js → _id_-D6ZvwHpH.js} +2 -2
  48. package/langwatch/dist/client/assets/{_id_-DUngklVb.js → _id_-DOC1ZkBm.js} +2 -2
  49. package/langwatch/dist/client/assets/{_id_-jFDAfbob.js → _id_-DfWwW6_N.js} +2 -2
  50. package/langwatch/dist/client/assets/{_id_-BKBrWGG0.js → _id_-DxUo4W7J.js} +2 -2
  51. package/langwatch/dist/client/assets/_not-found-COI3ShsR.js +1 -0
  52. package/langwatch/dist/client/assets/{_project_-Bt1tayHB.js → _project_-_UUt5Ar9.js} +2 -2
  53. package/langwatch/dist/client/assets/{_runId_-CfvnDt5H.js → _runId_-Dimwzp48.js} +2 -2
  54. package/langwatch/dist/client/assets/_slug_-BMvKBwS_.js +2 -0
  55. package/langwatch/dist/client/assets/{_slug_-DZAdl0QS.js → _slug_-CE6VoDSC.js} +2 -2
  56. package/langwatch/dist/client/assets/{_slug_-DmoWXjKT.js → _slug_-OiOLG1Mv.js} +2 -2
  57. package/langwatch/dist/client/assets/{_team_-DL_wKSWK.js → _team_-DKvmwO_5.js} +2 -2
  58. package/langwatch/dist/client/assets/{_workflow_-DcMXLPUe.js → _workflow_-FkilKiB-.js} +3 -3
  59. package/langwatch/dist/client/assets/{_workflow_-NI9bac7d.js → _workflow_-gJZppg3h.js} +2 -2
  60. package/langwatch/dist/client/assets/{access-audit-CFwNwusI.js → access-audit-xcUVYMMT.js} +2 -2
  61. package/langwatch/dist/client/assets/{agents-Di4XRwcn.js → agents-D32g91cu.js} +2 -2
  62. package/langwatch/dist/client/assets/{all-C273mlDB.js → all-vnREzDZj.js} +2 -2
  63. package/langwatch/dist/client/assets/{analytics-CEAcSf6B.js → analytics-DP6Y4Feh.js} +2 -2
  64. package/langwatch/dist/client/assets/{annotation-scores-CHfn4LQp.js → annotation-scores-CjD4CEB6.js} +2 -2
  65. package/langwatch/dist/client/assets/{annotations-CHZQrha6.js → annotations-1rVXiDRQ.js} +2 -2
  66. package/langwatch/dist/client/assets/{api-keys-BT7HExHM.js → api-keys-BJpKyuaz.js} +2 -2
  67. package/langwatch/dist/client/assets/{audit-log-BGk-51Dt.js → audit-log-BdUdZjxp.js} +2 -2
  68. package/langwatch/dist/client/assets/{authentication-DvwXfkp-.js → authentication-8mQB00CC.js} +2 -2
  69. package/langwatch/dist/client/assets/{authorize-tXpHrWyw.js → authorize-BpUueMNW.js} +2 -2
  70. package/langwatch/dist/client/assets/{authorize-CRu9xlpU.js → authorize-CbNBtmxW.js} +2 -2
  71. package/langwatch/dist/client/assets/{automations-CjDvz9Ak.js → automations-34KMkRxd.js} +2 -2
  72. package/langwatch/dist/client/assets/{billing-plans-FUqEPN62.js → billing-plans-BUQp08MI.js} +2 -2
  73. package/langwatch/dist/client/assets/{budgets-BV6_RHrs.js → budgets-CdelE8Hv.js} +2 -2
  74. package/langwatch/dist/client/assets/{cache-rules-CtYA79E_.js → cache-rules-D2m1QlNJ.js} +2 -2
  75. package/langwatch/dist/client/assets/choose-C0LdeUiH.js +2 -0
  76. package/langwatch/dist/client/assets/{command-bar-CaJygoez.js → command-bar-DUK45yin.js} +7 -9
  77. package/langwatch/dist/client/assets/custom-hBq2K4FJ.js +1 -0
  78. package/langwatch/dist/client/assets/{datasets-vLWpH84_.js → datasets-ErNNhmjg.js} +2 -2
  79. package/langwatch/dist/client/assets/{dejaview-DwVR3RGg.js → dejaview-BaD4_v90.js} +2 -2
  80. package/langwatch/dist/client/assets/{dist-SwV3YZv3.js → dist-Cds4Mqhj.js} +4 -6
  81. package/langwatch/dist/client/assets/{edit-CyxsmQmW.js → edit-DpT8ejBV.js} +2 -2
  82. package/langwatch/dist/client/assets/{evaluations-BfgeZMph.js → evaluations-BdQ2Dm2r.js} +2 -2
  83. package/langwatch/dist/client/assets/{evaluations-HSQIMvbX.js → evaluations-C90I4VAr.js} +2 -2
  84. package/langwatch/dist/client/assets/{evaluators-DLHVvnrh.js → evaluators-ig_ugRLt.js} +2 -2
  85. package/langwatch/dist/client/assets/{foundry-Ckq0WjPU.js → foundry-B-X_80pD.js} +2 -2
  86. package/langwatch/dist/client/assets/{gateway-CDSYPZ6w.js → gateway-CS_mtJx-.js} +2 -2
  87. package/langwatch/dist/client/assets/{groups-CCCRUqPj.js → groups-Bp90ChP3.js} +2 -2
  88. package/langwatch/dist/client/assets/{index-Bm6z2fM9.js → index-BEjGS0kI.js} +5 -5
  89. package/langwatch/dist/client/assets/{license-CHOarGWr.js → license-CgnlvyuI.js} +2 -2
  90. package/langwatch/dist/client/assets/{me-CBya_vXs.js → me-DEqhm_KC.js} +2 -2
  91. package/langwatch/dist/client/assets/{members-lIFLh-rh.js → members-CUJANDtH.js} +2 -2
  92. package/langwatch/dist/client/assets/{messages-CG9j8Dz8.js → messages-fQBfCjvp.js} +2 -2
  93. package/langwatch/dist/client/assets/{metrics-C9pzeaI6.js → metrics-DeIxebpD.js} +2 -2
  94. package/langwatch/dist/client/assets/{model-costs-Bc5uqjkl.js → model-costs-C1RbgK--.js} +2 -2
  95. package/langwatch/dist/client/assets/{model-providers-B5UjRgS_.js → model-providers-Pv3ML_-t.js} +2 -2
  96. package/langwatch/dist/client/assets/{my-queue-BkEfiWyR.js → my-queue-BLre2NMr.js} +2 -2
  97. package/langwatch/dist/client/assets/{ops-Cc-g-CMn.js → ops-CCw-FJaT.js} +2 -2
  98. package/langwatch/dist/client/assets/{organization-features-CoIKKHkQ.js → organization-features-rqg-75mI.js} +2 -2
  99. package/langwatch/dist/client/assets/{organizations-DWcQUTzi.js → organizations-DjCzIHVx.js} +2 -2
  100. package/langwatch/dist/client/assets/{persistence-CTQ44vGL.js → persistence-BPvHS0F6.js} +2 -2
  101. package/langwatch/dist/client/assets/{plans-Dq3eFg5K.js → plans-Ch2Ol-Fd.js} +2 -2
  102. package/langwatch/dist/client/assets/{projections-CTNj1QBM.js → projections-it4FOVjm.js} +2 -2
  103. package/langwatch/dist/client/assets/{projects-BxM7C87h.js → projects-CjWZFLfn.js} +2 -2
  104. package/langwatch/dist/client/assets/{prompts-DhXnJT6e.js → prompts-DilmFH_s.js} +2 -2
  105. package/langwatch/dist/client/assets/{providers-DW7VWdqq.js → providers-tlLT_lTF.js} +2 -2
  106. package/langwatch/dist/client/assets/{reports-D3QFKhNP.js → reports-vlrcTrLs.js} +2 -2
  107. package/langwatch/dist/client/assets/{roles-B_0t5DWA.js → roles-DNgi-NQ9.js} +2 -2
  108. package/langwatch/dist/client/assets/{scenarios-BX3XslU0.js → scenarios-BmG_wDkR.js} +2 -2
  109. package/langwatch/dist/client/assets/{scim-DDsLO39r.js → scim-BKr1_FHt.js} +2 -2
  110. package/langwatch/dist/client/assets/{secrets-BvEGwDCy.js → secrets-CU8ocTGv.js} +2 -2
  111. package/langwatch/dist/client/assets/{settings-9giNiAQQ.js → settings-CDzdoYVK.js} +2 -2
  112. package/langwatch/dist/client/assets/{setup-HxXKoVKG.js → setup-nEvn2rjN.js} +2 -2
  113. package/langwatch/dist/client/assets/{subscription-DhyswDze.js → subscription-BPNl_6jF.js} +3 -3
  114. package/langwatch/dist/client/assets/{subscriptions-Dyyau22a.js → subscriptions-D0G-OE5C.js} +2 -2
  115. package/langwatch/dist/client/assets/{teams-DRmeAxzf.js → teams-DThgDQvB.js} +2 -2
  116. package/langwatch/dist/client/assets/{textOverflowHeuristic-JibhpzDV.js → textOverflowHeuristic-DTC8-Ffx.js} +2 -2
  117. package/langwatch/dist/client/assets/{topic-clustering-Bllfw5rZ.js → topic-clustering-BR2Mbpao.js} +2 -2
  118. package/langwatch/dist/client/assets/{topics-CpiGYxqb.js → topics-CI8GoNqp.js} +2 -2
  119. package/langwatch/dist/client/assets/{traceExecutor-CiHXJB0V.js → traceExecutor-CDUGyUaw.js} +2 -2
  120. package/langwatch/dist/client/assets/{usage-BnsstwBY.js → usage-B4mR7ut_.js} +2 -2
  121. package/langwatch/dist/client/assets/{usage-CoyGtJoI.js → usage-C8fbffYi.js} +2 -2
  122. package/langwatch/dist/client/assets/{useAdminResource-SPC5iBHM.js → useAdminResource-SmnnHro6.js} +2 -2
  123. package/langwatch/dist/client/assets/{useAnnotationQueues-2DKZTC7r.js → useAnnotationQueues-CA6Vk--V.js} +2 -2
  124. package/langwatch/dist/client/assets/{useAvailableEvaluators-HndTl2LV.js → useAvailableEvaluators-hmbmcRQr.js} +2 -2
  125. package/langwatch/dist/client/assets/{useDeleteDatasetConfirmation-BgWN6Qqb.js → useDeleteDatasetConfirmation-BCK_zUUe.js} +2 -2
  126. package/langwatch/dist/client/assets/{useWorkflowStore-e1wFCvo2.js → useWorkflowStore-QUJ3J8X9.js} +2 -2
  127. package/langwatch/dist/client/assets/{users-C6wjliCC.js → users-CfhanCfR.js} +2 -2
  128. package/langwatch/dist/client/assets/{users-tF6ZKeV1.js → users-HjuN3o6k.js} +2 -2
  129. package/langwatch/dist/client/assets/{virtual-keys-BL-65S0B.js → virtual-keys-Bj-MhW66.js} +2 -2
  130. package/langwatch/dist/client/assets/{wizard-faGkpZDT.js → wizard-dRWCVVx6.js} +2 -2
  131. package/langwatch/dist/client/assets/{workbench-Oj0s_YR-.js → workbench-CuixH3G1.js} +2 -2
  132. package/langwatch/dist/client/assets/{workflows-Cu9k-Twu.js → workflows-BT6m4Yu9.js} +2 -2
  133. package/langwatch/dist/client/index.html +3 -3
  134. package/langwatch/dist/scenario-child-process.js +20 -10
  135. package/langwatch/package.json +2 -2
  136. package/langwatch/pnpm-lock.yaml +329 -328
  137. package/langwatch/scripts/seed-dogfood-password.ts +163 -0
  138. package/langwatch/src/app/api/workflows/post_event/__tests__/post-event-evaluator.integration.test.ts +458 -0
  139. package/langwatch/src/app/api/workflows/post_event/__tests__/post-event-routing.test.ts +188 -0
  140. package/langwatch/src/app/api/workflows/post_event/__tests__/post-event.integration.test.ts +274 -0
  141. package/langwatch/src/app/api/workflows/post_event/post-event.ts +29 -1
  142. package/langwatch/src/components/agents/AgentCodeEditorDrawer.tsx +4 -5
  143. package/langwatch/src/components/agents/__tests__/AgentCodeEditorDrawer.integration.test.tsx +40 -0
  144. package/langwatch/src/components/evaluations/wizard/hooks/evaluation-wizard-store/slices/factories/__tests__/code-execution-node.factory.unit.test.ts +47 -0
  145. package/langwatch/src/components/evaluations/wizard/hooks/evaluation-wizard-store/slices/factories/code-execution-node.factory.ts +2 -4
  146. package/langwatch/src/components/experiments/BatchEvaluationV2/BatchEvaluationV2EvaluationResults.tsx +6 -1
  147. package/langwatch/src/hooks/usePostHog.ts +11 -0
  148. package/langwatch/src/optimization_studio/__tests__/registry.test.ts +29 -1
  149. package/langwatch/src/optimization_studio/components/Optimize.tsx +17 -3
  150. package/langwatch/src/optimization_studio/components/properties/AgentPropertiesPanel.tsx +4 -5
  151. package/langwatch/src/optimization_studio/hooks/workflowStoreCore.ts +17 -6
  152. package/langwatch/src/optimization_studio/hooks/workflowStoreCore.unit.test.ts +42 -0
  153. package/langwatch/src/optimization_studio/registry.ts +2 -4
  154. package/langwatch/src/optimization_studio/server/lambda/index.ts +12 -2
  155. package/langwatch/src/server/api/routers/workflows.ts +18 -0
  156. package/langwatch/src/server/evaluations-v3/execution/workflowBuilder.ts +3 -2
  157. package/langwatch/src/server/evaluations-v3/services/__tests__/experiment-run.service.getRun-null.unit.test.ts +71 -0
  158. package/langwatch/src/server/evaluations-v3/services/experiment-run.service.ts +18 -9
  159. package/langwatch/src/server/modelProviders/utils.ts +11 -1
  160. package/langwatch/src/server/nlpgo/__tests__/nlpgoFetch.integration.test.ts +248 -0
  161. package/langwatch/src/server/nlpgo/nlpgoFetch.ts +155 -0
  162. package/langwatch/src/server/routes/__tests__/playground-proxy.integration.test.ts +242 -0
  163. package/langwatch/src/server/routes/playground.ts +11 -1
  164. package/langwatch/src/server/routes/workflows.ts +17 -0
  165. package/langwatch/src/server/topicClustering/topicClustering.ts +33 -8
  166. package/langwatch/src/server/workflows/runWorkflow.ts +10 -13
  167. package/langwatch_nlp/langwatch_nlp/studio/execute/execute_component.py +25 -1
  168. package/langwatch_nlp/langwatch_nlp/studio/parser.py +121 -16
  169. package/langwatch_nlp/langwatch_nlp/topic_clustering/topic_naming.py +39 -32
  170. package/langwatch_nlp/scripts/entrypoint.sh +67 -0
  171. package/langwatch_nlp/tests/studio/test_parse.py +198 -0
  172. package/mcp-server/pnpm-lock.yaml +15 -21
  173. package/package.json +1 -1
  174. package/packages/server/dist/cli.cjs +78 -94
  175. package/langwatch/dist/client/assets/ChatWindow-DzB-tNlQ.js +0 -1
  176. package/langwatch/dist/client/assets/_not-found-PEUaWdF3.js +0 -1
  177. package/langwatch/dist/client/assets/_slug_-C-8AjsjC.js +0 -2
  178. package/langwatch/dist/client/assets/choose--PBky27o.js +0 -2
  179. package/langwatch/dist/client/assets/custom-CSiS1liN.js +0 -1
@@ -0,0 +1,188 @@
1
+ /**
2
+ * @vitest-environment node
3
+ *
4
+ * Pin which Studio event types route through the Go engine when
5
+ * `release_nlp_go_engine_enabled` is on for the project.
6
+ *
7
+ * Regression history:
8
+ * The first wiring of nlpgo into Studio only added execute_flow,
9
+ * execute_component, and execute_evaluation to GO_ENGINE_EVENT_TYPES.
10
+ * Heartbeats (is_alive) and stop_execution were left routing to the
11
+ * legacy Python /studio/execute endpoint, so any operator who ran
12
+ * nlpgo with NLPGO_CHILD_BYPASS=true (or whose uvicorn child died)
13
+ * saw the Studio UI stuck in 'Connecting...' with a misleading
14
+ * 'Failed run workflow: Bad Gateway' toast firing on the heartbeat
15
+ * tick — and Run/Playground/Publish disabled. Caught during browser
16
+ * QA dogfood by sarah + ash; PR #3483.
17
+ *
18
+ * The contract: every event the Studio sends in the FF-on hot path
19
+ * MUST land on /go/studio/execute. If a future refactor drops one
20
+ * from GO_ENGINE_EVENT_TYPES this test fails with the offending type
21
+ * named.
22
+ *
23
+ * Pure routing test — no nlpgo subprocess, no live OpenAI. The
24
+ * existing post-event.integration.test.ts covers the actual /go/
25
+ * round-trip end-to-end.
26
+ */
27
+ import { describe, expect, it, vi } from "vitest";
28
+
29
+ import type { StudioClientEvent } from "../../../../../optimization_studio/types/events";
30
+
31
+ vi.mock("../../../../../server/featureFlag/featureFlag.service", () => ({
32
+ featureFlagService: {
33
+ isEnabled: vi.fn().mockResolvedValue(true),
34
+ },
35
+ }));
36
+
37
+ // `isNlpGoEnabled` resolves the project's organization via Prisma. Unit
38
+ // shards have no DB, so the live import throws PrismaClientInitializationError
39
+ // before the FF mock above is ever consulted. Stub the gate directly to
40
+ // keep this a pure routing test.
41
+ vi.mock("../../../../../server/nlpgo/nlpgoFetch", () => ({
42
+ isNlpGoEnabled: vi.fn().mockResolvedValue(true),
43
+ }));
44
+
45
+ vi.mock("../../../../../optimization_studio/server/addEnvs", async () => {
46
+ const actual = await vi.importActual<
47
+ typeof import("../../../../../optimization_studio/server/addEnvs")
48
+ >("../../../../../optimization_studio/server/addEnvs");
49
+ return {
50
+ ...actual,
51
+ getS3CacheKey: () => undefined,
52
+ };
53
+ });
54
+
55
+ const capturedPaths: string[] = [];
56
+ vi.mock("../../../../../optimization_studio/server/lambda", () => ({
57
+ invokeLambda: vi.fn(
58
+ async (
59
+ _projectId: string,
60
+ _event: StudioClientEvent,
61
+ _s3CacheKey: string | undefined,
62
+ options: { path?: string } = {},
63
+ ) => {
64
+ capturedPaths.push(options.path ?? "/studio/execute");
65
+ // One valid `done` frame so studioBackendPostEvent's reader exits
66
+ // cleanly via its `serverEvent.type === "done"` short-circuit
67
+ // instead of logging a "Studio invalid response" error on close.
68
+ // Routing happens before the first read so the path capture isn't
69
+ // dependent on what the body contains, but a clean stream keeps
70
+ // test output free of misleading errors.
71
+ const stream = new ReadableStream<Uint8Array>({
72
+ start(controller) {
73
+ controller.enqueue(
74
+ new TextEncoder().encode('data: {"type":"done"}\n\n'),
75
+ );
76
+ controller.close();
77
+ },
78
+ });
79
+ return stream.getReader();
80
+ },
81
+ ),
82
+ }));
83
+
84
+ const minimalWorkflow = {
85
+ workflow_id: "routing-test",
86
+ api_key: "k",
87
+ spec_version: "1.3",
88
+ name: "routing",
89
+ icon: "🧪",
90
+ description: "",
91
+ version: "1.3",
92
+ template_adapter: "default",
93
+ nodes: [],
94
+ edges: [],
95
+ state: {},
96
+ };
97
+
98
+ const eventByType: Record<string, StudioClientEvent> = {
99
+ execute_flow: {
100
+ type: "execute_flow",
101
+ payload: {
102
+ trace_id: "t",
103
+ workflow: minimalWorkflow as any,
104
+ inputs: [{}],
105
+ },
106
+ },
107
+ execute_component: {
108
+ type: "execute_component",
109
+ payload: {
110
+ trace_id: "t",
111
+ workflow: minimalWorkflow as any,
112
+ node_id: "n",
113
+ inputs: {},
114
+ },
115
+ },
116
+ execute_evaluation: {
117
+ type: "execute_evaluation",
118
+ payload: {
119
+ run_id: "r",
120
+ workflow: minimalWorkflow as any,
121
+ workflow_version_id: "v",
122
+ evaluate_on: "test",
123
+ },
124
+ },
125
+ is_alive: { type: "is_alive", payload: {} },
126
+ stop_execution: {
127
+ type: "stop_execution",
128
+ payload: { trace_id: "t" },
129
+ },
130
+ };
131
+
132
+ const FF_ON_EVENT_TYPES = [
133
+ "execute_flow",
134
+ "execute_component",
135
+ "execute_evaluation",
136
+ "is_alive",
137
+ "stop_execution",
138
+ ] as const;
139
+
140
+ describe("studioBackendPostEvent routing when FF is on", () => {
141
+ for (const eventType of FF_ON_EVENT_TYPES) {
142
+ it(`routes ${eventType} to /go/studio/execute`, async () => {
143
+ capturedPaths.length = 0;
144
+ const { studioBackendPostEvent } = await import("../post-event");
145
+ await studioBackendPostEvent({
146
+ projectId: "any-project",
147
+ message: eventByType[eventType]!,
148
+ onEvent: () => {},
149
+ });
150
+ expect(
151
+ capturedPaths,
152
+ `event type "${eventType}" must route to the Go engine when FF is on; ` +
153
+ `if you removed it from GO_ENGINE_EVENT_TYPES in post-event.ts, ` +
154
+ `Studio will silently fall back to the Python sidecar — see PR #3483 dogfood for the UX impact`,
155
+ ).toEqual(["/go/studio/execute"]);
156
+ });
157
+ }
158
+
159
+ it("execute_optimization is rejected before routing (DSPy is gone on the Go path)", async () => {
160
+ capturedPaths.length = 0;
161
+ const { studioBackendPostEvent } = await import("../post-event");
162
+ // execute_optimization is the one event type intentionally excluded
163
+ // from the Go engine — DSPy was dropped per owner directive. The
164
+ // route layer returns 410 before this function is called, but if
165
+ // someone bypasses the route guard, we still want to NOT route
166
+ // through the Go engine (no /go/ entry exists for it).
167
+ const event: StudioClientEvent = {
168
+ type: "execute_optimization",
169
+ payload: {
170
+ run_id: "r",
171
+ workflow: minimalWorkflow as any,
172
+ workflow_version_id: "v",
173
+ optimizer: "MIPROv2ZeroShot" as any,
174
+ params: {} as any,
175
+ },
176
+ };
177
+ await studioBackendPostEvent({
178
+ projectId: "any-project",
179
+ message: event,
180
+ onEvent: () => {},
181
+ });
182
+ // Either the legacy path (if a future refactor lets it through) or
183
+ // an empty array (current behavior with the route-layer 410 + this
184
+ // function's GO_ENGINE_EVENT_TYPES gating). Both are acceptable;
185
+ // the assertion is "MUST NOT route to /go/".
186
+ expect(capturedPaths).not.toContain("/go/studio/execute");
187
+ });
188
+ });
@@ -0,0 +1,274 @@
1
+ /**
2
+ * @vitest-environment node
3
+ *
4
+ * Live SSE end-to-end through the actual Studio "Run" path:
5
+ * studioBackendPostEvent → invokeLambda(path: /go/studio/execute)
6
+ * → real nlpgo Go subprocess → real OpenAI provider call.
7
+ *
8
+ * Why this test exists:
9
+ * The interactive Studio "Run" button posts events to
10
+ * /api/workflows/post_event, which calls studioBackendPostEvent. That
11
+ * function used to ALWAYS route to the Python /studio/execute endpoint
12
+ * regardless of the FF — meaning the entire Go-engine migration was
13
+ * only exercised by the batch evaluation path (runWorkflow.ts). This
14
+ * test pins the FF-gated routing so a future refactor can't silently
15
+ * regress the live UI path.
16
+ *
17
+ * Skipped (not failed) when:
18
+ * - OPENAI_API_KEY not set
19
+ * - go binary not on PATH
20
+ *
21
+ * Run cost: ~3-5s per invocation + ~3s subprocess startup.
22
+ */
23
+ import { spawn, type ChildProcess } from "node:child_process";
24
+ import { setTimeout as sleep } from "node:timers/promises";
25
+ import path from "node:path";
26
+
27
+ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
28
+
29
+ import type { StudioServerEvent } from "../../../../../optimization_studio/types/events";
30
+
31
+ // FF-on regardless of PostHog state.
32
+ vi.mock("../../../../../server/featureFlag/featureFlag.service", () => ({
33
+ featureFlagService: {
34
+ isEnabled: vi.fn().mockResolvedValue(true),
35
+ },
36
+ }));
37
+
38
+ // No S3 dependency for the test — use undefined cache key.
39
+ vi.mock("../../../../../optimization_studio/server/addEnvs", async () => {
40
+ const actual = await vi.importActual<
41
+ typeof import("../../../../../optimization_studio/server/addEnvs")
42
+ >("../../../../../optimization_studio/server/addEnvs");
43
+ return {
44
+ ...actual,
45
+ getS3CacheKey: () => undefined,
46
+ };
47
+ });
48
+
49
+ // Per-owner port scheme (rchaves's call): use the 5561X / 5562X range.
50
+ // Each port corresponds to a "real" production port + an extra trailing
51
+ // digit, so the connection between dev port and test port is obvious
52
+ // to readers and high enough to avoid collision with langwatch app on
53
+ // 5570, nlpgo on 5562, aigateway on 5563 even when the dev stack is
54
+ // running. Each live integration test that spawns its own nlpgo
55
+ // subprocess claims a unique port:
56
+ // 55620 — playground proxy live OpenAI (Ash)
57
+ // 55610 — this test (post_event SSE FF gating)
58
+ // 55611 — post_event evaluator with real provider e2e
59
+ const NLPGO_PORT = 55610;
60
+ const REPO_ROOT = path.resolve(__dirname, "../../../../../../..");
61
+
62
+ let nlpgoProcess: ChildProcess | null = null;
63
+
64
+ async function waitForHealth(timeoutMs = 30_000): Promise<void> {
65
+ const deadline = Date.now() + timeoutMs;
66
+ while (Date.now() < deadline) {
67
+ try {
68
+ const r = await fetch(`http://127.0.0.1:${NLPGO_PORT}/healthz`);
69
+ if (r.status === 200 || r.status === 503) return;
70
+ } catch {
71
+ // not ready yet
72
+ }
73
+ await sleep(250);
74
+ }
75
+ throw new Error(`nlpgo did not become healthy within ${timeoutMs}ms`);
76
+ }
77
+
78
+ beforeAll(async () => {
79
+ if (!process.env.OPENAI_API_KEY) return;
80
+
81
+ // Point invokeLambda's URL-fallback branch (no LAMBDA_CONFIG) at our
82
+ // local nlpgo subprocess. invokeLambda does:
83
+ // fetch(`${LANGWATCH_NLP_SERVICE}${path}`, ...)
84
+ process.env.LANGWATCH_NLP_SERVICE = `http://127.0.0.1:${NLPGO_PORT}`;
85
+ delete process.env.LANGWATCH_NLP_LAMBDA_CONFIG;
86
+
87
+ // detached:true puts `go run` into its own process group, so the
88
+ // SIGTERM in afterAll can target the whole group with kill(-pid, ...).
89
+ // Without this, SIGTERM hits only the `go` toolchain wrapper — its
90
+ // compiled child (the actual nlpgo binary) installs its own signal
91
+ // handlers and can survive long enough to keep $NLPGO_PORT bound,
92
+ // breaking parallel test runs with EADDRINUSE on retry.
93
+ nlpgoProcess = spawn("go", ["run", "./cmd/service", "nlpgo"], {
94
+ cwd: REPO_ROOT,
95
+ env: {
96
+ ...process.env,
97
+ NLPGO_CHILD_BYPASS: "true",
98
+ // Override the Go service's default :5562 listener so we don't
99
+ // collide with a dev nlpgo or aigateway already on PATH ports.
100
+ SERVER_ADDR: `:${NLPGO_PORT}`,
101
+ },
102
+ stdio: ["ignore", "pipe", "pipe"],
103
+ detached: true,
104
+ });
105
+
106
+ nlpgoProcess.stderr?.on("data", (chunk: Buffer) => {
107
+ if (process.env.NLPGO_TEST_LOG === "1") {
108
+ process.stderr.write(`[nlpgo] ${chunk.toString()}`);
109
+ }
110
+ });
111
+ nlpgoProcess.on("exit", (code, signal) => {
112
+ if (code !== 0 && code !== null) {
113
+ console.error(`nlpgo exited unexpectedly: code=${code} signal=${signal}`);
114
+ }
115
+ });
116
+
117
+ await waitForHealth();
118
+ }, 90_000);
119
+
120
+ afterAll(async () => {
121
+ if (!nlpgoProcess?.pid) return;
122
+ // Negative pid → kill the whole process group (`go run` plus its
123
+ // compiled child). Falls back to single-pid SIGKILL on edge cases
124
+ // (e.g. process already exited so the group is gone).
125
+ const pgid = -nlpgoProcess.pid;
126
+ try {
127
+ process.kill(pgid, "SIGTERM");
128
+ } catch {
129
+ // group already gone — nothing to do
130
+ }
131
+ const exited = await Promise.race([
132
+ new Promise<boolean>((resolve) =>
133
+ nlpgoProcess!.once("exit", () => resolve(true)),
134
+ ),
135
+ sleep(2000).then(() => false),
136
+ ]);
137
+ if (!exited) {
138
+ try {
139
+ process.kill(pgid, "SIGKILL");
140
+ } catch {
141
+ // best-effort
142
+ }
143
+ }
144
+ });
145
+
146
+ const liveOpenAI = process.env.OPENAI_API_KEY ? it : it.skip;
147
+
148
+ describe("studioBackendPostEvent FF-gated SSE routing to nlpgo", () => {
149
+ liveOpenAI(
150
+ "execute_flow with FF on streams a real Studio workflow through /go/studio/execute and returns success",
151
+ async () => {
152
+ const { studioBackendPostEvent } = await import("../post-event");
153
+
154
+ const workflow = {
155
+ workflow_id: "ts-postevent-e2e",
156
+ api_key: "k",
157
+ spec_version: "1.3",
158
+ name: "TS Post-Event E2E",
159
+ icon: "🧪",
160
+ description: "ts integration",
161
+ version: "1.3",
162
+ template_adapter: "default",
163
+ nodes: [
164
+ {
165
+ id: "entry",
166
+ type: "entry",
167
+ data: {
168
+ outputs: [{ identifier: "question", type: "str" }],
169
+ dataset: {
170
+ inline: {
171
+ records: { question: ["Reply with just the digit 7."] },
172
+ },
173
+ },
174
+ entry_selection: 0,
175
+ train_size: 1.0,
176
+ test_size: 0.0,
177
+ seed: 1,
178
+ },
179
+ },
180
+ {
181
+ id: "answer",
182
+ type: "signature",
183
+ data: {
184
+ name: "Answer",
185
+ parameters: [
186
+ {
187
+ identifier: "llm",
188
+ type: "llm",
189
+ value: {
190
+ model: "openai/gpt-5-mini",
191
+ litellm_params: { api_key: process.env.OPENAI_API_KEY },
192
+ },
193
+ },
194
+ ],
195
+ inputs: [{ identifier: "question", type: "str" }],
196
+ outputs: [{ identifier: "answer", type: "str" }],
197
+ },
198
+ },
199
+ {
200
+ id: "end",
201
+ type: "end",
202
+ data: { inputs: [{ identifier: "answer", type: "str" }] },
203
+ },
204
+ ],
205
+ edges: [
206
+ {
207
+ id: "e1",
208
+ source: "entry",
209
+ sourceHandle: "outputs.question",
210
+ target: "answer",
211
+ targetHandle: "inputs.question",
212
+ type: "default",
213
+ },
214
+ {
215
+ id: "e2",
216
+ source: "answer",
217
+ sourceHandle: "outputs.answer",
218
+ target: "end",
219
+ targetHandle: "inputs.answer",
220
+ type: "default",
221
+ },
222
+ ],
223
+ state: {},
224
+ };
225
+
226
+ const message = {
227
+ type: "execute_flow" as const,
228
+ payload: {
229
+ trace_id: "ts-postevent-e2e-trace",
230
+ workflow,
231
+ inputs: [{}],
232
+ origin: "workflow",
233
+ },
234
+ };
235
+
236
+ const events: StudioServerEvent[] = [];
237
+ await studioBackendPostEvent({
238
+ projectId: "test-project",
239
+ message: message as any,
240
+ onEvent: (ev) => events.push(ev),
241
+ });
242
+
243
+ // SSE stream MUST terminate with a 'done' event for a successful
244
+ // run. Anything else means we landed on an error path or the
245
+ // legacy /studio/execute (which would 502 because nlpgo's child
246
+ // proxy targets are bypassed).
247
+ const done = events.find((e) => e.type === "done");
248
+ const errorEvent = events.find((e) => e.type === "error");
249
+ expect(
250
+ errorEvent,
251
+ errorEvent && "payload" in errorEvent
252
+ ? JSON.stringify(errorEvent.payload)
253
+ : "no error payload",
254
+ ).toBeUndefined();
255
+ expect(done, JSON.stringify(events.slice(-3))).toBeDefined();
256
+
257
+ // The final state on the 'end' component carries the result. The
258
+ // 'answer' field is whatever OpenAI replied with; it must contain
259
+ // the digit we asked for. Loose match: the actual response often
260
+ // includes trailing whitespace or punctuation.
261
+ const componentChanges = events.filter(
262
+ (e): e is Extract<StudioServerEvent, { type: "component_state_change" }> =>
263
+ e.type === "component_state_change",
264
+ );
265
+ const lastEndChange = [...componentChanges]
266
+ .reverse()
267
+ .find((e) => e.payload.component_id === "end");
268
+ expect(lastEndChange, JSON.stringify(events)).toBeDefined();
269
+ const stringified = JSON.stringify(lastEndChange?.payload.execution_state);
270
+ expect(stringified).toContain("7");
271
+ },
272
+ 60_000,
273
+ );
274
+ });
@@ -1,6 +1,7 @@
1
1
  import { captureException } from "~/utils/posthogErrorCapture";
2
2
  import { getS3CacheKey } from "../../../../optimization_studio/server/addEnvs";
3
3
  import { invokeLambda } from "../../../../optimization_studio/server/lambda";
4
+ import { isNlpGoEnabled } from "~/server/nlpgo/nlpgoFetch";
4
5
  import type {
5
6
  StudioClientEvent,
6
7
  StudioServerEvent,
@@ -9,6 +10,26 @@ import { createLogger } from "../../../../utils/logger/server";
9
10
 
10
11
  const logger = createLogger("langwatch:post_event");
11
12
 
13
+ /** Event types the Go engine handles natively when the FF is on. The
14
+ * only outlier is `execute_optimization`, intentionally rejected at
15
+ * the route layer with 410 (DSPy is gone). Studio fires `is_alive`
16
+ * every ~7s as a heartbeat and `stop_execution` when the user clicks
17
+ * Stop — if either of those still routes to the legacy
18
+ * `/studio/execute` path while the engine is on `/go/`, an operator
19
+ * running without the Python sidecar (the post-100% target topology)
20
+ * gets a perpetual "Connecting…" status plus a misleading "Bad Gateway
21
+ * child upstream unavailable" toast every heartbeat tick. So both
22
+ * passthrough types belong on the Go path; nlpgo answers them with
23
+ * bare SSE frames (see executeStreamHandler in
24
+ * services/nlpgo/adapters/httpapi/handlers.go). */
25
+ const GO_ENGINE_EVENT_TYPES = new Set([
26
+ "execute_flow",
27
+ "execute_component",
28
+ "execute_evaluation",
29
+ "is_alive",
30
+ "stop_execution",
31
+ ]);
32
+
12
33
  export const studioBackendPostEvent = async ({
13
34
  projectId,
14
35
  message: message,
@@ -25,7 +46,14 @@ export const studioBackendPostEvent = async ({
25
46
  try {
26
47
  const s3CacheKey = getS3CacheKey(projectId);
27
48
 
28
- reader = await invokeLambda(projectId, message, s3CacheKey);
49
+ const goEnabled =
50
+ GO_ENGINE_EVENT_TYPES.has(message.type) &&
51
+ (await isNlpGoEnabled({ projectId }));
52
+
53
+ reader = await invokeLambda(projectId, message, s3CacheKey, {
54
+ path: goEnabled ? "/go/studio/execute" : "/studio/execute",
55
+ headers: goEnabled ? { "X-LangWatch-Origin": "workflow" } : undefined,
56
+ });
29
57
  } catch (error) {
30
58
  if (
31
59
  (error as any)?.cause?.code === "ECONNREFUSED" ||
@@ -48,10 +48,8 @@ import { isHandledByGlobalHandler } from "~/utils/trpcError";
48
48
  import { ScenarioInputMappingSection, isScenarioMappingValid } from "~/components/suites/ScenarioInputMappingSection";
49
49
  import { computeBestMatchMappings } from "~/server/scenarios/execution/resolve-field-mappings";
50
50
 
51
- const DEFAULT_CODE = `import dspy
52
-
53
- class Code(dspy.Module):
54
- def forward(self, input: str):
51
+ const DEFAULT_CODE = `class Code:
52
+ def __call__(self, input: str):
55
53
  # Your code goes here
56
54
 
57
55
  return {"output": input.upper()}
@@ -476,7 +474,8 @@ export function AgentCodeEditorDrawer(props: AgentCodeEditorDrawerProps) {
476
474
  <Field.Root>
477
475
  <Field.Label>Python Code</Field.Label>
478
476
  <Text fontSize="sm" color="fg.muted" marginBottom={2}>
479
- Write a DSPy module that takes inputs and returns outputs.
477
+ Define a Python class with a `__call__` method that takes
478
+ inputs and returns outputs.
480
479
  </Text>
481
480
  <CodeBlockEditor
482
481
  code={code}
@@ -324,4 +324,44 @@ describe("AgentCodeEditorDrawer", () => {
324
324
  });
325
325
  });
326
326
  });
327
+
328
+ // Per owner directive on PR #3483 (nlp-go-migration): the Code Agent
329
+ // editor's default template must NOT reference dspy. Caught during
330
+ // workbench dogfood by ash — a reviewer landing on the editor and
331
+ // seeing `import dspy` reasonably concludes the migration didn't
332
+ // happen, even though the runtime would still execute via fake_dspy.
333
+ // The matching workflow-studio Code block already has this
334
+ // regression test in optimization_studio/__tests__/registry.test.ts;
335
+ // this pins the standalone agent editor side.
336
+ describe("default code template (nlp-go-migration regression)", () => {
337
+ it("ships without any dspy reference", async () => {
338
+ renderDrawer();
339
+
340
+ const textarea = await waitFor(() =>
341
+ screen.getByTestId("code-textarea"),
342
+ );
343
+ const value = (textarea as HTMLTextAreaElement).value;
344
+
345
+ expect(value).not.toContain("import dspy");
346
+ expect(value).not.toContain("dspy.Module");
347
+ expect(value).not.toContain("(dspy.");
348
+ });
349
+
350
+ it("uses a plain Python class with a __call__ method", async () => {
351
+ renderDrawer();
352
+
353
+ const textarea = await waitFor(() =>
354
+ screen.getByTestId("code-textarea"),
355
+ );
356
+ const value = (textarea as HTMLTextAreaElement).value;
357
+
358
+ // Default template uses Python's idiomatic `__call__` (instances
359
+ // are callable) instead of torch/dspy's `forward` convention.
360
+ // Existing customer code with `forward` still resolves via the
361
+ // runner's fallback rules — this only pins the new default shape.
362
+ expect(value).toMatch(/^class\s+\w+\s*:/m);
363
+ expect(value).toContain("def __call__(self");
364
+ expect(value).not.toContain("def forward");
365
+ });
366
+ });
327
367
  });
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @vitest-environment node
3
+ *
4
+ * Pin the eval-wizard Code-Execution-Node default template post
5
+ * nlp-go-migration. The wizard reaches this factory whenever a user
6
+ * adds a Code block to a custom evaluator's pipeline; if it ships with
7
+ * `import dspy` again, dogfooders see a contradiction with the rest of
8
+ * the migration (workflow-studio template is plain Python, agent
9
+ * editor is plain Python, but the wizard still imports dspy).
10
+ *
11
+ * Mirrors optimization_studio/__tests__/registry.test.ts and
12
+ * components/agents/__tests__/AgentCodeEditorDrawer.integration.test.tsx —
13
+ * three surfaces, one rule.
14
+ */
15
+ import { describe, expect, it } from "vitest";
16
+
17
+ import { CodeExecutionNodeFactory } from "../code-execution-node.factory";
18
+
19
+ describe("CodeExecutionNodeFactory default template", () => {
20
+ it("ships without any dspy reference", () => {
21
+ const node = CodeExecutionNodeFactory.build();
22
+ const codeParam = node.data.parameters?.find(
23
+ (p) => p.identifier === "code",
24
+ );
25
+ const value = codeParam?.value as string;
26
+
27
+ expect(value).not.toContain("import dspy");
28
+ expect(value).not.toContain("dspy.Module");
29
+ expect(value).not.toContain("(dspy.");
30
+ });
31
+
32
+ it("uses a plain Python class with a __call__ method", () => {
33
+ const node = CodeExecutionNodeFactory.build();
34
+ const codeParam = node.data.parameters?.find(
35
+ (p) => p.identifier === "code",
36
+ );
37
+ const value = codeParam?.value as string;
38
+
39
+ // Default template uses Python's idiomatic `__call__` (instances
40
+ // are callable) instead of torch/dspy's `forward` convention.
41
+ // Existing customer code with `forward` still resolves via the
42
+ // runner's fallback rules — this only pins the new default shape.
43
+ expect(value).toMatch(/^class\s+\w+\s*:/m);
44
+ expect(value).toContain("def __call__(self");
45
+ expect(value).not.toContain("def forward");
46
+ });
47
+ });
@@ -17,10 +17,8 @@ const DEFAULT_CODE_NODE_PROPERTIES: CodeExecutionNode = {
17
17
  {
18
18
  identifier: "code",
19
19
  type: "code",
20
- value: `import dspy
21
-
22
- class Code(dspy.Module):
23
- def forward(self, ${INPUT_FIELD_NAME}: str):
20
+ value: `class Code:
21
+ def __call__(self, ${INPUT_FIELD_NAME}: str):
24
22
  # Your code goes here
25
23
 
26
24
  return {"${OUTPUT_FIELD_NAME}": "Hello world!"}
@@ -321,7 +321,12 @@ export const useBatchEvaluationDownloadCSV = ({
321
321
 
322
322
  const link = document.createElement("a");
323
323
  link.href = url;
324
- const formattedDate = new Date(run.data.timestamps.createdAt)
324
+ // Non-null per the `isDownloadCSVEnabled` guard above (the early
325
+ // throw on line 208 ensures `run.data` is populated by the time we
326
+ // get here). `getRun` returns `ExperimentRunWithItems | null` since
327
+ // PR #3483 to handle the cold-start window where the row hasn't
328
+ // been folded into ClickHouse yet — see service comment.
329
+ const formattedDate = new Date(run.data!.timestamps.createdAt)
325
330
  .toISOString()
326
331
  .split("T")[0];
327
332
  const fileName = `${formattedDate}_${experiment.name}_${runId}.csv`;
@@ -32,6 +32,17 @@ export function usePostHog() {
32
32
  recordCrossOriginIframes: true,
33
33
  },
34
34
  loaded: (posthog) => {
35
+ // Explicitly expose `window.posthog` so the PostHog toolbar
36
+ // (launched from the PostHog dashboard's "Toolbar" button)
37
+ // can attach in any environment, not just development. The
38
+ // posthog-js library sets this internally on most builds, but
39
+ // bundlers and strict-mode wrappers can sometimes strip the
40
+ // implicit global; the assignment is best-effort and has no
41
+ // downside in environments where it's already set.
42
+ if (typeof window !== "undefined") {
43
+ (window as unknown as { posthog: typeof posthog }).posthog =
44
+ posthog;
45
+ }
35
46
  if (publicEnv.data?.NODE_ENV === "development") posthog.debug();
36
47
  },
37
48
  });