🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore(web): typecheck test files in CI and fix latent test type errors (#15038)
Tobias Wochinger158100bd8878
diff --git a/turbo.json b/turbo.jsonindex 76a221c1e9..d792804a6b 100644--- a/turbo.json+++ b/turbo.json@@ -10,6 +10,10 @@"tasks": {"build": {"dependsOn": ["db:generate", "^build"],+ // NEXT_IGNORE_BUILD_ERRORS toggles the Next.js type check, so builds+ // with and without it must not share a cache entry — a cached+ // unchecked build would otherwise replay as a "type-checked" one.+ "env": ["NEXT_IGNORE_BUILD_ERRORS"],"outputs": ["dist/**", ".next/**", "!.next/cache/**"],"cache": true,"outputLogs": "errors-only"@@ -85,6 +89,7 @@},"build:check": {"dependsOn": ["db:generate", "^build"],+ "env": ["NEXT_IGNORE_BUILD_ERRORS"],"outputs": [".next-check/**", "!.next-check/cache/**"],"cache": true,"outputLogs": "errors-only"diff --git a/web/eslint.config.mjs b/web/eslint.config.mjsindex 3a6b6abb2a..8c96083b58 100644--- a/web/eslint.config.mjs+++ b/web/eslint.config.mjs@@ -172,9 +172,11 @@ export default [},},- // Restrict react-icons imports+ // Restricted import paths. Flat config replaces (not merges) a rule that is+ // configured twice, so all no-restricted-imports patterns live in this one+ // block.{- name: "langfuse/web/react-icons-restriction",+ name: "langfuse/web/restricted-imports",rules: {"no-restricted-imports": ["error",@@ -190,6 +192,21 @@ export default [message:"Only react-icons/si and react-icons/tb are allowed. Please use lucide-react for other icons.",},+ {+ // Relative paths escaping web/ bypass @langfuse/shared's exports+ // map (which points at dist/) and pull shared *source* into the+ // Next.js typecheck program, where web's next-auth augmentation+ // breaks it — this failed production deploys (PR #15031).+ // Note: only static imports are checked. Dynamic import() is not+ // covered by this rule, which also leaves room for the one+ // legitimate use: tests that need a Vite-transformed source copy+ // of a shared module to observe env mutations (vitest loads the+ // CJS dist through Node's require cache as a second instance —+ // see blob-storage-integration-trpc.servertest.ts).+ regex: "^(\\.\\./)+(packages|ee|worker)/",+ message:+ "Do not import other workspace packages via relative paths. Use the package entrypoints instead (e.g. @langfuse/shared/src/db, @langfuse/shared/src/server).",+ },],},],diff --git a/web/package.json b/web/package.jsonindex aa1126a867..aa0612e570 100644--- a/web/package.json+++ b/web/package.json@@ -9,7 +9,7 @@"scripts": {"build": "INLINE_RUNTIME_CHUNK=false dotenv -e ../.env -- next build","build:check": "NEXT_DIST_DIR=.next-check INLINE_RUNTIME_CHUNK=false dotenv -e ../.env -- next build",- "typecheck": "dotenv -e ../.env -- tsgo -p tsconfig.build.json --noEmit --skipLibCheck --incremental --tsBuildInfoFile .tsbuildinfo",+ "typecheck": "dotenv -e ../.env -- tsgo -p tsconfig.json --noEmit --skipLibCheck --incremental --tsBuildInfoFile .tsbuildinfo","dev": "dotenv -e ../.env -- next dev","dev:http": "dotenv -e ../.env -- next dev --experimental-https --experimental-https-key ./localhost+1-key.pem --experimental-https-cert ./localhost+1.pem","lint": "dotenv -e ../.env -- eslint . --cache --cache-location .next/cache/eslint/ --max-warnings 0 --concurrency 2",diff --git a/web/src/__tests__/aggregateScores.clienttest.ts b/web/src/__tests__/aggregateScores.clienttest.tsindex ef2bd249c2..9326638bfa 100644--- a/web/src/__tests__/aggregateScores.clienttest.ts+++ b/web/src/__tests__/aggregateScores.clienttest.ts@@ -1,9 +1,11 @@-import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";-import { type ScoreDomain } from "@langfuse/shared";+import {+ aggregateScores,+ type ScoreToAggregate,+} from "@/src/features/scores/lib/aggregateScores";describe("aggregateScores", () => {it("should return an empty object for an empty array", () => {- const scores: ScoreDomain[] = [];+ const scores: ScoreToAggregate[] = [];expect(aggregateScores(scores)).toEqual({});});@@ -16,7 +18,7 @@ describe("aggregateScores", () => {value: 5,comment: "test comment",},- ] as ScoreDomain[];+ ] as ScoreToAggregate[];expect(aggregateScores(scores)).toEqual({"test-API-NUMERIC": {type: "NUMERIC",@@ -43,7 +45,7 @@ describe("aggregateScores", () => {value: 7,comment: "another comment",},- ] as ScoreDomain[];+ ] as ScoreToAggregate[];expect(aggregateScores(scores)).toEqual({"test-API-NUMERIC": {type: "NUMERIC",@@ -70,7 +72,7 @@ describe("aggregateScores", () => {value: 5,comment: "another comment",},- ] as ScoreDomain[];+ ] as ScoreToAggregate[];expect(aggregateScores(scores)).toEqual({"test-API-NUMERIC": {type: "NUMERIC",@@ -82,7 +84,7 @@ describe("aggregateScores", () => {});it("should correctly aggregate scores with different keys", () => {- const scores: ScoreDomain[] = [+ const scores: ScoreToAggregate[] = [{name: "test1",source: "API",@@ -97,7 +99,7 @@ describe("aggregateScores", () => {value: 7,comment: "another comment",},- ] as ScoreDomain[];+ ] as ScoreToAggregate[];expect(aggregateScores(scores)).toEqual({"test1-API-NUMERIC": {type: "NUMERIC",@@ -123,7 +125,7 @@ describe("aggregateScores", () => {stringValue: "good",comment: "test comment",},- ] as ScoreDomain[];+ ] as ScoreToAggregate[];expect(aggregateScores(scores)).toEqual({"test-ANNOTATION-CATEGORICAL": {type: "CATEGORICAL",@@ -150,7 +152,7 @@ describe("aggregateScores", () => {stringValue: "False",comment: "another comment",},- ] as ScoreDomain[];+ ] as ScoreToAggregate[];expect(aggregateScores(scores)).toEqual({"test-API-BOOLEAN": {type: "CATEGORICAL",@@ -197,7 +199,7 @@ describe("aggregateScores", () => {value: 0,comment: "last comment",},- ] as ScoreDomain[];+ ] as ScoreToAggregate[];expect(aggregateScores(scores)).toEqual({"test-API-NUMERIC": {type: "NUMERIC",diff --git a/web/src/__tests__/mergeScoresWithCache.clienttest.ts b/web/src/__tests__/mergeScoresWithCache.clienttest.tsindex b00d9b7f52..6dc8da8f5c 100644--- a/web/src/__tests__/mergeScoresWithCache.clienttest.ts+++ b/web/src/__tests__/mergeScoresWithCache.clienttest.ts@@ -4,12 +4,13 @@ import {mergeAnnotationScoresWithCache,} from "@/src/features/scores/lib/mergeScoresWithCache";import { type ScoreDomain, type ScoreAggregate } from "@langfuse/shared";+import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";import { type CachedScore } from "@/src/features/scores/contexts/ScoreCacheContext";import { type AnnotationScore } from "@/src/features/scores/types";describe("mergeScoresWithCache", () => {it("should return server scores when cache is empty", () => {- const serverScores: ScoreDomain[] = [+ const serverScores: WithStringifiedMetadata<ScoreDomain>[] = [{id: "score-1",name: "quality",@@ -30,7 +31,8 @@ describe("mergeScoresWithCache", () => {authorUserId: "user-1",queueId: null,datasetRunId: null,- metadata: {},+ metadata: null,+ longStringValue: "",executionTraceId: null,},];@@ -42,7 +44,7 @@ describe("mergeScoresWithCache", () => {});it("should filter out deleted server scores", () => {- const serverScores: ScoreDomain[] = [+ const serverScores: WithStringifiedMetadata<ScoreDomain>[] = [{id: "score-1",name: "quality",@@ -63,7 +65,8 @@ describe("mergeScoresWithCache", () => {authorUserId: "user-1",queueId: null,datasetRunId: null,- metadata: {},+ metadata: null,+ longStringValue: "",executionTraceId: null,},{@@ -86,7 +89,8 @@ describe("mergeScoresWithCache", () => {authorUserId: "user-1",queueId: null,datasetRunId: null,- metadata: {},+ metadata: null,+ longStringValue: "",executionTraceId: null,},];@@ -100,7 +104,7 @@ describe("mergeScoresWithCache", () => {});it("should overlay cached scores onto server scores", () => {- const serverScores: ScoreDomain[] = [+ const serverScores: WithStringifiedMetadata<ScoreDomain>[] = [{id: "score-1",name: "quality",@@ -121,7 +125,8 @@ describe("mergeScoresWithCache", () => {authorUserId: "user-1",queueId: null,datasetRunId: null,- metadata: {},+ metadata: null,+ longStringValue: "",executionTraceId: null,},];@@ -153,7 +158,7 @@ describe("mergeScoresWithCache", () => {});it("should add cache-only scores", () => {- const serverScores: ScoreDomain[] = [+ const serverScores: WithStringifiedMetadata<ScoreDomain>[] = [{id: "score-1",name: "quality",@@ -174,7 +179,8 @@ describe("mergeScoresWithCache", () => {authorUserId: "user-1",queueId: null,datasetRunId: null,- metadata: {},+ metadata: null,+ longStringValue: "",executionTraceId: null,},];@@ -207,7 +213,7 @@ describe("mergeScoresWithCache", () => {});it("should handle both delete and cache overlay", () => {- const serverScores: ScoreDomain[] = [+ const serverScores: WithStringifiedMetadata<ScoreDomain>[] = [{id: "score-1",name: "quality",@@ -228,7 +234,8 @@ describe("mergeScoresWithCache", () => {authorUserId: "user-1",queueId: null,datasetRunId: null,- metadata: {},+ metadata: null,+ longStringValue: "",executionTraceId: null,},{@@ -251,7 +258,8 @@ describe("mergeScoresWithCache", () => {authorUserId: "user-1",queueId: null,datasetRunId: null,- metadata: {},+ metadata: null,+ longStringValue: "",executionTraceId: null,},];diff --git a/web/src/__tests__/nestObservations.clienttest.ts b/web/src/__tests__/nestObservations.clienttest.tsindex 3896ff37ea..63fdbf8688 100644--- a/web/src/__tests__/nestObservations.clienttest.ts+++ b/web/src/__tests__/nestObservations.clienttest.ts@@ -12,45 +12,49 @@ import { nestObservations } from "@/src/components/trace/lib/helpers";import { type ObservationReturnType } from "@/src/server/api/routers/traces";describe("nestObservations", () => {+ // nestObservations only reads id/parentObservationId/startTime, so the mock+ // keeps its legacy shape (nulls and pre-v4 usage fields) and is cast as a+ // whole instead of tracking every field of ObservationReturnType.const createMockObservation = (overrides: Partial<ObservationReturnType> = {},- ): ObservationReturnType => ({- id: "mock-id",- name: "Mock Observation",- type: "SPAN",- startTime: new Date("2024-01-01T00:00:00.000Z"),- endTime: new Date("2024-01-01T00:00:01.000Z"),- parentObservationId: null,- traceId: "mock-trace-id",- projectId: "mock-project-id",- createdAt: new Date("2024-01-01T00:00:00.000Z"),- updatedAt: new Date("2024-01-01T00:00:00.000Z"),- level: "DEFAULT",- statusMessage: null,- version: null,- model: null,- modelParameters: null,- promptTokens: null,- completionTokens: null,- totalTokens: null,- unit: null,- inputCost: null,- outputCost: null,- totalCost: null,- completionStartTime: null,- timeToFirstToken: null,- promptId: null,- modelId: null,- inputUsage: null,- outputUsage: null,- totalUsage: null,- costDetails: null,- calculatedInputCost: null,- calculatedOutputCost: null,- calculatedTotalCost: null,- latency: null,- ...overrides,- });+ ): ObservationReturnType =>+ ({+ id: "mock-id",+ name: "Mock Observation",+ type: "SPAN",+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ endTime: new Date("2024-01-01T00:00:01.000Z"),+ parentObservationId: null,+ traceId: "mock-trace-id",+ projectId: "mock-project-id",+ createdAt: new Date("2024-01-01T00:00:00.000Z"),+ updatedAt: new Date("2024-01-01T00:00:00.000Z"),+ level: "DEFAULT",+ statusMessage: null,+ version: null,+ model: null,+ modelParameters: null,+ promptTokens: null,+ completionTokens: null,+ totalTokens: null,+ unit: null,+ inputCost: null,+ outputCost: null,+ totalCost: null,+ completionStartTime: null,+ timeToFirstToken: null,+ promptId: null,+ modelId: null,+ inputUsage: null,+ outputUsage: null,+ totalUsage: null,+ costDetails: null,+ calculatedInputCost: null,+ calculatedOutputCost: null,+ calculatedTotalCost: null,+ latency: null,+ ...overrides,+ }) as unknown as ObservationReturnType;it("should build a nested tree from flat observations with parent-child relationships", () => {// Create a flat list of observations representing this tree structure:diff --git a/web/src/__tests__/server/admin-access-webhook-middleware.servertest.ts b/web/src/__tests__/server/admin-access-webhook-middleware.servertest.tsindex ed4a750b50..c589c8e204 100644--- a/web/src/__tests__/server/admin-access-webhook-middleware.servertest.ts+++ b/web/src/__tests__/server/admin-access-webhook-middleware.servertest.ts@@ -1,4 +1,10 @@import type { Session } from "next-auth";++// Session fixture sub-object types; casts keep the runtime fixtures unchanged+// while satisfying newer required fields on the session user type.+type SessionUser = NonNullable<Session["user"]>;+type SessionProjects = SessionUser["organizations"][number]["projects"];+type SessionFeatureFlags = SessionUser["featureFlags"];import * as z from "zod";import { env } from "@/src/env.mjs";@@ -55,13 +61,13 @@ const createAdminSession = (retentionDays: 30,deletedAt: null,name: project.name ?? "Project",- })),- },+ })) as SessionProjects,+ } as SessionUser["organizations"][number],],featureFlags: {excludeClickhouseRead: false,templateFlag: true,- },+ } as SessionFeatureFlags,admin: true,},environment: {} as any,diff --git a/web/src/__tests__/server/admin-api-key-auth.servertest.ts b/web/src/__tests__/server/admin-api-key-auth.servertest.tsindex 05d3c02ca3..d407b8b1f3 100644--- a/web/src/__tests__/server/admin-api-key-auth.servertest.ts+++ b/web/src/__tests__/server/admin-api-key-auth.servertest.ts@@ -46,7 +46,7 @@ describe("Admin API Key Authentication", () => {headers: {authorization: auth,},- } as NextApiRequest;+ } as unknown as NextApiRequest;const result = await verifyAuth(mockReq, false);@@ -60,7 +60,7 @@ describe("Admin API Key Authentication", () => {headers: {authorization: "Basic invalid",},- } as NextApiRequest;+ } as unknown as NextApiRequest;await expect(verifyAuth(mockReq, false)).rejects.toEqual({status: 401,@@ -94,7 +94,7 @@ describe("Admin API Key Authentication", () => {"Basic " +Buffer.from(`${publicKey}:${secretKey}`).toString("base64"),},- } as NextApiRequest;+ } as unknown as NextApiRequest;await expect(verifyAuth(mockReq, false)).rejects.toMatchObject({status: 401,@@ -111,7 +111,7 @@ describe("Admin API Key Authentication", () => {"x-langfuse-admin-api-key": ADMIN_API_KEY,"x-langfuse-project-id": projectId,},- } as NextApiRequest;+ } as unknown as NextApiRequest;const result = await verifyAuth(mockReq, true);@@ -128,7 +128,7 @@ describe("Admin API Key Authentication", () => {headers: {authorization: auth,},- } as NextApiRequest;+ } as unknown as NextApiRequest;const result = await verifyAuth(mockReq, true);@@ -142,7 +142,7 @@ describe("Admin API Key Authentication", () => {headers: {authorization: auth,},- } as NextApiRequest;+ } as unknown as NextApiRequest;const result = await verifyAuth(mockReq, true);@@ -159,7 +159,7 @@ describe("Admin API Key Authentication", () => {"x-langfuse-admin-api-key": ADMIN_API_KEY,"x-langfuse-project-id": projectId,},- } as NextApiRequest;+ } as unknown as NextApiRequest;await expect(verifyAuth(mockReq, true)).rejects.toEqual({status: 403,@@ -178,7 +178,7 @@ describe("Admin API Key Authentication", () => {"x-langfuse-admin-api-key": "some-key","x-langfuse-project-id": projectId,},- } as NextApiRequest;+ } as unknown as NextApiRequest;await expect(verifyAuth(mockReq, true)).rejects.toEqual({status: 500,@@ -195,7 +195,7 @@ describe("Admin API Key Authentication", () => {"x-langfuse-admin-api-key": ADMIN_API_KEY,"x-langfuse-project-id": projectId,},- } as NextApiRequest;+ } as unknown as NextApiRequest;await expect(verifyAuth(mockReq, true)).rejects.toEqual({status: 401,@@ -210,7 +210,7 @@ describe("Admin API Key Authentication", () => {"x-langfuse-admin-api-key": "wrong-key","x-langfuse-project-id": projectId,},- } as NextApiRequest;+ } as unknown as NextApiRequest;await expect(verifyAuth(mockReq, true)).rejects.toEqual({status: 401,@@ -225,7 +225,7 @@ describe("Admin API Key Authentication", () => {"x-langfuse-admin-api-key": "different-key-2","x-langfuse-project-id": projectId,},- } as NextApiRequest;+ } as unknown as NextApiRequest;await expect(verifyAuth(mockReq, true)).rejects.toEqual({status: 401,@@ -239,7 +239,7 @@ describe("Admin API Key Authentication", () => {authorization: `Bearer ${ADMIN_API_KEY}`,"x-langfuse-admin-api-key": ADMIN_API_KEY,},- } as NextApiRequest;+ } as unknown as NextApiRequest;await expect(verifyAuth(mockReq, true)).rejects.toEqual({status: 400,@@ -255,7 +255,7 @@ describe("Admin API Key Authentication", () => {"x-langfuse-admin-api-key": ADMIN_API_KEY,"x-langfuse-project-id": "non-existent-project",},- } as NextApiRequest;+ } as unknown as NextApiRequest;await expect(verifyAuth(mockReq, true)).rejects.toEqual({status: 404,@@ -269,7 +269,7 @@ describe("Admin API Key Authentication", () => {authorization: auth,"x-langfuse-project-id": projectId,},- } as NextApiRequest;+ } as unknown as NextApiRequest;const result = await verifyAuth(mockReq, true);diff --git a/web/src/__tests__/server/admin-org-context-trpc.servertest.ts b/web/src/__tests__/server/admin-org-context-trpc.servertest.tsindex 2a7a0bb50a..d8dcda0fd1 100644--- a/web/src/__tests__/server/admin-org-context-trpc.servertest.ts+++ b/web/src/__tests__/server/admin-org-context-trpc.servertest.ts@@ -1,4 +1,10 @@import type { Session } from "next-auth";++// Session fixture sub-object types; casts keep the runtime fixtures unchanged+// while satisfying newer required fields on the session user type.+type SessionUser = NonNullable<Session["user"]>;+type SessionOrgs = SessionUser["organizations"];+type SessionFeatureFlags = SessionUser["featureFlags"];import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";@@ -15,7 +21,7 @@ const createSession = (opts: { admin: boolean; member: boolean }): Session => ({canCreateOrganizations: true,name: "Test User",organizations: opts.member- ? [+ ? ([{id: orgId,name: "Admin Org Context Test Org",@@ -32,19 +38,22 @@ const createSession = (opts: { admin: boolean; member: boolean }): Session => ({},],},- ]+ ] as SessionOrgs): [],featureFlags: {excludeClickhouseRead: false,templateFlag: true,- },+ } as SessionFeatureFlags,admin: opts.admin,},environment: {} as any,});const createCaller = (opts: { admin: boolean; member: boolean }) => {- const ctx = createInnerTRPCContext({ session: createSession(opts) });+ const ctx = createInnerTRPCContext({+ session: createSession(opts),+ headers: {},+ });return appRouter.createCaller({ ...ctx, prisma });};diff --git a/web/src/__tests__/server/annotation-queue-items-trpc.servertest.ts b/web/src/__tests__/server/annotation-queue-items-trpc.servertest.tsindex a53e418a03..784f7ad932 100644--- a/web/src/__tests__/server/annotation-queue-items-trpc.servertest.ts+++ b/web/src/__tests__/server/annotation-queue-items-trpc.servertest.ts@@ -30,6 +30,8 @@ describe("annotationQueueItems trpc", () => {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: setup.project.id,@@ -37,6 +39,8 @@ describe("annotationQueueItems trpc", () => {name: setup.project.name,deletedAt: null,retentionDays: null,+ hasTraces: false,+ createdAt: new Date().toISOString(),metadata: {},},],@@ -45,6 +49,10 @@ describe("annotationQueueItems trpc", () => {featureFlags: {templateFlag: true,excludeClickhouseRead: false,+ experimentsV4Enabled: false,+ observationEvals: false,+ searchBar: false,+ v4BetaToggleVisible: false,},},environment: {} as Session["environment"],diff --git a/web/src/__tests__/server/api-key-list-filter.servertest.ts b/web/src/__tests__/server/api-key-list-filter.servertest.tsindex 3cbd3809a8..e57edd6bfe 100644--- a/web/src/__tests__/server/api-key-list-filter.servertest.ts+++ b/web/src/__tests__/server/api-key-list-filter.servertest.ts@@ -23,7 +23,7 @@ function createMockResponse() {},};- return response as NextApiResponse & {+ return response as unknown as NextApiResponse & {statusCode: number;body: { apiKeys: Array<{ id: string; note: string | null }> } & Record<string,diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.tsindex 9661a9b708..b7c38a1095 100644--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts@@ -1,9 +1,56 @@import {OtelIngestionProcessor,createIngestionEventSchema,+ type IngestionEventType,type OtelIngestionProcessorConfig,+ type ResourceSpan,} from "@langfuse/shared/src/server";+/**+ * Widened event shape for assertions in this file.+ *+ * `processToIngestionEvents` returns `IngestionEventType`, whose `body` is a+ * wide Zod-inferred union (trace / observation / score / sdk-log bodies).+ * The assertions below read fields that do not exist on every union member —+ * and some, like `usageDetails` on span-create events or the normalized+ * `metadata.attributes` shape, that the processor emits at runtime beyond the+ * narrow static type. Widen `body` once here to the superset of asserted+ * fields instead of narrowing at every call site. Type-level only; the+ * runtime events are unchanged.+ */+type TestIngestionEventBody = {+ id?: string | null;+ timestamp?: string | null;+ name?: string | null;+ traceId?: string | null;+ sessionId?: string | null;+ userId?: string | null;+ environment?: string | null;+ release?: string | null;+ version?: string | null;+ public?: boolean | null;+ tags?: string[] | null;+ startTime?: string | null;+ endTime?: string | null;+ level?: string | null;+ statusMessage?: string | null;+ model?: string | null;+ promptName?: string | null;+ promptVersion?: number | null;+ input?: unknown;+ output?: unknown;+ usageDetails: Record<string, number | undefined>;+ metadata: {+ attributes?: Record<string, unknown>;+ resourceAttributes: Record<string, unknown>;+ [key: string]: unknown;+ };+};++type TestIngestionEvent = Omit<IngestionEventType, "body"> & {+ body: TestIngestionEventBody;+};+function createTestOtelProcessor(config: Partial<OtelIngestionProcessorConfig> = {},) {@@ -22,7 +69,7 @@ async function convertOtelSpanToIngestionEvent(resourceSpan: any,seenTraces: Set<string>,publicKey?: string,-) {+): Promise<TestIngestionEvent[]> {const processor = createTestOtelProcessor({publicKey: publicKey ?? "",});@@ -32,7 +79,9 @@ async function convertOtelSpanToIngestionEvent((processor as any).seenTraces = seenTraces;(processor as any).isInitialized = true;- return await processor.processToIngestionEvents([resourceSpan]);+ return (await processor.processToIngestionEvents([+ resourceSpan,+ ])) as unknown as TestIngestionEvent[];}describe("OTel Resource Span Mapping", () => {@@ -1254,7 +1303,7 @@ describe("OTel Resource Span Mapping", () => {],},],- };+ } as unknown as ResourceSpan;const processor = createTestOtelProcessor();const eventInputs = processor.processToEvent([resourceSpan]);@@ -3880,18 +3929,19 @@ describe("OTel Resource Span Mapping", () => {);describe("prompt linking gated to GENERATION observations", () => {- const buildResourceSpan = (attributes: Record<string, any>[]) => ({- scopeSpans: [- {- spans: [- {- ...defaultSpanProps,- attributes,- },- ],- },- ],- });+ const buildResourceSpan = (attributes: Record<string, any>[]) =>+ ({+ scopeSpans: [+ {+ spans: [+ {+ ...defaultSpanProps,+ attributes,+ },+ ],+ },+ ],+ }) as unknown as ResourceSpan;const promptAttributes = [{@@ -5457,7 +5507,7 @@ describe("OTel Resource Span Mapping", () => {],},],- };+ } as unknown as ResourceSpan;const processor = createTestOtelProcessor();const eventInputs = processor.processToEvent([resourceSpan]);@@ -5514,7 +5564,7 @@ describe("OTel Resource Span Mapping", () => {],},],- };+ } as unknown as ResourceSpan;const processor = createTestOtelProcessor();const eventInputs = processor.processToEvent([resourceSpan]);@@ -5621,7 +5671,7 @@ describe("OTel Resource Span Mapping", () => {],},],- };+ } as unknown as ResourceSpan;const processor = createTestOtelProcessor();const eventInputs = processor.processToEvent([resourceSpan]);@@ -6579,7 +6629,7 @@ describe("OTel Resource Span Mapping", () => {const traceEvent = events.find((e) => e.type === "trace-create");expect(traceEvent).toBeDefined();- expect(traceEvent.body.sessionId).toBe("langfuse-session-123");+ expect(traceEvent!.body.sessionId).toBe("langfuse-session-123");});it("should prioritize session.id over gen_ai.conversation.id when both are present", async () => {@@ -6653,7 +6703,7 @@ describe("OTel Resource Span Mapping", () => {const traceEvent = events.find((e) => e.type === "trace-create");expect(traceEvent).toBeDefined();- expect(traceEvent.body.sessionId).toBe("session-id-123");+ expect(traceEvent!.body.sessionId).toBe("session-id-123");});it("should default to span-create for unknown observation type", async () => {@@ -7275,16 +7325,16 @@ describe("OTel Resource Span Mapping", () => {// original_span_attribute should still existexpect(- updatedTraceEvent.body.metadata?.attributes?.original_span_attribute,+ updatedTraceEvent!.body.metadata?.attributes?.original_span_attribute,).toBe("should_be_preserved");// new_span_attribute should now existexpect(- updatedTraceEvent.body.metadata?.attributes?.new_span_attribute,+ updatedTraceEvent!.body.metadata?.attributes?.new_span_attribute,).toBe("new_value");// The sessionId should be updated- expect(updatedTraceEvent.body.sessionId).toBe("new-session");+ expect(updatedTraceEvent!.body.sessionId).toBe("new-session");});});diff --git a/web/src/__tests__/server/automations-trpc.servertest.ts b/web/src/__tests__/server/automations-trpc.servertest.tsindex 57ab5b99cf..2d7e20e115 100644--- a/web/src/__tests__/server/automations-trpc.servertest.ts+++ b/web/src/__tests__/server/automations-trpc.servertest.ts@@ -8,6 +8,7 @@ import {ActionExecutionStatus,JobConfigState,type SafeWebhookActionConfig,+ TriggerEventSource,type WebhookActionConfigWithSecrets,isWebhookAction,} from "@langfuse/shared";@@ -34,14 +35,18 @@ async function prepare() {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: project.id,role: "ADMIN",retentionDays: 30,deletedAt: null,+ hasTraces: false,name: project.name,metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -49,6 +54,10 @@ async function prepare() {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},@@ -353,13 +362,13 @@ describe("automations trpc", () => {const monitor = await caller.automations.getAutomations({projectId: project.id,- eventSource: "monitor",+ eventSource: TriggerEventSource.Monitor,});expect(monitor.map((a) => a.name)).toEqual(["monitor-automation"]);const prompt = await caller.automations.getAutomations({projectId: project.id,- eventSource: "prompt",+ eventSource: TriggerEventSource.Prompt,});expect(prompt.map((a) => a.name)).toEqual(["prompt-automation"]);});@@ -405,7 +414,7 @@ describe("automations trpc", () => {const response = await caller.automations.getAutomations({projectId: project.id,- eventSource: "project-notification",+ eventSource: TriggerEventSource.ProjectNotification,});expect(response.map((a) => a.name)).toEqual(["notification-channel"]);});@@ -468,7 +477,7 @@ describe("automations trpc", () => {// Explicit eventSource still returns the channel.const notificationList = await caller.automations.getAutomations({projectId: project.id,- eventSource: "project-notification",+ eventSource: TriggerEventSource.ProjectNotification,});expect(notificationList.map((a) => a.name)).toEqual(["notification-channel",@@ -902,16 +911,16 @@ describe("automations trpc", () => {// Headers should be encrypted for secret ones, plain for othersconst config = createdAction?.config as WebhookActionConfigWithSecrets;- expect(config.requestHeaders["content-type"].value).toBe(+ expect(config.requestHeaders!["content-type"].value).toBe("application/json",);- expect(config.requestHeaders["x-public"].value).toBe("public-value");- expect(config.requestHeaders["x-api-key"].secret).toBe(true);- expect(config.requestHeaders["x-api-key"].value).not.toBe(+ expect(config.requestHeaders!["x-public"].value).toBe("public-value");+ expect(config.requestHeaders!["x-api-key"].secret).toBe(true);+ expect(config.requestHeaders!["x-api-key"].value).not.toBe("secret-key-123",); // Should be encrypted- expect(config.requestHeaders["authorization"].secret).toBe(true);- expect(config.requestHeaders["authorization"].value).not.toBe(+ expect(config.requestHeaders!["authorization"].secret).toBe(true);+ expect(config.requestHeaders!["authorization"].value).not.toBe("Bearer secret-token-456",); // Should be encrypted@@ -920,8 +929,8 @@ describe("automations trpc", () => {"content-type": { secret: false, value: "application/json" },"x-public": { secret: false, value: "public-value" },});- expect(config.displayHeaders["x-api-key"].value).toBe("secr...-123");- expect(config.displayHeaders["authorization"].value).toBe("Bear...-456");+ expect(config.displayHeaders!["x-api-key"].value).toBe("secr...-123");+ expect(config.displayHeaders!["authorization"].value).toBe("Bear...-456");});it("should create automation with secret headers that do not expose values in response", async () => {@@ -979,10 +988,10 @@ describe("automations trpc", () => {"content-type": { secret: false, value: "application/json" },"x-public": { secret: false, value: "public-value" },});- expect(config.requestHeaders["x-api-key"].value).not.toBe(+ expect(config.requestHeaders!["x-api-key"].value).not.toBe("secret-value-123",);- expect(config.requestHeaders["authorization"].value).not.toBe(+ expect(config.requestHeaders!["authorization"].value).not.toBe("Bearer token-456",);@@ -1451,12 +1460,12 @@ describe("automations trpc", () => {const config = updatedAction?.config as WebhookActionConfigWithSecrets;// x-currently-public should now be encrypted (was plain, now secret)- expect(config.requestHeaders["x-currently-public"].value).not.toBe(+ expect(config.requestHeaders!["x-currently-public"].value).not.toBe("now-secret-value",);// x-currently-secret should now be plain (was secret, now public)- expect(config.requestHeaders["x-currently-secret"].value).toBe(+ expect(config.requestHeaders!["x-currently-secret"].value).toBe("now-public-value",);@@ -1537,7 +1546,7 @@ describe("automations trpc", () => {},});- fail("Expected an error to be thrown");+ throw new Error("Expected an error to be thrown");} catch (error: any) {expect(error).toBeInstanceOf(TRPCError);expect(error.message).toBe(@@ -1554,7 +1563,7 @@ describe("automations trpc", () => {const config = updatedAction?.config as WebhookActionConfigWithSecrets;// x-currently-secret should still be encrypted- expect(config.requestHeaders["x-currently-secret"].value).not.toBe(+ expect(config.requestHeaders!["x-currently-secret"].value).not.toBe("secret-value",);@@ -1657,10 +1666,10 @@ describe("automations trpc", () => {expect(config.url).toBe("https://example.com/new-webhook-url");// Secret headers should still be encrypted and preserved- expect(config.requestHeaders["x-api-key"].value).not.toBe(+ expect(config.requestHeaders!["x-api-key"].value).not.toBe("secret-key-123",);- expect(config.requestHeaders["authorization"].value).not.toBe(+ expect(config.requestHeaders!["authorization"].value).not.toBe("Bearer token-456",);@@ -1757,14 +1766,14 @@ describe("automations trpc", () => {expect(config.headers).toEqual({});// Secret header should be encrypted in requestHeaders- expect(config.requestHeaders["x-api-key"].secret).toBe(true);- expect(config.requestHeaders["x-api-key"].value).not.toBe(+ expect(config.requestHeaders!["x-api-key"].secret).toBe(true);+ expect(config.requestHeaders!["x-api-key"].value).not.toBe("new-secret-key",);// Public header should remain plain- expect(config.requestHeaders["content-type"].secret).toBe(false);- expect(config.requestHeaders["content-type"].value).toBe(+ expect(config.requestHeaders!["content-type"].secret).toBe(false);+ expect(config.requestHeaders!["content-type"].value).toBe("application/json",);@@ -2729,7 +2738,9 @@ describe("automations trpc", () => {});// Verify token is NOT returned (users provided it themselves)- expect(response.webhookSecret).toBeUndefined();+ expect(+ (response as unknown as { webhookSecret?: string }).webhookSecret,+ ).toBeUndefined();const config = response.action.config as any;expect(config.displayGitHubToken).toMatch(/^ghp_...6$/);diff --git a/web/src/__tests__/server/batchExport-trpc.servertest.ts b/web/src/__tests__/server/batchExport-trpc.servertest.tsindex 2e56929a05..4e54d3527c 100644--- a/web/src/__tests__/server/batchExport-trpc.servertest.ts+++ b/web/src/__tests__/server/batchExport-trpc.servertest.ts@@ -44,6 +44,7 @@ function makeSession(cloudConfig: undefined,metadata: {},aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: projectId,@@ -61,11 +62,10 @@ function makeSession(featureFlags: {excludeClickhouseRead: false,templateFlag: false,- inAppAgent: false,+ searchBar: false,v4BetaToggleVisible: false,observationEvals: false,experimentsV4Enabled: false,- monitors: false,},admin: false,},diff --git a/web/src/__tests__/server/blob-storage-integration-api.servertest.ts b/web/src/__tests__/server/blob-storage-integration-api.servertest.tsindex 395ff9b568..02e0e34e4a 100644--- a/web/src/__tests__/server/blob-storage-integration-api.servertest.ts+++ b/web/src/__tests__/server/blob-storage-integration-api.servertest.ts@@ -242,7 +242,7 @@ describe("Blob Storage Integrations API", () => {},});- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("GET","/api/public/integrations/blob-storage",undefined,@@ -352,7 +352,7 @@ describe("Blob Storage Integrations API", () => {region: "us-east-1",};- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT","/api/public/integrations/blob-storage",invalidBody,@@ -369,7 +369,7 @@ describe("Blob Storage Integrations API", () => {type: "INVALID_TYPE",};- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT","/api/public/integrations/blob-storage",invalidBody,@@ -386,7 +386,7 @@ describe("Blob Storage Integrations API", () => {prefix: "invalid-prefix", // Should end with /};- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("PUT","/api/public/integrations/blob-storage",invalidBody,@@ -403,7 +403,7 @@ describe("Blob Storage Integrations API", () => {projectId: nonExistentProjectId,};- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT","/api/public/integrations/blob-storage",requestBody,@@ -419,7 +419,7 @@ describe("Blob Storage Integrations API", () => {projectId: otherProjectId,};- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT","/api/public/integrations/blob-storage",requestBody,@@ -1481,7 +1481,7 @@ describe("Blob Storage Integrations API", () => {describe("Method validation", () => {it("should return 405 for unsupported methods", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PATCH","/api/public/integrations/blob-storage",undefined,@@ -1569,7 +1569,7 @@ describe("Blob Storage Integrations API", () => {where: { id: testProject1Id },data: { createdAt: POST_CUTOFF },});- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT","/api/public/integrations/blob-storage",{@@ -1595,7 +1595,7 @@ describe("Blob Storage Integrations API", () => {where: { id: testProject1Id },data: { createdAt: POST_CUTOFF },});- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT","/api/public/integrations/blob-storage",{@@ -1649,7 +1649,7 @@ describe("Blob Storage Integrations API", () => {where: { id: testProject1Id },data: { createdAt: POST_CUTOFF },});- const result = await makeAPICall(+ const result = await makeAPICall<{ exportSource: string }>("PUT","/api/public/integrations/blob-storage",{ ...basePayload, projectId: testProject1Id },@@ -1691,7 +1691,7 @@ describe("Blob Storage Integrations API", () => {exportSource: "EVENTS",},});- const result = await makeAPICall(+ const result = await makeAPICall<{ exportSource: string }>("PUT","/api/public/integrations/blob-storage",{ ...basePayload, projectId: testProject1Id },@@ -1763,7 +1763,7 @@ describe("Blob Storage Integrations API", () => {});it("no existing row + legacy source → 400 mentioning the integration cutoff", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT","/api/public/integrations/blob-storage",{@@ -1785,7 +1785,7 @@ describe("Blob Storage Integrations API", () => {it("pre-cutoff existing row + legacy source → 200 (grandfathered)", async () => {await seedIntegration(INTEGRATION_PRE_CUTOFF);- const result = await makeAPICall(+ const result = await makeAPICall<{ exportSource: string }>("PUT","/api/public/integrations/blob-storage",{@@ -1803,7 +1803,7 @@ describe("Blob Storage Integrations API", () => {// Boundary: only rows created strictly before the cutoff are// grandfathered.await seedIntegration(LEGACY_BLOB_EXPORTER_CUTOFF);- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT","/api/public/integrations/blob-storage",{@@ -1821,7 +1821,7 @@ describe("Blob Storage Integrations API", () => {it("post-cutoff existing row + legacy source → 400", async () => {await seedIntegration(INTEGRATION_POST_CUTOFF);- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT","/api/public/integrations/blob-storage",{@@ -1838,7 +1838,7 @@ describe("Blob Storage Integrations API", () => {});it("no existing row + OBSERVATIONS_V2 → 200", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ exportSource: string }>("PUT","/api/public/integrations/blob-storage",{@@ -1855,7 +1855,7 @@ describe("Blob Storage Integrations API", () => {it("no existing row + omitted exportSource → 200 and persists EVENTS", async () => {// New Cloud rows must never get the legacy column default, even on a// pre-cutoff project.- const result = await makeAPICall(+ const result = await makeAPICall<{ exportSource: string }>("PUT","/api/public/integrations/blob-storage",{ ...basePayload, projectId: testProject1Id },diff --git a/web/src/__tests__/server/blob-storage-integration-status-api.servertest.ts b/web/src/__tests__/server/blob-storage-integration-status-api.servertest.tsindex dd03db33d6..c475081c65 100644--- a/web/src/__tests__/server/blob-storage-integration-status-api.servertest.ts+++ b/web/src/__tests__/server/blob-storage-integration-status-api.servertest.ts@@ -406,7 +406,7 @@ describe("Blob Storage Integration Status API - GET /api/public/integrations/blo200,);- expect(new Date(response.body.lastErrorAt).getTime()).toBe(+ expect(new Date(response.body.lastErrorAt!).getTime()).toBe(errorDate.getTime(),);});diff --git a/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts b/web/src/__tests__/server/blob-storage-integration-trpc.servertest.tsindex c81d09e0c7..03ae7dce23 100644--- a/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts+++ b/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts@@ -62,14 +62,18 @@ const prepare = async () => {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: project.id,role: "ADMIN",retentionDays: 30,deletedAt: null,+ hasTraces: false,name: project.name,metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -77,6 +81,10 @@ const prepare = async () => {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},diff --git a/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts b/web/src/__tests__/server/code-eval-test-run-trpc.servertest.tsindex 7f4a2e40c4..ccc4a74443 100644--- a/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts+++ b/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts@@ -83,11 +83,10 @@ async function prepare() {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,v4BetaToggleVisible: false,observationEvals: false,experimentsV4Enabled: false,- monitors: false,- inAppAgent: false,},admin: true,},diff --git a/web/src/__tests__/server/compileChatMessages.servertest.ts b/web/src/__tests__/server/compileChatMessages.servertest.tsindex a9325b97ce..8016d7a4ff 100644--- a/web/src/__tests__/server/compileChatMessages.servertest.ts+++ b/web/src/__tests__/server/compileChatMessages.servertest.ts@@ -12,7 +12,7 @@ describe("compileChatMessages", () => {const promptTemplate = [{ role: "system", content: "You are a helpful assistant." },{- type: ChatMessageType.Placeholder,+ type: ChatMessageType.Placeholder as const,name: "conversation_history",},{ role: "user", content: "{{user_question}}" },@@ -50,7 +50,7 @@ describe("compileChatMessages", () => {const promptTemplate = [{ role: "system", content: "You are a helpful assistant." },{- type: ChatMessageType.Placeholder,+ type: ChatMessageType.Placeholder as const,name: "missing_placeholder",},{ role: "user", content: "Hello" },@@ -67,7 +67,7 @@ describe("compileChatMessages", () => {const promptTemplate = [{ role: "system", content: "You are a helpful assistant." },{- type: ChatMessageType.Placeholder,+ type: ChatMessageType.Placeholder as const,name: "arbitrary_messages",},];@@ -114,7 +114,7 @@ describe("compileChatMessages", () => {content: "You are a helpful assistant. {{system_var}}",},{- type: ChatMessageType.Placeholder,+ type: ChatMessageType.Placeholder as const,name: "history",},{ role: "user", content: "{{user_var}}" },diff --git a/web/src/__tests__/server/createFilterFromFilterState-nullIf.servertest.ts b/web/src/__tests__/server/createFilterFromFilterState-nullIf.servertest.tsindex 901fe02995..acbc360f88 100644--- a/web/src/__tests__/server/createFilterFromFilterState-nullIf.servertest.ts+++ b/web/src/__tests__/server/createFilterFromFilterState-nullIf.servertest.ts@@ -35,7 +35,7 @@ describe("createFilterFromFilterState with emptyEqualsNull", () => {it.each<{desc: string;operator: "is null" | "is not null";- mapping: typeof withEmptyEqualsNull;+ mapping: typeof withoutFlag & { emptyEqualsNull?: boolean };expected: string;}>([{diff --git a/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.ts b/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.tsindex ab1d7cc503..a52759eb1d 100644--- a/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.ts+++ b/web/src/__tests__/server/dashboard-v1-v2-consistency.servertest.ts@@ -68,6 +68,22 @@ function pick<T>(arr: T[], i: number): T {return arr[i % arr.length];}+/**+ * Type-level shim for event fixtures that pass `metadata` (and a stringified+ * `prompt_version`), which EventRecordInsertType does not model. events_full+ * has no `metadata` map column — ClickHouse skips unknown JSONEachRow fields+ * on insert — so the extra key is inert; the cast keeps the fixture unchanged.+ */+type EventInsertInput = Parameters<typeof createEvent>[0];+function asEventInsert(+ event: Omit<EventInsertInput, "prompt_version"> & {+ metadata?: Record<string, string>;+ prompt_version?: string | number | null;+ },+): EventInsertInput {+ return event as unknown as EventInsertInput;+}+/*** Derive v2 events from v1 traces + observations.*@@ -85,36 +101,38 @@ function buildMatchingEvents(// Root events — one per trace.for (const t of traces) {events.push(- createEvent({- id: `t-${t.id}`,- span_id: `t-${t.id}`,- trace_id: t.id,- project_id: t.project_id,- parent_span_id: "",- name: t.name ?? "",- type: "SPAN",- environment: t.environment,- trace_name: t.name ?? "",- user_id: t.user_id ?? "",- session_id: t.session_id ?? null,- tags: t.tags ?? [],- release: t.release ?? null,- version: t.version ?? null,- public: t.public,- bookmarked: t.bookmarked,- input: t.input ?? null,- output: t.output ?? null,- metadata: t.metadata ?? {},- start_time: t.timestamp * 1000,- end_time: null,- cost_details: {},- provided_cost_details: {},- usage_details: {},- provided_usage_details: {},- created_at: t.created_at * 1000,- updated_at: t.updated_at * 1000,- event_ts: t.event_ts * 1000,- }),+ createEvent(+ asEventInsert({+ id: `t-${t.id}`,+ span_id: `t-${t.id}`,+ trace_id: t.id,+ project_id: t.project_id,+ parent_span_id: "",+ name: t.name ?? "",+ type: "SPAN",+ environment: t.environment,+ trace_name: t.name ?? "",+ user_id: t.user_id ?? "",+ session_id: t.session_id ?? null,+ tags: t.tags ?? [],+ release: t.release ?? null,+ version: t.version ?? null,+ public: t.public,+ bookmarked: t.bookmarked,+ input: t.input ?? null,+ output: t.output ?? null,+ metadata: t.metadata ?? {},+ start_time: t.timestamp * 1000,+ end_time: null,+ cost_details: {},+ provided_cost_details: {},+ usage_details: {},+ provided_usage_details: {},+ created_at: t.created_at * 1000,+ updated_at: t.updated_at * 1000,+ event_ts: t.event_ts * 1000,+ }),+ ),);}@@ -123,49 +141,51 @@ function buildMatchingEvents(const traceId = o.trace_id!;const t = traceMap.get(traceId)!;events.push(- createEvent({- id: o.id,- span_id: o.id,- trace_id: traceId,- project_id: o.project_id,- // dev-tables.sh: coalesce(parent_observation_id, concat('t-', trace_id))- parent_span_id: o.parent_observation_id ?? `t-${traceId}`,- name: o.name ?? "",- type: o.type as string,- environment: o.environment,- trace_name: t.name ?? "",- user_id: t.user_id ?? "",- session_id: t.session_id ?? undefined,- tags: t.tags ?? [],- release: t.release ?? null,- version: o.version ?? null,- level: o.level ?? "DEFAULT",- status_message: o.status_message ?? null,- provided_model_name: o.provided_model_name ?? null,- model_parameters: o.model_parameters ?? "{}",- input: o.input ?? null,- output: o.output ?? null,- // dev-tables.sh: mapConcat(obs.metadata, trace.metadata)- metadata: { ...(t.metadata ?? {}), ...(o.metadata ?? {}) },- provided_usage_details: o.provided_usage_details ?? {},- usage_details: o.usage_details ?? {},- provided_cost_details: o.provided_cost_details ?? {},- cost_details: o.cost_details ?? {},- prompt_id: o.prompt_id ?? null,- prompt_name: o.prompt_name ?? null,- prompt_version: o.prompt_version ? String(o.prompt_version) : null,- tool_definitions: o.tool_definitions ?? {},- tool_calls: o.tool_calls ?? [],- tool_call_names: o.tool_call_names ?? [],- start_time: o.start_time * 1000,- end_time: o.end_time ? o.end_time * 1000 : null,- completion_start_time: o.completion_start_time- ? o.completion_start_time * 1000- : null,- created_at: o.created_at * 1000,- updated_at: o.updated_at * 1000,- event_ts: o.event_ts * 1000,- }),+ createEvent(+ asEventInsert({+ id: o.id,+ span_id: o.id,+ trace_id: traceId,+ project_id: o.project_id,+ // dev-tables.sh: coalesce(parent_observation_id, concat('t-', trace_id))+ parent_span_id: o.parent_observation_id ?? `t-${traceId}`,+ name: o.name ?? "",+ type: o.type as string,+ environment: o.environment,+ trace_name: t.name ?? "",+ user_id: t.user_id ?? "",+ session_id: t.session_id ?? undefined,+ tags: t.tags ?? [],+ release: t.release ?? null,+ version: o.version ?? null,+ level: o.level ?? "DEFAULT",+ status_message: o.status_message ?? null,+ provided_model_name: o.provided_model_name ?? null,+ model_parameters: o.model_parameters ?? "{}",+ input: o.input ?? null,+ output: o.output ?? null,+ // dev-tables.sh: mapConcat(obs.metadata, trace.metadata)+ metadata: { ...(t.metadata ?? {}), ...(o.metadata ?? {}) },+ provided_usage_details: o.provided_usage_details ?? {},+ usage_details: o.usage_details ?? {},+ provided_cost_details: o.provided_cost_details ?? {},+ cost_details: o.cost_details ?? {},+ prompt_id: o.prompt_id ?? null,+ prompt_name: o.prompt_name ?? null,+ prompt_version: o.prompt_version ? String(o.prompt_version) : null,+ tool_definitions: o.tool_definitions ?? {},+ tool_calls: o.tool_calls ?? [],+ tool_call_names: o.tool_call_names ?? [],+ start_time: o.start_time * 1000,+ end_time: o.end_time ? o.end_time * 1000 : null,+ completion_start_time: o.completion_start_time+ ? o.completion_start_time * 1000+ : null,+ created_at: o.created_at * 1000,+ updated_at: o.updated_at * 1000,+ event_ts: o.event_ts * 1000,+ }),+ ),);}@@ -487,6 +507,7 @@ describe("dashboard v1 vs v2 consistency", () => {name: "Test Project",hasTraces: true,metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -496,6 +517,8 @@ describe("dashboard v1 vs v2 consistency", () => {templateFlag: true,v4BetaToggleVisible: false,observationEvals: false,+ experimentsV4Enabled: false,+ searchBar: false,},admin: true,},@@ -1496,145 +1519,153 @@ describe("dashboard v1 vs v2 consistency", () => {emptyTraceNameTraceId = v4();const childObsId = v4();- const rootEventEmpty = createEvent({- id: `t-${emptyTraceNameTraceId}`,- span_id: `t-${emptyTraceNameTraceId}`,- trace_id: emptyTraceNameTraceId,- project_id: fallbackProjectId,- parent_span_id: "",- name: "FallbackTraceName",- type: "SPAN",- environment: "default",- trace_name: "",- user_id: "",- session_id: null,- tags: [],- release: null,- version: null,- public: false,- bookmarked: false,- input: null,- output: null,- metadata: {},- start_time: baseTimeUs,- end_time: null,- cost_details: {},- provided_cost_details: {},- usage_details: {},- provided_usage_details: {},- created_at: baseTimeUs,- updated_at: baseTimeUs,- event_ts: baseTimeUs,- });+ const rootEventEmpty = createEvent(+ asEventInsert({+ id: `t-${emptyTraceNameTraceId}`,+ span_id: `t-${emptyTraceNameTraceId}`,+ trace_id: emptyTraceNameTraceId,+ project_id: fallbackProjectId,+ parent_span_id: "",+ name: "FallbackTraceName",+ type: "SPAN",+ environment: "default",+ trace_name: "",+ user_id: "",+ session_id: null,+ tags: [],+ release: null,+ version: null,+ public: false,+ bookmarked: false,+ input: null,+ output: null,+ metadata: {},+ start_time: baseTimeUs,+ end_time: null,+ cost_details: {},+ provided_cost_details: {},+ usage_details: {},+ provided_usage_details: {},+ created_at: baseTimeUs,+ updated_at: baseTimeUs,+ event_ts: baseTimeUs,+ }),+ );- const childEventEmpty = createEvent({- id: childObsId,- span_id: childObsId,- trace_id: emptyTraceNameTraceId,- project_id: fallbackProjectId,- parent_span_id: `t-${emptyTraceNameTraceId}`,- name: "ChildObservationName",- type: "GENERATION",- environment: "default",- trace_name: "",- user_id: "",- session_id: null,- tags: [],- release: null,- version: null,- level: "DEFAULT",- status_message: null,- provided_model_name: "gpt-4o-mini-2024-07-18",- model_parameters: "{}",- input: null,- output: null,- metadata: {},- provided_usage_details: {},- usage_details: {},- provided_cost_details: {},- cost_details: {},- prompt_id: null,- prompt_name: null,- prompt_version: null,- start_time: baseTimeUs + 100_000,- end_time: baseTimeUs + 500_000,- completion_start_time: null,- created_at: baseTimeUs + 100_000,- updated_at: baseTimeUs + 500_000,- event_ts: baseTimeUs + 500_000,- });+ const childEventEmpty = createEvent(+ asEventInsert({+ id: childObsId,+ span_id: childObsId,+ trace_id: emptyTraceNameTraceId,+ project_id: fallbackProjectId,+ parent_span_id: `t-${emptyTraceNameTraceId}`,+ name: "ChildObservationName",+ type: "GENERATION",+ environment: "default",+ trace_name: "",+ user_id: "",+ session_id: null,+ tags: [],+ release: null,+ version: null,+ level: "DEFAULT",+ status_message: null,+ provided_model_name: "gpt-4o-mini-2024-07-18",+ model_parameters: "{}",+ input: null,+ output: null,+ metadata: {},+ provided_usage_details: {},+ usage_details: {},+ provided_cost_details: {},+ cost_details: {},+ prompt_id: null,+ prompt_name: null,+ prompt_version: null,+ start_time: baseTimeUs + 100_000,+ end_time: baseTimeUs + 500_000,+ completion_start_time: null,+ created_at: baseTimeUs + 100_000,+ updated_at: baseTimeUs + 500_000,+ event_ts: baseTimeUs + 500_000,+ }),+ );// ── Trace 2: populated trace_name (happy path) ──populatedTraceNameTraceId = v4();const childObsId2 = v4();- const rootEventPopulated = createEvent({- id: `t-${populatedTraceNameTraceId}`,- span_id: `t-${populatedTraceNameTraceId}`,- trace_id: populatedTraceNameTraceId,- project_id: fallbackProjectId,- parent_span_id: "",- name: "PopulatedTraceName",- type: "SPAN",- environment: "default",- trace_name: "PopulatedTraceName",- user_id: "",- session_id: null,- tags: [],- release: null,- version: null,- public: false,- bookmarked: false,- input: null,- output: null,- metadata: {},- start_time: baseTimeUs + 1_000_000,- end_time: null,- cost_details: {},- provided_cost_details: {},- usage_details: {},- provided_usage_details: {},- created_at: baseTimeUs + 1_000_000,- updated_at: baseTimeUs + 1_000_000,- event_ts: baseTimeUs + 1_000_000,- });+ const rootEventPopulated = createEvent(+ asEventInsert({+ id: `t-${populatedTraceNameTraceId}`,+ span_id: `t-${populatedTraceNameTraceId}`,+ trace_id: populatedTraceNameTraceId,+ project_id: fallbackProjectId,+ parent_span_id: "",+ name: "PopulatedTraceName",+ type: "SPAN",+ environment: "default",+ trace_name: "PopulatedTraceName",+ user_id: "",+ session_id: null,+ tags: [],+ release: null,+ version: null,+ public: false,+ bookmarked: false,+ input: null,+ output: null,+ metadata: {},+ start_time: baseTimeUs + 1_000_000,+ end_time: null,+ cost_details: {},+ provided_cost_details: {},+ usage_details: {},+ provided_usage_details: {},+ created_at: baseTimeUs + 1_000_000,+ updated_at: baseTimeUs + 1_000_000,+ event_ts: baseTimeUs + 1_000_000,+ }),+ );- const childEventPopulated = createEvent({- id: childObsId2,- span_id: childObsId2,- trace_id: populatedTraceNameTraceId,- project_id: fallbackProjectId,- parent_span_id: `t-${populatedTraceNameTraceId}`,- name: "SomeObservation",- type: "GENERATION",- environment: "default",- trace_name: "PopulatedTraceName",- user_id: "",- session_id: null,- tags: [],- release: null,- version: null,- level: "DEFAULT",- status_message: null,- provided_model_name: "gpt-4o-mini-2024-07-18",- model_parameters: "{}",- input: null,- output: null,- metadata: {},- provided_usage_details: {},- usage_details: {},- provided_cost_details: {},- cost_details: {},- prompt_id: null,- prompt_name: null,- prompt_version: null,- start_time: baseTimeUs + 1_100_000,- end_time: baseTimeUs + 1_500_000,- completion_start_time: null,- created_at: baseTimeUs + 1_100_000,- updated_at: baseTimeUs + 1_500_000,- event_ts: baseTimeUs + 1_500_000,- });+ const childEventPopulated = createEvent(+ asEventInsert({+ id: childObsId2,+ span_id: childObsId2,+ trace_id: populatedTraceNameTraceId,+ project_id: fallbackProjectId,+ parent_span_id: `t-${populatedTraceNameTraceId}`,+ name: "SomeObservation",+ type: "GENERATION",+ environment: "default",+ trace_name: "PopulatedTraceName",+ user_id: "",+ session_id: null,+ tags: [],+ release: null,+ version: null,+ level: "DEFAULT",+ status_message: null,+ provided_model_name: "gpt-4o-mini-2024-07-18",+ model_parameters: "{}",+ input: null,+ output: null,+ metadata: {},+ provided_usage_details: {},+ usage_details: {},+ provided_cost_details: {},+ cost_details: {},+ prompt_id: null,+ prompt_name: null,+ prompt_version: null,+ start_time: baseTimeUs + 1_100_000,+ end_time: baseTimeUs + 1_500_000,+ completion_start_time: null,+ created_at: baseTimeUs + 1_100_000,+ updated_at: baseTimeUs + 1_500_000,+ event_ts: baseTimeUs + 1_500_000,+ }),+ );// ── Scores for both traces (for scores view test) ──const scoreTs = baseTime + 200;diff --git a/web/src/__tests__/server/dashboard-widget-version.servertest.ts b/web/src/__tests__/server/dashboard-widget-version.servertest.tsindex 0e352e94ca..f2599f9ab8 100644--- a/web/src/__tests__/server/dashboard-widget-version.servertest.ts+++ b/web/src/__tests__/server/dashboard-widget-version.servertest.ts@@ -70,6 +70,7 @@ describe("dashboard widget minVersion", () => {name: "Test Project",hasTraces: true,metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -79,6 +80,8 @@ describe("dashboard widget minVersion", () => {templateFlag: true,v4BetaToggleVisible: false,observationEvals: false,+ experimentsV4Enabled: false,+ searchBar: false,},admin: true,},diff --git a/web/src/__tests__/server/dataset-item-media-references.servertest.ts b/web/src/__tests__/server/dataset-item-media-references.servertest.tsindex f4ef1443df..77e9d75888 100644--- a/web/src/__tests__/server/dataset-item-media-references.servertest.ts+++ b/web/src/__tests__/server/dataset-item-media-references.servertest.ts@@ -56,9 +56,9 @@ const session: Session = {},],featureFlags: {+ searchBar: false,excludeClickhouseRead: false,templateFlag: true,- inAppAgent: false,v4BetaToggleVisible: false,observationEvals: false,experimentsV4Enabled: false,@@ -347,15 +347,17 @@ describe("Dataset item media tRPC procedures", () => {"x-amz-checksum-sha256": sha256Hash,"x-ms-blob-type": "BlockBlob",});- expect(result.uploadHeaders["x-ms-version"]).toBeDefined();+ expect(+ (result.uploadHeaders as { "x-ms-version"?: string })["x-ms-version"],+ ).toBeDefined();const uploadResponse = await fetch(result.uploadUrl!, {method: "PUT",- body: fileBytes,+ body: fileBytes as BodyInit,headers: {"Content-Type": MediaContentType.PNG,...result.uploadHeaders,- },+ } as HeadersInit,});await caller.datasets.markItemMediaUploadComplete({diff --git a/web/src/__tests__/server/datasets-metrics.servertest.ts b/web/src/__tests__/server/datasets-metrics.servertest.tsindex 3bc1fce308..63f69db08c 100644--- a/web/src/__tests__/server/datasets-metrics.servertest.ts+++ b/web/src/__tests__/server/datasets-metrics.servertest.ts@@ -19,6 +19,9 @@ const session: Session = {role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: projectId,@@ -26,6 +29,9 @@ const session: Session = {retentionDays: 30,deletedAt: null,name: "Test Project",+ hasTraces: true,+ metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -33,13 +39,17 @@ const session: Session = {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,+ searchBar: false,},admin: true,},environment: {} as any,};-const ctx = createInnerTRPCContext({ session });+const ctx = createInnerTRPCContext({ session, headers: {} });const caller = appRouter.createCaller({ ...ctx, prisma });describe("datasets.allDatasetsMetrics", () => {diff --git a/web/src/__tests__/server/datasets-remote-experiment.servertest.ts b/web/src/__tests__/server/datasets-remote-experiment.servertest.tsindex cdee5a7657..bf051b46c8 100644--- a/web/src/__tests__/server/datasets-remote-experiment.servertest.ts+++ b/web/src/__tests__/server/datasets-remote-experiment.servertest.ts@@ -25,6 +25,8 @@ const prepare = async () => {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: setup.projectId,@@ -32,14 +34,20 @@ const prepare = async () => {name: "Test Project",deletedAt: null,retentionDays: null,+ hasTraces: false,metadata: {},+ createdAt: new Date().toISOString(),},],},],featureFlags: {+ searchBar: false,templateFlag: true,excludeClickhouseRead: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},diff --git a/web/src/__tests__/server/datasets-trpc.servertest.ts b/web/src/__tests__/server/datasets-trpc.servertest.tsindex 6bac063eff..00702c9219 100644--- a/web/src/__tests__/server/datasets-trpc.servertest.ts+++ b/web/src/__tests__/server/datasets-trpc.servertest.ts@@ -34,8 +34,10 @@ async function prepare({role: projectRole,retentionDays: 30,deletedAt: null,+ hasTraces: false,name: project.name,metadata: {},+ createdAt: new Date().toISOString(),},],aiFeaturesEnabled: false,@@ -43,8 +45,12 @@ async function prepare({},],featureFlags: {+ searchBar: false,excludeClickhouseRead: false,templateFlag: true,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin,},diff --git a/web/src/__tests__/server/evals-trpc.servertest.ts b/web/src/__tests__/server/evals-trpc.servertest.tsindex 654fe064aa..3f39fed48a 100644--- a/web/src/__tests__/server/evals-trpc.servertest.ts+++ b/web/src/__tests__/server/evals-trpc.servertest.ts@@ -76,14 +76,18 @@ async function prepare() {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: project.id,role: "ADMIN",retentionDays: 30,deletedAt: null,+ hasTraces: false,name: project.name,metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -91,6 +95,10 @@ async function prepare() {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},@@ -100,7 +108,7 @@ async function prepare() {},};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });const caller = appRouter.createCaller({ ...ctx, prisma });__orgIds.push(org.id);@@ -1492,7 +1500,10 @@ describe("evals trpc", () => {expires: session.expires,environment: session.environment,};- const limitedCtx = createInnerTRPCContext({ session: limitedSession });+ const limitedCtx = createInnerTRPCContext({+ session: limitedSession,+ headers: {},+ });const limitedCaller = appRouter.createCaller({ ...limitedCtx, prisma });// Create a job@@ -1757,7 +1768,10 @@ describe("evals trpc", () => {expires: session.expires,environment: session.environment,};- const limitedCtx = createInnerTRPCContext({ session: limitedSession });+ const limitedCtx = createInnerTRPCContext({+ session: limitedSession,+ headers: {},+ });const limitedCaller = appRouter.createCaller({ ...limitedCtx, prisma });const evalTemplate = await createTemplateVersion(diff --git a/web/src/__tests__/server/execute-query-stream.servertest.ts b/web/src/__tests__/server/execute-query-stream.servertest.tsindex 3069fe66de..3d06d297ea 100644--- a/web/src/__tests__/server/execute-query-stream.servertest.ts+++ b/web/src/__tests__/server/execute-query-stream.servertest.ts@@ -1,5 +1,5 @@import { v4 } from "uuid";-import { createMocks } from "node-mocks-http";+import { createMocks, type Body } from "node-mocks-http";import type { NextApiRequest, NextApiResponse } from "next";import {createOrgProjectAndApiKey,@@ -29,7 +29,7 @@ vi.mock("../../server/adminAccessWebhook", () => ({function createPostMocks(body: unknown) {const { req, res } = createMocks<NextApiRequest, NextApiResponse>({method: "POST",- body,+ body: body as Body,});// node-mocks-http doesn't implement flushHeadersres.flushHeaders = vi.fn();diff --git a/web/src/__tests__/server/experiments-versioning.servertest.ts b/web/src/__tests__/server/experiments-versioning.servertest.tsindex 956ab832b9..28a6a1059f 100644--- a/web/src/__tests__/server/experiments-versioning.servertest.ts+++ b/web/src/__tests__/server/experiments-versioning.servertest.ts@@ -43,8 +43,10 @@ async function prepare() {role: "ADMIN",retentionDays: 30,deletedAt: null,+ hasTraces: false,name: project.name,metadata: {},+ createdAt: new Date().toISOString(),},],aiFeaturesEnabled: false,@@ -52,8 +54,12 @@ async function prepare() {},],featureFlags: {+ searchBar: false,excludeClickhouseRead: false,templateFlag: true,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},diff --git a/web/src/__tests__/server/fts-rewrites.servertest.ts b/web/src/__tests__/server/fts-rewrites.servertest.tsindex 0d3f778d92..25e56aa26d 100644--- a/web/src/__tests__/server/fts-rewrites.servertest.ts+++ b/web/src/__tests__/server/fts-rewrites.servertest.ts@@ -139,17 +139,19 @@ maybeEventsTable("FTS filter rewrites", () => {it.each(Array.from(FTS_EVENTS_TABLES).flatMap((table) =>Array.from(FTS_TEXT_FIELDS).flatMap((field) =>- [- { operator: "=", value: "alpha" },- { operator: "=", value: "ALPHA" },- { operator: "=", value: "привет" },- { operator: "=", value: "東京" },- { operator: "=", value: "[email protected]" },- { operator: "=", value: "!!!" },- { operator: "contains", value: "alpha" },- { operator: "starts with", value: "alpha" },- { operator: "ends with", value: "alpha" },- ].map((testCase) => ({+ (+ [+ { operator: "=", value: "alpha" },+ { operator: "=", value: "ALPHA" },+ { operator: "=", value: "привет" },+ { operator: "=", value: "東京" },+ { operator: "=", value: "[email protected]" },+ { operator: "=", value: "!!!" },+ { operator: "contains", value: "alpha" },+ { operator: "starts with", value: "alpha" },+ { operator: "ends with", value: "alpha" },+ ] as const+ ).map((testCase) => ({table,field,...testCase,@@ -184,13 +186,15 @@ maybeEventsTable("FTS filter rewrites", () => {it.each(Array.from(FTS_EVENTS_TABLES).flatMap((table) =>- [- { operator: "=", value: "alpha" },- { operator: "contains", value: "alpha" },- { operator: "starts with", value: "alpha" },- { operator: "ends with", value: "alpha" },- { operator: "does not contain", value: "alpha" },- ].map((testCase) => ({+ (+ [+ { operator: "=", value: "alpha" },+ { operator: "contains", value: "alpha" },+ { operator: "starts with", value: "alpha" },+ { operator: "ends with", value: "alpha" },+ { operator: "does not contain", value: "alpha" },+ ] as const+ ).map((testCase) => ({table,...testCase,})),diff --git a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.tsindex 9581c2f84a..b98bce59d7 100644--- a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts@@ -194,7 +194,7 @@ describe("in-app agent public API route auth", () => {resume: {approved: true,approvalRequest: {- type: "tool_approval_request",+ type: "tool_approval_request" as const,toolCallId: "tool-call-1",toolName: "langfuse_upsertDataset",args: { name: "Approved dataset" },diff --git a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts b/web/src/__tests__/server/in-app-agent-persistence.servertest.tsindex f6a47c924f..4302a0fe34 100644--- a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts@@ -7,6 +7,7 @@ vi.mock("@langfuse/shared/src/server", async () => {});import type { Session } from "next-auth";+import type { Flags } from "@/src/features/feature-flags/types";import { EventType } from "@ag-ui/core";import { randomUUID } from "crypto";import { vi } from "vitest";@@ -103,7 +104,7 @@ describe("in-app agent persistence", () => {],},],- featureFlags: {},+ featureFlags: {} as Flags,admin: false,},environment: {} as any,diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.tsindex 359a9fa3ca..6ba61ab1e5 100644--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts@@ -16,6 +16,27 @@ import { decodeFiltersGeneric } from "@/src/features/filters/lib/filter-query-enimport "@/src/features/mcp/server/bootstrap";import { toolRegistry } from "@/src/features/mcp/server/registry";import type { MastraAgent } from "@ag-ui/mastra";+import type { Langfuse } from "langfuse";+import type { InAppAgentTracingConfig } from "@/src/ee/features/in-app-agent/server/instrumentation";++// Shape of the tool entries the mocked MCP client feeds into the Agent+// constructor. `Agent`'s own `tools` type is a `DynamicArgument` union that+// does not allow property access, so tests read it through this view.+type MockedAgentTools = Record<+ string,+ | {+ id?: string;+ server?: string;+ requireApproval?: boolean;+ execute?: (...args: unknown[]) => Promise<unknown>;+ }+ | undefined+>;++const getAgentTools = (+ agentConfig: { tools?: unknown } | undefined,+): MockedAgentTools | undefined =>+ agentConfig?.tools as MockedAgentTools | undefined;const adapterEvents = vi.hoisted(() => ({items: [] as AgUiEvent[],@@ -48,7 +69,10 @@ const instrumentationMocks = vi.hoisted(() => {});const promptMocks = vi.hoisted(() => ({- compile: vi.fn(() => "Prompt-managed assistant instructions"),+ compile: vi.fn(+ (_variables: Record<string, unknown>) =>+ "Prompt-managed assistant instructions",+ ),getPrompt: vi.fn(),}));@@ -171,7 +195,7 @@ const createPatchedChunkProcessor = () => {const onError = vi.fn();const flush = vi.fn();const adapter = {- createChunkProcessor: vi.fn(() => ({+ createChunkProcessor: vi.fn((_options: { onError: unknown }) => ({handleChunk: (chunk: unknown) => {forwardedChunks.push(chunk);return false;@@ -566,7 +590,7 @@ describe("createAgUiStream", () => {const eventOrder: string[] = [];const langfuseClient = {getPrompt: promptMocks.getPrompt,- };+ } as unknown as Langfuse;adapterEvents.inputs = [];adapterEvents.items = [@@ -645,13 +669,7 @@ describe("createAgUiStream", () => {},langfuseClient,useLocalPrompt: false,- langfuseTracing: {- environment: "langfuse-in-app-agent",- metadata: { langfuse_project_id: "project-1" },- user: { id: "user-1" },- traceId: "0123456789abcdef0123456789abcdef",- targetProjectId: "project-1",- },+ langfuseTracing: createTestTracingConfig(),},});const streamedText = await readStream(stream, (event) => {@@ -701,33 +719,30 @@ describe("createAgUiStream", () => {},},});- expect(agentConfig?.tools).not.toHaveProperty("langfuse_search");- expect(agentConfig?.tools?.langfuse_getHealth).not.toHaveProperty(+ const agentTools = getAgentTools(agentConfig);+ expect(agentTools).not.toHaveProperty("langfuse_search");+ expect(agentTools?.langfuse_getHealth).not.toHaveProperty("requireApproval",);- expect(agentConfig?.tools?.langfuseDocs_search).not.toHaveProperty(+ expect(agentTools?.langfuseDocs_search).not.toHaveProperty("requireApproval",);- expect(agentConfig?.tools?.langfuseDocs_fetch).not.toHaveProperty(+ expect(agentTools?.langfuseDocs_fetch).not.toHaveProperty("requireApproval",);expect(- agentConfig?.tools?.[IN_APP_AGENT_REDIRECT_TOOL_NAME]?.requireApproval,+ agentTools?.[IN_APP_AGENT_REDIRECT_TOOL_NAME]?.requireApproval,).not.toBe(true);- const docsSearchTool = agentConfig?.tools?.langfuseDocs_search;+ const docsSearchTool = agentTools?.langfuseDocs_search;await expect(docsSearchTool?.execute?.({}, {})).resolves.toMatchObject({_meta: expect.objectContaining({choices: expect.any(Array),}),});- const redirectTool = vi.mocked(Agent).mock.calls[0]?.[0]?.tools?.[+ const redirectTool = getAgentTools(vi.mocked(Agent).mock.calls[0]?.[0])?.[IN_APP_AGENT_REDIRECT_TOOL_NAME- ] as- | {- execute?: (input: unknown) => Promise<unknown>;- }- | undefined;+ ];await expect(redirectTool?.execute?.({@@ -834,9 +849,11 @@ describe("createAgUiStream", () => {}),model: "eu.anthropic.claude-opus-4-8",});- const onStepFinish = agentConfig?.defaultOptions?.onStepFinish as- | ((event: unknown) => void)- | undefined;+ const onStepFinish = (+ agentConfig?.defaultOptions as+ | { onStepFinish?: (event: unknown) => void }+ | undefined+ )?.onStepFinish;expect(onStepFinish).toEqual(expect.any(Function));onStepFinish?.({ usage: { inputTokens: 10, outputTokens: 5 } });expect(@@ -885,7 +902,7 @@ describe("createAgUiStream", () => {};const langfuseClient = {getPrompt: promptMocks.getPrompt,- };+ } as unknown as Langfuse;adapterEvents.items = [{@@ -948,7 +965,7 @@ describe("createAgUiStream", () => {const persistedEvents: AgUiEvent[] = [];const langfuseClient = {getPrompt: promptMocks.getPrompt,- };+ } as unknown as Langfuse;const stream = await createAgUiStream({input,@@ -1089,12 +1106,8 @@ describe("createAgUiStream", () => {});const agentConfig = vi.mocked(Agent).mock.calls[0]?.[0];- const createScoreConfigTool = agentConfig?.tools- ?.langfuse_createScoreConfig as- | {- execute?: ReturnType<typeof vi.fn>;- }- | undefined;+ const createScoreConfigTool =+ getAgentTools(agentConfig)?.langfuse_createScoreConfig;expect(createScoreConfigTool?.execute).toHaveBeenCalledWith({name: "readiness",@@ -1133,7 +1146,7 @@ describe("createAgUiStream", () => {const onError = vi.fn();const langfuseClient = {getPrompt: promptMocks.getPrompt,- };+ } as unknown as Langfuse;const stream = await createAgUiStream({input,@@ -1162,7 +1175,12 @@ describe("createAgUiStream", () => {await readStream(stream);expect(onError).not.toHaveBeenCalled();- const resumedMessages = adapterEvents.inputs[0]?.messages ?? [];+ const resumedMessages =+ (+ adapterEvents.inputs[0] as {+ messages?: { id: string; role: string; content?: unknown }[];+ }+ )?.messages ?? [];const retryGuidanceMessage = resumedMessages.find((message) =>message.id === "tool-call-1-approval-tool-error-guidance" &&@@ -1278,7 +1296,7 @@ describe("createAgUiStream", () => {adapterEvents.items = [];const langfuseClient = {getPrompt: promptMocks.getPrompt,- };+ } as unknown as Langfuse;const stream = await createAgUiStream({input,@@ -1349,7 +1367,7 @@ describe("createAgUiStream", () => {];const langfuseClient = {getPrompt: promptMocks.getPrompt,- };+ } as unknown as Langfuse;const persistedEvents: AgUiEvent[] = [];const streamedEvents: AgUiEvent[] = [];const onComplete = vi.fn();@@ -1500,7 +1518,7 @@ describe("createAgUiStream", () => {adapterEvents.items = [];const langfuseClient = {getPrompt: promptMocks.getPrompt,- };+ } as unknown as Langfuse;const stream = await createAgUiStream({input,@@ -1524,13 +1542,9 @@ describe("createAgUiStream", () => {});await readStream(stream);- const redirectTool = vi.mocked(Agent).mock.calls[0]?.[0]?.tools?.[+ const redirectTool = getAgentTools(vi.mocked(Agent).mock.calls[0]?.[0])?.[IN_APP_AGENT_REDIRECT_TOOL_NAME- ] as- | {- execute?: (input: unknown) => Promise<unknown>;- }- | undefined;+ ];const result = await redirectTool?.execute?.({label: "Open traces tagged checkout",@@ -1584,7 +1598,7 @@ describe("createAgUiStream", () => {const runErrorMessage = "AWS credential provider failed: Token is expired.";const langfuseClient = {getPrompt: promptMocks.getPrompt,- };+ } as unknown as Langfuse;adapterEvents.items = [{@@ -1716,14 +1730,17 @@ function createToolApprovalResumeInput(approved: boolean) {};}-function createTestTracingConfig() {+function createTestTracingConfig(): InAppAgentTracingConfig {+ // Intentionally keeps the historical fixture shape (traceId instead of+ // runId, no user.isAdmin); instrumentation is mocked in these tests and the+ // config is only spread through, so the runtime payload must stay as-is.return {environment: "langfuse-in-app-agent",metadata: { langfuse_project_id: "project-1" },user: { id: "user-1" },traceId: "0123456789abcdef0123456789abcdef",targetProjectId: "project-1",- };+ } as unknown as InAppAgentTracingConfig;}function parseEvents(chunk: string) {diff --git a/web/src/__tests__/server/llm-api-key.servertest.ts b/web/src/__tests__/server/llm-api-key.servertest.tsindex 60142f3b87..ae67b3d159 100644--- a/web/src/__tests__/server/llm-api-key.servertest.ts+++ b/web/src/__tests__/server/llm-api-key.servertest.ts@@ -62,7 +62,9 @@ describe("llmApiKey.all RPC", () => {const setup = await createOrgProjectAndApiKey();projectId = setup.projectId;orgId = setup.orgId;- mockFetchLLMCompletion.mockReset().mockResolvedValue({});+ mockFetchLLMCompletion+ .mockReset()+ .mockResolvedValue({} as Awaited<ReturnType<typeof fetchLLMCompletion>>);session = {expires: "1",@@ -78,6 +80,8 @@ describe("llmApiKey.all RPC", () => {cloudConfig: undefined,name: "Test Organization",metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: projectId,@@ -85,14 +89,20 @@ describe("llmApiKey.all RPC", () => {name: "Test Project",deletedAt: null,retentionDays: null,+ hasTraces: false,metadata: {},+ createdAt: new Date().toISOString(),},],},],featureFlags: {+ searchBar: false,templateFlag: true,excludeClickhouseRead: false,+ observationEvals: false,+ v4BetaToggleVisible: false,+ experimentsV4Enabled: false,},admin: true,},@@ -540,7 +550,7 @@ describe("llmApiKey.all RPC", () => {const llmConnection = mockFetchLLMCompletion.mock.calls[0][0].llmConnection;expect(llmConnection.baseURL).toBe("https://api.openai.com/v1");expect(decrypt(llmConnection.secretKey)).toBe("sk-original");- expect(JSON.parse(decrypt(llmConnection.extraHeaders))).toEqual(+ expect(JSON.parse(decrypt(llmConnection.extraHeaders!))).toEqual(existingExtraHeaders,);});diff --git a/web/src/__tests__/server/llm-connections-api.servertest.ts b/web/src/__tests__/server/llm-connections-api.servertest.tsindex 2f0a37bce0..c8e40e3adb 100644--- a/web/src/__tests__/server/llm-connections-api.servertest.ts+++ b/web/src/__tests__/server/llm-connections-api.servertest.ts@@ -382,7 +382,7 @@ describe("/api/public/llm-connections API Endpoints", () => {});it("should reject creating a connection with a localhost baseURL", async () => {- const response = await makeAPICall(+ const response = await makeAPICall<{ message: string }>("PUT","/api/public/llm-connections",{diff --git a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts b/web/src/__tests__/server/mcp-public-api-tools.servertest.tsindex 62e714e253..7fbf317e82 100644--- a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts+++ b/web/src/__tests__/server/mcp-public-api-tools.servertest.ts@@ -300,7 +300,7 @@ describe("MCP public API tools", () => {queueId: queue.id,objectId: uuidv4(),objectType: "TRACE",- },+ } as unknown as Parameters<typeof handleCreateAnnotationQueueItem>[0],context,)) as { id: string; status: string };expect(queueItem.status).toBe("PENDING");@@ -727,7 +727,12 @@ describe("MCP public API tools", () => {it("covers health public API route and cross-project recent-event checks", async () => {const { context } = await createMcpTestSetup();- await expect(handleGetHealth({}, context)).resolves.toMatchObject({+ await expect(+ handleGetHealth(+ {} as unknown as Parameters<typeof handleGetHealth>[0],+ context,+ ),+ ).resolves.toMatchObject({status: "OK",version: expect.any(String),});@@ -750,7 +755,12 @@ describe("MCP public API tools", () => {]);await expect(- handleGetHealth({ failIfNoRecentEvents: true }, context),+ handleGetHealth(+ { failIfNoRecentEvents: true } as unknown as Parameters<+ typeof handleGetHealth+ >[0],+ context,+ ),).resolves.toMatchObject({status: "OK",version: expect.any(String),@@ -852,7 +862,7 @@ describe("MCP public API tools", () => {dataType: "NUMERIC",numericMinValue: 0,numericMaxValue: 1,- },+ } as unknown as Parameters<typeof handleCreateScoreConfig>[0],context,)) as { id: string; name: string };expect(scoreConfig.name).toBe(scoreConfigName);diff --git a/web/src/__tests__/server/mcp-tools-read.servertest.ts b/web/src/__tests__/server/mcp-tools-read.servertest.tsindex 1284c109d3..1ca115934b 100644--- a/web/src/__tests__/server/mcp-tools-read.servertest.ts+++ b/web/src/__tests__/server/mcp-tools-read.servertest.ts@@ -677,11 +677,22 @@ describe("MCP Read Tools", () => {});it("should expose object-shaped advanced filters in the tool schema", () => {- const filterSchema = listObservationsTool.inputSchema.properties- .filter as+ const filterSchema = (+ listObservationsTool.inputSchema.properties as Record<string, unknown>+ ).filter as| {type?: string;items?: {+ type?: string;+ required?: string[];+ properties?: Record<+ string,+ {+ const?: unknown;+ enum?: unknown[];+ type?: string;+ }+ >;anyOf?: Array<{type?: string;properties?: Record<@@ -1319,7 +1330,10 @@ describe("MCP Read Tools", () => {});it("should expose object-shaped metrics query input in the tool schema", () => {- const properties = queryMetricsTool.inputSchema.properties;+ const properties = queryMetricsTool.inputSchema.properties as Record<+ string,+ unknown+ >;expect(properties.view).toBeDefined();expect(properties.dimensions).toBeDefined();@@ -1361,7 +1375,7 @@ describe("MCP Read Tools", () => {},],...metricsWindow,- },+ } as unknown as Parameters<typeof handleQueryMetrics>[0],context,),);@@ -1409,7 +1423,7 @@ describe("MCP Read Tools", () => {],orderBy: [{ field: "count", direction: "desc" }],...metricsWindow,- },+ } as unknown as Parameters<typeof handleQueryMetrics>[0],context,),);@@ -1478,7 +1492,7 @@ describe("MCP Read Tools", () => {],orderBy: [{ field: "value", direction: "desc" }],...metricsWindow,- },+ } as unknown as Parameters<typeof handleQueryMetrics>[0],context,),);@@ -1501,7 +1515,7 @@ describe("MCP Read Tools", () => {metrics: [{ measure: "count", aggregation: "count" }],orderBy: [{ field: "observations.name", direction: "asc" }],...metricsWindow,- },+ } as unknown as Parameters<typeof handleQueryMetrics>[0],context,),).rejects.toThrow(/Use returned metric aliases.*getMetricsSchema/i);@@ -1537,7 +1551,7 @@ describe("MCP Read Tools", () => {},],...metricsWindow,- },+ } as unknown as Parameters<typeof handleQueryMetrics>[0],context,),);@@ -1576,7 +1590,7 @@ describe("MCP Read Tools", () => {],config: { row_limit: 5 },...metricsWindow,- },+ } as unknown as Parameters<typeof handleQueryMetrics>[0],context,),);@@ -1595,7 +1609,7 @@ describe("MCP Read Tools", () => {metrics: [{ measure: "count", aggregation: "count" }],orderBy: [{ field: "count_count", direction: "desc" }],...metricsWindow,- },+ } as unknown as Parameters<typeof handleQueryMetrics>[0],context,),).rejects.toThrow(@@ -1666,7 +1680,9 @@ describe("MCP Read Tools", () => {});it("should be available to in-app agent keys", async () => {- const context = mockServerContext({ isInAppAgentKey: true });+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });await expect(toolRegistry.getEnabledTool(getObservationTool.name, context),@@ -1788,7 +1804,9 @@ describe("MCP Read Tools", () => {});it("should be available to in-app agent keys", async () => {- const context = mockServerContext({ isInAppAgentKey: true });+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });await expect(toolRegistry.getEnabledTool(@@ -2050,7 +2068,7 @@ describe("MCP Read Tools", () => {dataType: "NUMERIC",url: buildTraceUrl({projectId,- traceId: matchingScore.trace_id,+ traceId: matchingScore.trace_id!,}),}),]);@@ -2106,7 +2124,7 @@ describe("MCP Read Tools", () => {name: score.name,dataType: "NUMERIC",value: 0.8,- url: buildTraceUrl({ projectId, traceId: score.trace_id }),+ url: buildTraceUrl({ projectId, traceId: score.trace_id! }),});});@@ -2363,7 +2381,10 @@ describe("MCP Read Tools", () => {])("should create %s score configs", async (_type, input) => {const { context, projectId, apiKeyId } = await createMcpTestSetup();- const result = (await handleCreateScoreConfig(input, context)) as any;+ const result = (await handleCreateScoreConfig(+ input as unknown as Parameters<typeof handleCreateScoreConfig>[0],+ context,+ )) as any;expect(result).toMatchObject({projectId,@@ -2389,7 +2410,7 @@ describe("MCP Read Tools", () => {{name: `mcp-bool-${nanoid(8)}`,dataType: "BOOLEAN",- },+ } as unknown as Parameters<typeof handleCreateScoreConfig>[0],context,);@@ -2414,7 +2435,7 @@ describe("MCP Read Tools", () => {{ label: "Duplicate", value: 1 },{ label: "Duplicate", value: 2 },],- },+ } as unknown as Parameters<typeof handleCreateScoreConfig>[0],context,),).rejects.toThrow(/Category labels must be unique/i);@@ -2443,7 +2464,7 @@ describe("MCP Read Tools", () => {{name: "css-injection}*{background:red}/*",dataType: "TEXT",- },+ } as unknown as Parameters<typeof handleCreateScoreConfig>[0],context,),).rejects.toThrow(/invalid characters/i);@@ -2489,7 +2510,7 @@ describe("MCP Read Tools", () => {name: "mcp-updated",description: "Updated through MCP",numericMinValue: -1,- },+ } as unknown as Parameters<typeof handleUpdateScoreConfig>[0],context,);@@ -2624,7 +2645,9 @@ describe("MCP Read Tools", () => {});it("should be available to in-app agent keys", async () => {- const context = mockServerContext({ isInAppAgentKey: true });+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });await expect(toolRegistry.getEnabledTool(getPromptTool.name, context),@@ -2918,7 +2941,9 @@ describe("MCP Read Tools", () => {});it("should be available to in-app agent keys", async () => {- const context = mockServerContext({ isInAppAgentKey: true });+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });await expect(toolRegistry.getEnabledTool(listPromptsTool.name, context),@@ -3298,7 +3323,9 @@ describe("MCP Read Tools", () => {});it("should be available to in-app agent keys", async () => {- const context = mockServerContext({ isInAppAgentKey: true });+ const context = mockServerContext({+ inAppAgent: { permissions: "read" },+ });await expect(toolRegistry.getEnabledTool(getPromptUnresolvedTool.name, context),diff --git a/web/src/__tests__/server/mcp-tools-write.servertest.ts b/web/src/__tests__/server/mcp-tools-write.servertest.tsindex 67ec7967a2..7c98b07470 100644--- a/web/src/__tests__/server/mcp-tools-write.servertest.ts+++ b/web/src/__tests__/server/mcp-tools-write.servertest.ts@@ -269,7 +269,7 @@ describe("MCP Write Tools", () => {enabled: false,target: "observation",filter: [],- },+ } as unknown as Parameters<typeof handleCreateEvaluationRule>[0],context,)) as { id: string };expect(rule.id).toBeDefined();diff --git a/web/src/__tests__/server/media.servertest.ts b/web/src/__tests__/server/media.servertest.tsindex ca37cf0043..b5b833c02a 100644--- a/web/src/__tests__/server/media.servertest.ts+++ b/web/src/__tests__/server/media.servertest.ts@@ -45,26 +45,36 @@ describe("Media Upload API", () => {role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: projectId,role: "ADMIN",retentionDays: 30,deletedAt: null,+ hasTraces: false,name: "Test Project",+ metadata: {},+ createdAt: new Date().toISOString(),},],},],featureFlags: {+ searchBar: false,excludeClickhouseRead: false,templateFlag: true,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });const caller = appRouter.createCaller({ ...ctx, prisma });// Read the image file once and reuse it for all tests@@ -175,7 +185,7 @@ describe("Media Upload API", () => {getUploadUrlResponse.body.uploadUrl,{method: "PUT",- body: fileBytes,+ body: fileBytes as BodyInit,headers: {"Content-Type": contentType,"X-Amz-Checksum-Sha256": sha256Hash,diff --git a/web/src/__tests__/server/members-trpc.servertest.ts b/web/src/__tests__/server/members-trpc.servertest.tsindex cc3de4f015..a36e20bdbb 100644--- a/web/src/__tests__/server/members-trpc.servertest.ts+++ b/web/src/__tests__/server/members-trpc.servertest.ts@@ -3,6 +3,12 @@ import { createInnerTRPCContext } from "@/src/server/api/trpc";import { prisma } from "@langfuse/shared/src/db";import { Role, type Plan } from "@langfuse/shared";import type { Session } from "next-auth";++// Session fixture sub-object types; casts keep the runtime fixtures unchanged+// while satisfying newer required fields on the session user type.+type SessionUser = NonNullable<Session["user"]>;+type SessionProject = SessionUser["organizations"][number]["projects"][number];+type SessionFeatureFlags = SessionUser["featureFlags"];import { v4 as uuidv4 } from "uuid";async function createTestOrg(plan: Plan) {@@ -80,14 +86,14 @@ function createSession(deletedAt: null,name: project.name,metadata: {},- },+ } as SessionProject,],},],featureFlags: {excludeClickhouseRead: false,templateFlag: true,- },+ } as SessionFeatureFlags,admin: false, // Not admin to test actual limits},environment: {diff --git a/web/src/__tests__/server/memberships-api.servertest.ts b/web/src/__tests__/server/memberships-api.servertest.tsindex 8adfab47de..fffb7c8a9d 100644--- a/web/src/__tests__/server/memberships-api.servertest.ts+++ b/web/src/__tests__/server/memberships-api.servertest.ts@@ -327,7 +327,7 @@ describe("Memberships APIs", () => {expect(membershipBefore).not.toBeNull();// Delete the membership- const response = await makeAPICall(+ const response = await makeAPICall<{ message: string; userId: string }>("DELETE",`/api/public/projects/${testProjectId}/memberships`,{@@ -510,7 +510,7 @@ describe("Memberships APIs", () => {expect(membershipBefore).not.toBeNull();// Delete the membership- const response = await makeAPICall(+ const response = await makeAPICall<{ message: string; userId: string }>("DELETE",`/api/public/organizations/memberships`,{diff --git a/web/src/__tests__/server/metrics-api.servertest.ts b/web/src/__tests__/server/metrics-api.servertest.tsindex 07d1ae5ef4..a49ec17877 100644--- a/web/src/__tests__/server/metrics-api.servertest.ts+++ b/web/src/__tests__/server/metrics-api.servertest.ts@@ -312,7 +312,10 @@ describe("/api/public/metrics API Endpoint", () => {toTimestamp: new Date().toISOString(),};- const { status, body } = await makeAPICall(+ const { status, body } = await makeAPICall<{+ error: string;+ message: string;+ }>("GET",`/api/public/metrics?query=${encodeURIComponent(JSON.stringify(invalidMetricNameQuery))}`,undefined,@@ -335,7 +338,10 @@ describe("/api/public/metrics API Endpoint", () => {toTimestamp: new Date().toISOString(),};- const { status, body } = await makeAPICall(+ const { status, body } = await makeAPICall<{+ error: string;+ message: string;+ }>("GET",`/api/public/metrics?query=${encodeURIComponent(JSON.stringify(invalidAggregationQuery))}`,undefined,@@ -358,7 +364,10 @@ describe("/api/public/metrics API Endpoint", () => {toTimestamp: new Date().toISOString(),};- const { status, body } = await makeAPICall(+ const { status, body } = await makeAPICall<{+ error: string;+ message: string;+ }>("GET",`/api/public/metrics?query=${encodeURIComponent(JSON.stringify(invalidDimensionQuery))}`,undefined,@@ -389,7 +398,10 @@ describe("/api/public/metrics API Endpoint", () => {toTimestamp: new Date().toISOString(),};- const { status, body } = await makeAPICall(+ const { status, body } = await makeAPICall<{+ error: string;+ message: string;+ }>("GET",`/api/public/metrics?query=${encodeURIComponent(JSON.stringify(invalidFilterQuery))}`,undefined,@@ -522,7 +534,10 @@ describe("/api/public/metrics API Endpoint", () => {};// Make API call and expect 400 error- const response = await makeAPICall(+ const response = await makeAPICall<{+ error: string;+ message: string;+ }>("GET",`/api/public/metrics?query=${encodeURIComponent(JSON.stringify(invalidStringTypeQuery))}`,);@@ -602,7 +617,10 @@ describe("/api/public/metrics API Endpoint", () => {orderBy: null,};- const response = await makeAPICall(+ const response = await makeAPICall<{+ error: string;+ message: string;+ }>("GET",`/api/public/metrics?query=${encodeURIComponent(JSON.stringify(invalidSessionIdTypeQuery))}`,);@@ -676,7 +694,7 @@ describe("/api/public/metrics API Endpoint", () => {(row: any) => row.name === "tagged-trace",);expect(taggedTraceResult).toBeDefined();- expect(Number(taggedTraceResult.count_count)).toBe(1);+ expect(Number(taggedTraceResult!.count_count)).toBe(1);});});});diff --git a/web/src/__tests__/server/metrics-v2-api.servertest.ts b/web/src/__tests__/server/metrics-v2-api.servertest.tsindex 020f1092d3..06aa2a67dc 100644--- a/web/src/__tests__/server/metrics-v2-api.servertest.ts+++ b/web/src/__tests__/server/metrics-v2-api.servertest.ts@@ -67,7 +67,11 @@ describe("/api/public/v2/metrics API Endpoint", () => {input: 0.001 * (i + 1),output: 0.002 * (i + 1),},- total_cost: 0.003 * (i + 1),+ // total_cost is an ALIAS column in events_full (not insertable);+ // ClickHouse skips the unknown JSONEachRow field, so it is inert.+ ...({ total_cost: 0.003 * (i + 1) } as Partial<+ Parameters<typeof createEvent>[0]+ >),}),);}@@ -278,7 +282,11 @@ describe("/api/public/v2/metrics API Endpoint", () => {name: `histogram-observation-${index}`,type: "GENERATION",start_time: timeValue,- total_cost: cost,+ // total_cost is an ALIAS column in events_full (not insertable);+ // ClickHouse skips the unknown JSONEachRow field, so it is inert.+ ...({ total_cost: cost } as Partial<+ Parameters<typeof createEvent>[0]+ >),metadata_names: ["test"],metadata_values: [testMetadataValue],}),@@ -522,7 +530,10 @@ describe("/api/public/v2/metrics API Endpoint", () => {toTimestamp: new Date().toISOString(),};- const response = await makeAPICall(+ const response = await makeAPICall<{+ error: unknown;+ message: string;+ }>("GET",`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(query))}`,);@@ -656,7 +667,10 @@ describe("/api/public/v2/metrics API Endpoint", () => {};// Make API call and expect 400 error- const response = await makeAPICall(+ const response = await makeAPICall<{+ error: string;+ message: string;+ }>("GET",`/api/public/v2/metrics?query=${encodeURIComponent(JSON.stringify(invalidStringTypeQuery))}`,);diff --git a/web/src/__tests__/server/mixpanel-integration.servertest.ts b/web/src/__tests__/server/mixpanel-integration.servertest.tsindex 9de6a022e8..6879f9e508 100644--- a/web/src/__tests__/server/mixpanel-integration.servertest.ts+++ b/web/src/__tests__/server/mixpanel-integration.servertest.ts@@ -24,6 +24,8 @@ const buildSession = (orgId: string, projectId: string): Session => ({cloudConfig: undefined,name: "Test Organization",metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: projectId,@@ -31,14 +33,20 @@ const buildSession = (orgId: string, projectId: string): Session => ({name: "Test Project",deletedAt: null,retentionDays: null,+ hasTraces: false,metadata: {},+ createdAt: new Date().toISOString(),},],},],featureFlags: {+ searchBar: false,templateFlag: true,excludeClickhouseRead: false,+ observationEvals: false,+ v4BetaToggleVisible: false,+ experimentsV4Enabled: false,},admin: true,},diff --git a/web/src/__tests__/server/model-pricing-tiers.servertest.ts b/web/src/__tests__/server/model-pricing-tiers.servertest.tsindex 475d5a6961..92407183ff 100644--- a/web/src/__tests__/server/model-pricing-tiers.servertest.ts+++ b/web/src/__tests__/server/model-pricing-tiers.servertest.ts@@ -18,6 +18,18 @@ import {} from "@langfuse/shared";import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+// Narrows the validator result union to its error branch for assertions.+const getValidationError = (+ result:+ | ReturnType<typeof validatePricingTiers>+ | ReturnType<typeof validatePricingMethod>,+): string => {+ if (result.valid) {+ throw new Error("Expected validation result to be invalid");+ }+ return result.error;+};+describe("validation methods", () => {describe("validateRegexPattern", () => {it("should accept valid regex patterns", () => {@@ -94,7 +106,9 @@ describe("validation methods", () => {it("should reject empty tier array", () => {const result = validatePricingTiers([]);expect(result.valid).toBe(false);- expect(result.error).toContain("At least one pricing tier is required");+ expect(getValidationError(result)).toContain(+ "At least one pricing tier is required",+ );});it("should reject tiers with no default", () => {@@ -110,7 +124,7 @@ describe("validation methods", () => {const result = validatePricingTiers(tiers);expect(result.valid).toBe(false);- expect(result.error).toContain(+ expect(getValidationError(result)).toContain("Exactly one pricing tier must have isDefault: true",);});@@ -135,7 +149,7 @@ describe("validation methods", () => {const result = validatePricingTiers(tiers);expect(result.valid).toBe(false);- expect(result.error).toContain(+ expect(getValidationError(result)).toContain("Only one pricing tier can have isDefault: true",);});@@ -153,7 +167,7 @@ describe("validation methods", () => {const result = validatePricingTiers(tiers);expect(result.valid).toBe(false);- expect(result.error).toContain(+ expect(getValidationError(result)).toContain("Default pricing tier must have priority: 0",);});@@ -178,7 +192,7 @@ describe("validation methods", () => {const result = validatePricingTiers(tiers);expect(result.valid).toBe(false);- expect(result.error).toContain(+ expect(getValidationError(result)).toContain("Default pricing tier must have empty conditions array",);});@@ -224,7 +238,7 @@ describe("validation methods", () => {const result = validatePricingTiers(tiers);expect(result.valid).toBe(false);- expect(result.error).toContain("priorities must be unique");+ expect(getValidationError(result)).toContain("priorities must be unique");});it("should reject duplicate names", () => {@@ -254,7 +268,7 @@ describe("validation methods", () => {const result = validatePricingTiers(tiers);expect(result.valid).toBe(false);- expect(result.error).toContain("names must be unique");+ expect(getValidationError(result)).toContain("names must be unique");});it("should reject tier with invalid regex pattern", () => {@@ -284,7 +298,7 @@ describe("validation methods", () => {const result = validatePricingTiers(tiers);expect(result.valid).toBe(false);- expect(result.error).toContain("Invalid regex pattern");+ expect(getValidationError(result)).toContain("Invalid regex pattern");});it("should reject tier with no prices", () => {@@ -300,7 +314,9 @@ describe("validation methods", () => {const result = validatePricingTiers(tiers);expect(result.valid).toBe(false);- expect(result.error).toContain("must have at least one price defined");+ expect(getValidationError(result)).toContain(+ "must have at least one price defined",+ );});it("should reject non-default tier with no conditions", () => {@@ -323,7 +339,7 @@ describe("validation methods", () => {const result = validatePricingTiers(tiers);expect(result.valid).toBe(false);- expect(result.error).toContain(+ expect(getValidationError(result)).toContain('Non-default pricing tier "Custom Tier" must have at least one condition',);});@@ -355,10 +371,10 @@ describe("validation methods", () => {const result = validatePricingTiers(tiers);expect(result.valid).toBe(false);- expect(result.error).toContain(+ expect(getValidationError(result)).toContain('Pricing tier "High Volume" must have the same usage keys as the default tier',);- expect(result.error).toContain("Expected: [input, output]");+ expect(getValidationError(result)).toContain("Expected: [input, output]");});it("should accept tiers with same keys in different order", () => {@@ -429,7 +445,7 @@ describe("validation methods", () => {hasPricingTiers: true,});expect(result.valid).toBe(false);- expect(result.error).toContain("Cannot provide both");+ expect(getValidationError(result)).toContain("Cannot provide both");});it("should reject neither flat prices nor pricing tiers", () => {@@ -438,7 +454,7 @@ describe("validation methods", () => {hasPricingTiers: false,});expect(result.valid).toBe(false);- expect(result.error).toContain("Must provide either");+ expect(getValidationError(result)).toContain("Must provide either");});});});diff --git a/web/src/__tests__/server/monitors.servertest.ts b/web/src/__tests__/server/monitors.servertest.tsindex f8eeeafc5e..6fdcc4df6e 100644--- a/web/src/__tests__/server/monitors.servertest.ts+++ b/web/src/__tests__/server/monitors.servertest.ts@@ -46,20 +46,24 @@ const buildSession = (params: {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: params.projectId,role: params.projectRole,retentionDays: 30,deletedAt: null,+ hasTraces: false,name: params.projectName,metadata: {},+ createdAt: new Date().toISOString(),},],},],featureFlags: {- inAppAgent: false,+ searchBar: false,templateFlag: false,excludeClickhouseRead: false,v4BetaToggleVisible: false,diff --git a/web/src/__tests__/server/multilingual-fulltext-search.servertest.ts b/web/src/__tests__/server/multilingual-fulltext-search.servertest.tsindex c837f32315..3b6aabbaaf 100644--- a/web/src/__tests__/server/multilingual-fulltext-search.servertest.ts+++ b/web/src/__tests__/server/multilingual-fulltext-search.servertest.ts@@ -96,6 +96,7 @@ describe("multilingual full-text search (issue #11538)", () => {cloudConfig: undefined,metadata: {},aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: projectId,@@ -104,11 +105,20 @@ describe("multilingual full-text search (issue #11538)", () => {deletedAt: null,name: "Test Project",metadata: {},+ hasTraces: true,+ createdAt: new Date().toISOString(),},],},],- featureFlags: { excludeClickhouseRead: false, templateFlag: true },+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,+ searchBar: false,+ },admin: true,},environment: {} as any,diff --git a/web/src/__tests__/server/observations-api-v2.servertest.ts b/web/src/__tests__/server/observations-api-v2.servertest.tsindex 04757be0b7..f19b6d57f2 100644--- a/web/src/__tests__/server/observations-api-v2.servertest.ts+++ b/web/src/__tests__/server/observations-api-v2.servertest.ts@@ -1,5 +1,5 @@import {- createEvent,+ createEvent as createEventBase,createEventsCh,createOrgProjectAndApiKey,queryClickhouse,@@ -16,6 +16,15 @@ import waitForExpect from "wait-for-expect";let projectId: string;let auth: string;+// The events tables carry metadata as flattened `metadata_names` /+// `metadata_values` arrays. The fixtures below also pass the nested object+// form for readability; it is not a column and is ignored by the insert.+const createEvent = (+ event: Parameters<typeof createEventBase>[0] & {+ metadata?: Record<string, unknown>;+ },+) => createEventBase(event);+const getObservations = (url: string) =>makeZodVerifiedAPICall(GetObservationsV2Response,@@ -264,9 +273,9 @@ describe("/api/public/v2/observations API Endpoint", () => {const envA = `env-a-${randomUUID()}`;const envB = `env-b-${randomUUID()}`;const envC = `env-c-${randomUUID()}`;- const observationIdA = randomUUID();- const observationIdB = randomUUID();- const observationIdC = randomUUID();+ const observationIdA: string = randomUUID();+ const observationIdB: string = randomUUID();+ const observationIdC: string = randomUUID();const timestamp = new Date();const timeValue = timestamp.getTime() * 1000;@@ -1735,9 +1744,9 @@ describe("/api/public/v2/observations API Endpoint", () => {// Should fail validationexpect(response.status).toBe(400);expect(response.body).toHaveProperty("message");- expect((response.body as { message: string }).message).toContain(- "Invalid cursor format",- );+ expect(+ (response.body as unknown as { message: string }).message,+ ).toContain("Invalid cursor format");});});});diff --git a/web/src/__tests__/server/observations-api.servertest.ts b/web/src/__tests__/server/observations-api.servertest.tsindex 127b30ba4d..fb43e2b620 100644--- a/web/src/__tests__/server/observations-api.servertest.ts+++ b/web/src/__tests__/server/observations-api.servertest.ts@@ -2,7 +2,7 @@ import {createObservation,createTrace,createTracesCh,- createEvent,+ createEvent as createEventBase,createOrgProjectAndApiKey,} from "@langfuse/shared/src/server";import {@@ -17,6 +17,15 @@ import { GetObservationsV1Response } from "@/src/features/public-api/types/obserimport { randomUUID } from "crypto";import { env } from "@/src/env.mjs";+// The events tables carry metadata as flattened `metadata_names` /+// `metadata_values` arrays. The fixture below also passes the nested object+// form for readability; it is not a column and is ignored by the insert.+const createEvent = (+ event: Parameters<typeof createEventBase>[0] & {+ metadata?: Record<string, unknown>;+ },+) => createEventBase(event);+// Helper type for creating observation datatype ObservationData = {id?: string;@@ -709,7 +718,7 @@ describe("/api/public/observations API Endpoint", () => {undefined,auth,);- fail("Should have thrown an error");+ throw new Error("Should have thrown an error");} catch (error) {expect(error).toBeDefined();}diff --git a/web/src/__tests__/server/observations-comment-filter.servertest.ts b/web/src/__tests__/server/observations-comment-filter.servertest.tsindex 2deef7ba2e..30811a45cf 100644--- a/web/src/__tests__/server/observations-comment-filter.servertest.ts+++ b/web/src/__tests__/server/observations-comment-filter.servertest.ts@@ -32,6 +32,9 @@ describe("Observations Comment Filtering", () => {role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: projectId,@@ -39,6 +42,9 @@ describe("Observations Comment Filtering", () => {retentionDays: 30,deletedAt: null,name: "Test Project",+ hasTraces: true,+ metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -46,13 +52,17 @@ describe("Observations Comment Filtering", () => {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });caller = appRouter.createCaller({ ...ctx, prisma });});@@ -317,8 +327,6 @@ describe("Observations Comment Filtering", () => {searchQuery: null,searchType: [] as any[],orderBy: null as any,- page: 0,- limit: 10,});expect(typeof countResult.totalCount).toBe("number");diff --git a/web/src/__tests__/server/observations-trpc.servertest.ts b/web/src/__tests__/server/observations-trpc.servertest.tsindex e065dbee09..301fdb2109 100644--- a/web/src/__tests__/server/observations-trpc.servertest.ts+++ b/web/src/__tests__/server/observations-trpc.servertest.ts@@ -39,6 +39,8 @@ describe("traces trpc", () => {deletedAt: null,name: "Test Project",metadata: {},+ hasTraces: true,+ createdAt: new Date().toISOString(),},],},@@ -46,6 +48,10 @@ describe("traces trpc", () => {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},diff --git a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts b/web/src/__tests__/server/organizations-api-key-trpc.servertest.tsindex 753b54cfa0..8b7d6101af 100644--- a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts+++ b/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts@@ -1,4 +1,10 @@import type { Session } from "next-auth";++// Session fixture sub-object types; casts keep the runtime fixtures unchanged+// while satisfying newer required fields on the session user type.+type SessionUser = NonNullable<Session["user"]>;+type SessionOrg = SessionUser["organizations"][number];+type SessionFeatureFlags = SessionUser["featureFlags"];import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";@@ -39,13 +45,13 @@ describe("organization API keys trpc", () => {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},- projects: [],- },+ projects: [] as SessionOrg["projects"],+ } as SessionOrg,],featureFlags: {excludeClickhouseRead: false,templateFlag: true,- },+ } as SessionFeatureFlags,admin: true,},environment: {} as any,@@ -65,13 +71,13 @@ describe("organization API keys trpc", () => {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},- projects: [],- },+ projects: [] as SessionOrg["projects"],+ } as SessionOrg,],featureFlags: {excludeClickhouseRead: false,templateFlag: true,- },+ } as SessionFeatureFlags,admin: false,},environment: {} as any,@@ -91,28 +97,37 @@ describe("organization API keys trpc", () => {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},- projects: [],- },+ projects: [] as SessionOrg["projects"],+ } as SessionOrg,],featureFlags: {excludeClickhouseRead: false,templateFlag: true,- },+ } as SessionFeatureFlags,admin: false,},environment: {} as any,};- const ownerCtx = createInnerTRPCContext({ session: ownerSession });+ const ownerCtx = createInnerTRPCContext({+ session: ownerSession,+ headers: {},+ });const ownerCaller = appRouter.createCaller({ ...ownerCtx, prisma });- const memberCtx = createInnerTRPCContext({ session: memberSession });+ const memberCtx = createInnerTRPCContext({+ session: memberSession,+ headers: {},+ });const memberCaller = appRouter.createCaller({ ...memberCtx, prisma });- const adminCtx = createInnerTRPCContext({ session: adminSession });+ const adminCtx = createInnerTRPCContext({+ session: adminSession,+ headers: {},+ });const adminCaller = appRouter.createCaller({ ...adminCtx, prisma });- const unAuthedCtx = createInnerTRPCContext({ session: null });+ const unAuthedCtx = createInnerTRPCContext({ session: null, headers: {} });const unAuthedCaller = appRouter.createCaller({ ...unAuthedCtx, prisma });describe("organizationApiKeys.byOrganizationId", () => {diff --git a/web/src/__tests__/server/organizations-api.servertest.ts b/web/src/__tests__/server/organizations-api.servertest.tsindex c14ee433fd..9ffb0945e4 100644--- a/web/src/__tests__/server/organizations-api.servertest.ts+++ b/web/src/__tests__/server/organizations-api.servertest.ts@@ -2,7 +2,7 @@ import {makeZodVerifiedAPICall,makeAPICall,} from "@/src/__tests__/test-utils";-import { prisma } from "@langfuse/shared/src/db";+import { prisma, type Prisma } from "@langfuse/shared/src/db";import { z } from "zod";import { randomUUID } from "crypto";import {@@ -137,9 +137,13 @@ describe("Admin Organizations API", () => {it("should return 401 when no authorization header is provided", async () => {const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;- const result = await makeAPICall("POST", "/api/admin/organizations", {- name: uniqueOrgName,- });+ const result = await makeAPICall<{ error: string }>(+ "POST",+ "/api/admin/organizations",+ {+ name: uniqueOrgName,+ },+ );expect(result.status).toBe(401);expect(result.body.error).toContain("Unauthorized");});@@ -147,7 +151,7 @@ describe("Admin Organizations API", () => {it("should return 401 when invalid admin API key is provided", async () => {const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("POST","/api/admin/organizations",{@@ -160,7 +164,7 @@ describe("Admin Organizations API", () => {});it("should return 400 when organization name is too short", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("POST","/api/admin/organizations",{@@ -173,7 +177,7 @@ describe("Admin Organizations API", () => {});it("should return 400 when organization name is too long", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("POST","/api/admin/organizations",{@@ -238,7 +242,10 @@ describe("Admin Organizations API", () => {});it("should return 401 when no authorization header is provided", async () => {- const result = await makeAPICall("GET", "/api/admin/organizations");+ const result = await makeAPICall<{ error: string }>(+ "GET",+ "/api/admin/organizations",+ );expect(result.status).toBe(401);expect(result.body.error).toContain("Unauthorized");});@@ -332,7 +339,7 @@ describe("Admin Organizations API", () => {it("should return 404 when getting a non-existent organization", async () => {const nonExistentId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("GET",`/api/admin/organizations/${nonExistentId}`,undefined,@@ -401,7 +408,7 @@ describe("Admin Organizations API", () => {it("should return 404 when updating a non-existent organization", async () => {const nonExistentId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("PUT",`/api/admin/organizations/${nonExistentId}`,{@@ -415,7 +422,7 @@ describe("Admin Organizations API", () => {});it("should return 400 when updating with invalid name", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("PUT",`/api/admin/organizations/${testOrgId}`,{@@ -429,7 +436,7 @@ describe("Admin Organizations API", () => {});it("should return 401 when no authorization header is provided", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("PUT",`/api/admin/organizations/${testOrgId}`,{@@ -500,7 +507,7 @@ describe("Admin Organizations API", () => {it("should return 404 when deleting a non-existent organization", async () => {const nonExistentId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("DELETE",`/api/admin/organizations/${nonExistentId}`,undefined,@@ -520,7 +527,7 @@ describe("Admin Organizations API", () => {},});- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("DELETE",`/api/admin/organizations/${testOrgId}`,undefined,@@ -539,7 +546,7 @@ describe("Admin Organizations API", () => {});it("should return 401 when no authorization header is provided", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("DELETE",`/api/admin/organizations/${testOrgId}`,);@@ -605,7 +612,7 @@ describe("Admin Organizations API", () => {it("should return 404 when getting API keys for a non-existent organization", async () => {const nonExistentId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("GET",`/api/admin/organizations/${nonExistentId}/apiKeys`,undefined,@@ -671,7 +678,7 @@ describe("Admin Organizations API", () => {it("should return 404 when creating an API key for a non-existent organization", async () => {const nonExistentId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("POST",`/api/admin/organizations/${nonExistentId}/apiKeys`,{@@ -685,7 +692,7 @@ describe("Admin Organizations API", () => {});it("should return 401 when no authorization header is provided", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("POST",`/api/admin/organizations/${testOrgId}/apiKeys`,{@@ -762,7 +769,7 @@ describe("Admin Organizations API", () => {it("should return 404 when deleting a non-existent API key", async () => {const nonExistentId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("DELETE",`/api/admin/organizations/${testOrgId}/apiKeys/${nonExistentId}`,undefined,@@ -775,7 +782,7 @@ describe("Admin Organizations API", () => {it("should return 404 when deleting an API key for a non-existent organization", async () => {const nonExistentId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("DELETE",`/api/admin/organizations/${nonExistentId}/apiKeys/${testApiKeyId}`,undefined,@@ -787,7 +794,7 @@ describe("Admin Organizations API", () => {});it("should return 401 when no authorization header is provided", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("DELETE",`/api/admin/organizations/${testOrgId}/apiKeys/${testApiKeyId}`,);@@ -798,7 +805,7 @@ describe("Admin Organizations API", () => {});it("should return 405 for non-supported methods", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("PATCH","/api/admin/organizations",undefined,@@ -932,7 +939,7 @@ describe("Public Organizations API", () => {},});- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("GET",`/api/public/organizations/projects`,undefined,@@ -955,7 +962,7 @@ describe("Public Organizations API", () => {});it("should return 401 when using invalid API key", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("GET",`/api/public/organizations/projects`,undefined,@@ -965,7 +972,7 @@ describe("Public Organizations API", () => {});it("should return 405 for non-GET methods", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ error: string }>("POST",`/api/public/organizations/projects`,{ some: "data" },@@ -1065,7 +1072,9 @@ describe("Public Organizations API", () => {data: {name: `Null Metadata Project ${randomUUID().substring(0, 8)}`,orgId: testOrgId,- metadata: null,+ // intentionally passes a plain null (not Prisma.DbNull) to mirror+ // pre-existing runtime behavior; cast keeps the fixture unchanged+ metadata: null as unknown as Prisma.NullableJsonNullValueInput,},});@@ -1248,7 +1257,7 @@ describe("Public Organizations API", () => {scope: "PROJECT",});- const response = await makeAPICall(+ const response = await makeAPICall<{ error: string }>("GET",`/api/public/organizations/apiKeys`,undefined,@@ -1270,7 +1279,7 @@ describe("Public Organizations API", () => {});it("should reject request with invalid API key", async () => {- const response = await makeAPICall(+ const response = await makeAPICall<{ error: string }>("GET",`/api/public/organizations/apiKeys`,undefined,@@ -1281,7 +1290,7 @@ describe("Public Organizations API", () => {});it("should only allow GET method", async () => {- const response = await makeAPICall(+ const response = await makeAPICall<{ error: string }>("POST",`/api/public/organizations/apiKeys`,{},diff --git a/web/src/__tests__/server/posthog-integration.servertest.ts b/web/src/__tests__/server/posthog-integration.servertest.tsindex 24c1bbfce4..8742533a4d 100644--- a/web/src/__tests__/server/posthog-integration.servertest.ts+++ b/web/src/__tests__/server/posthog-integration.servertest.ts@@ -24,6 +24,8 @@ const buildSession = (orgId: string, projectId: string): Session => ({cloudConfig: undefined,name: "Test Organization",metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: projectId,@@ -31,14 +33,20 @@ const buildSession = (orgId: string, projectId: string): Session => ({name: "Test Project",deletedAt: null,retentionDays: null,+ hasTraces: false,metadata: {},+ createdAt: new Date().toISOString(),},],},],featureFlags: {+ searchBar: false,templateFlag: true,excludeClickhouseRead: false,+ observationEvals: false,+ v4BetaToggleVisible: false,+ experimentsV4Enabled: false,},admin: true,},diff --git a/web/src/__tests__/server/project-api-key-trpc.servertest.ts b/web/src/__tests__/server/project-api-key-trpc.servertest.tsindex 24843c4041..350e1a68e7 100644--- a/web/src/__tests__/server/project-api-key-trpc.servertest.ts+++ b/web/src/__tests__/server/project-api-key-trpc.servertest.ts@@ -42,27 +42,36 @@ describe("project API keys trpc", () => {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: projectId,role: "ADMIN",retentionDays: 30,deletedAt: null,+ hasTraces: false,name: "Test Project",+ metadata: {},+ createdAt: new Date().toISOString(),},],},],featureFlags: {+ searchBar: false,excludeClickhouseRead: false,templateFlag: true,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: false,},environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });const caller = appRouter.createCaller({ ...ctx, prisma });return { caller, projectId };diff --git a/web/src/__tests__/server/projects-api.servertest.ts b/web/src/__tests__/server/projects-api.servertest.tsindex e5e67afdb0..e7f7b8d77e 100644--- a/web/src/__tests__/server/projects-api.servertest.ts+++ b/web/src/__tests__/server/projects-api.servertest.ts@@ -127,7 +127,7 @@ describe("Projects API", () => {});it("should return 401 when invalid API keys are provided", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("GET","/api/public/projects",undefined,@@ -138,7 +138,7 @@ describe("Projects API", () => {});it("should return 405 for non-GET methods", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT", // Changed from POST to PUT since we now support POST"/api/public/projects",{},@@ -150,7 +150,7 @@ describe("Projects API", () => {it("should handle different authentication formats", async () => {// Test with Bearer token format- const bearerResult = await makeAPICall(+ const bearerResult = await makeAPICall<{ message: string }>("GET","/api/public/projects",undefined,@@ -159,7 +159,7 @@ describe("Projects API", () => {expect(bearerResult.status).toBe(401);// Test with just the secret key (no Bearer prefix)- const secretKeyResult = await makeAPICall(+ const secretKeyResult = await makeAPICall<{ message: string }>("GET","/api/public/projects",undefined,@@ -249,7 +249,7 @@ describe("Projects API", () => {"should reject create when metadata is %s",async (_label, metadataValue) => {const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("POST","/api/public/projects",{@@ -287,7 +287,7 @@ describe("Projects API", () => {it("should reject create when metadata is a literal null", async () => {const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("POST","/api/public/projects",{@@ -332,7 +332,7 @@ describe("Projects API", () => {const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;// Test with invalid retention days (less than 3 and not 0)- const invalidResult = await makeAPICall(+ const invalidResult = await makeAPICall<{ message: string }>("POST","/api/public/projects",{@@ -348,7 +348,7 @@ describe("Projects API", () => {it("should return 403 when using project API key instead of organization API key", async () => {const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("POST","/api/public/projects",{@@ -365,7 +365,7 @@ describe("Projects API", () => {it("should return 401 when invalid API keys are provided", async () => {const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("POST","/api/public/projects",{@@ -379,7 +379,7 @@ describe("Projects API", () => {it("should return 400 when project name is invalid", async () => {// Test with a name that's too short- const shortNameResult = await makeAPICall(+ const shortNameResult = await makeAPICall<{ message: string }>("POST","/api/public/projects",{@@ -391,7 +391,7 @@ describe("Projects API", () => {expect(shortNameResult.body.message).toContain("Invalid project name");// Test with a name that's too long- const longNameResult = await makeAPICall(+ const longNameResult = await makeAPICall<{ message: string }>("POST","/api/public/projects",{@@ -407,7 +407,7 @@ describe("Projects API", () => {const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;// First create a project- await makeAPICall(+ await makeAPICall<{ message: string }>("POST","/api/public/projects",{@@ -417,7 +417,7 @@ describe("Projects API", () => {);// Try to create another project with the same name- const duplicateResult = await makeAPICall(+ const duplicateResult = await makeAPICall<{ message: string }>("POST","/api/public/projects",{@@ -483,7 +483,7 @@ describe("Projects API", () => {it("should validate retention days on update", async () => {// Test with invalid retention days (less than 3 and not 0)- const invalidResult = await makeAPICall(+ const invalidResult = await makeAPICall<{ message: string }>("PUT",`/api/public/projects/${testProjectId}`,{@@ -578,7 +578,7 @@ describe("Projects API", () => {data: { metadata: seedMetadata },});- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT",`/api/public/projects/${testProjectId}`,{@@ -632,7 +632,7 @@ describe("Projects API", () => {data: { metadata: seedMetadata },});- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT",`/api/public/projects/${testProjectId}`,{@@ -651,7 +651,7 @@ describe("Projects API", () => {});it("should return 403 when using project API key instead of organization API key", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT",`/api/public/projects/${testProjectId}`,{@@ -667,7 +667,7 @@ describe("Projects API", () => {it("should return 404 when project does not exist", async () => {const nonExistentProjectId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT",`/api/public/projects/${nonExistentProjectId}`,{@@ -727,7 +727,7 @@ describe("Projects API", () => {});it("should return 403 when using project API key instead of organization API key", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("DELETE",`/api/public/projects/${testProjectId}`,undefined,@@ -740,7 +740,7 @@ describe("Projects API", () => {});it("should return 401 when invalid API keys are provided", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("DELETE",`/api/public/projects/${testProjectId}`,undefined,@@ -752,7 +752,7 @@ describe("Projects API", () => {it("should return 404 when project does not exist", async () => {const nonExistentProjectId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("DELETE",`/api/public/projects/${nonExistentProjectId}`,undefined,@@ -781,7 +781,7 @@ describe("Projects API", () => {});it("should return 401 when invalid API keys are provided", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("GET",`/api/public/projects/${projectId}/apiKeys`,undefined,@@ -792,7 +792,7 @@ describe("Projects API", () => {});it("should return 403 when using project API key instead of organization API key", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("GET",`/api/public/projects/${projectId}/apiKeys`,undefined,@@ -806,7 +806,7 @@ describe("Projects API", () => {it("should return 404 when project does not exist", async () => {const nonExistentProjectId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("GET",`/api/public/projects/${nonExistentProjectId}/apiKeys`,undefined,@@ -817,7 +817,7 @@ describe("Projects API", () => {});it("should return 405 for non-GET/POST methods", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PUT",`/api/public/projects/${projectId}/apiKeys`,{},@@ -886,7 +886,7 @@ describe("Projects API", () => {it("should return 403 when using project API key instead of organization API key", async () => {const note = `Test API Key ${randomUUID().substring(0, 8)}`;- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("POST",`/api/public/projects/${projectId}/apiKeys`,{@@ -903,7 +903,7 @@ describe("Projects API", () => {it("should return 401 when invalid API keys are provided", async () => {const note = `Test API Key ${randomUUID().substring(0, 8)}`;- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("POST",`/api/public/projects/${projectId}/apiKeys`,{@@ -919,7 +919,7 @@ describe("Projects API", () => {const nonExistentProjectId = randomUUID();const note = `Test API Key ${randomUUID().substring(0, 8)}`;- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("POST",`/api/public/projects/${nonExistentProjectId}/apiKeys`,{@@ -970,7 +970,7 @@ describe("Projects API", () => {const note = `Test API Key ${randomUUID().substring(0, 8)}`;const predefinedPublicKey = `pk-lf-${randomUUID()}`;- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("POST",`/api/public/projects/${projectId}/apiKeys`,{@@ -990,7 +990,7 @@ describe("Projects API", () => {const note = `Test API Key ${randomUUID().substring(0, 8)}`;const predefinedSecretKey = `sk-lf-${randomUUID()}`;- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("POST",`/api/public/projects/${projectId}/apiKeys`,{@@ -1011,7 +1011,7 @@ describe("Projects API", () => {const invalidPublicKey = `invalid-${randomUUID()}`;const predefinedSecretKey = `sk-lf-${randomUUID()}`;- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("POST",`/api/public/projects/${projectId}/apiKeys`,{@@ -1031,7 +1031,7 @@ describe("Projects API", () => {const predefinedPublicKey = `pk-lf-${randomUUID()}`;const invalidSecretKey = `invalid-${randomUUID()}`;- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("POST",`/api/public/projects/${projectId}/apiKeys`,{@@ -1053,7 +1053,7 @@ describe("Projects API", () => {const secretKey2 = `sk-lf-${randomUUID()}`;// Create first API key with predefined keys- const firstResponse = await makeAPICall(+ const firstResponse = await makeAPICall<{ id: string }>("POST",`/api/public/projects/${projectId}/apiKeys`,{@@ -1067,7 +1067,7 @@ describe("Projects API", () => {createdApiKeyId = firstResponse.body.id;// Try to create second API key with same publicKey but different secretKey- const secondResponse = await makeAPICall(+ const secondResponse = await makeAPICall<{ message: string }>("POST",`/api/public/projects/${projectId}/apiKeys`,{@@ -1131,7 +1131,7 @@ describe("Projects API", () => {});it("should return 403 when using project API key instead of organization API key", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("DELETE",`/api/public/projects/${projectId}/apiKeys/${deleteTestApiKeyId}`,undefined,@@ -1144,7 +1144,7 @@ describe("Projects API", () => {});it("should return 401 when invalid API keys are provided", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("DELETE",`/api/public/projects/${projectId}/apiKeys/${deleteTestApiKeyId}`,undefined,@@ -1156,7 +1156,7 @@ describe("Projects API", () => {it("should return 404 when API key does not exist", async () => {const nonExistentApiKeyId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("DELETE",`/api/public/projects/${projectId}/apiKeys/${nonExistentApiKeyId}`,undefined,@@ -1168,7 +1168,7 @@ describe("Projects API", () => {it("should return 404 when project does not exist", async () => {const nonExistentProjectId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("DELETE",`/api/public/projects/${nonExistentProjectId}/apiKeys/${deleteTestApiKeyId}`,undefined,@@ -1180,7 +1180,7 @@ describe("Projects API", () => {});it("should return 405 for unallowed methods", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ message: string }>("PATCH",`/api/public/projects/${projectId}`,undefined,diff --git a/web/src/__tests__/server/projectsRouter-setRetention.servertest.ts b/web/src/__tests__/server/projectsRouter-setRetention.servertest.tsindex 5b211404b9..010be73384 100644--- a/web/src/__tests__/server/projectsRouter-setRetention.servertest.ts+++ b/web/src/__tests__/server/projectsRouter-setRetention.servertest.ts@@ -70,13 +70,16 @@ function makeCaller({role,retentionDays: 0,deletedAt: null,+ hasTraces: false,name: "Test Project",metadata: {},+ createdAt: new Date().toISOString(),},],},],featureFlags: {+ searchBar: false,excludeClickhouseRead: false,templateFlag: true,v4BetaToggleVisible: false,diff --git a/web/src/__tests__/server/promptCache.servertest.ts b/web/src/__tests__/server/promptCache.servertest.tsindex af3012e004..8b15c406cf 100644--- a/web/src/__tests__/server/promptCache.servertest.ts+++ b/web/src/__tests__/server/promptCache.servertest.ts@@ -7,6 +7,9 @@ type Redis = NonNullable<typeof redis>;describe("PromptService", () => {let promptService: PromptService;let mockPrisma: Mocked<PrismaClient>;+ // Typed handle on the same vi.fn instance wired into mockPrisma, because+ // Prisma's overloaded findFirst signature survives vitest's Mocked mapping.+ let promptFindFirstMock: Mock;let mockRedis: Mocked<Redis>;let mockMetricIncrementer: Mock;@@ -29,9 +32,10 @@ describe("PromptService", () => {};beforeEach(() => {+ promptFindFirstMock = vi.fn();mockPrisma = {prompt: {- findFirst: vi.fn(),+ findFirst: promptFindFirstMock,},promptDependency: {findMany: vi.fn().mockResolvedValue([]),@@ -73,7 +77,7 @@ describe("PromptService", () => {it("should fetch from database if not in cache", async () => {mockRedis.get.mockResolvedValueOnce("epoch-1"); // getOrCreateEpoch for cache readmockRedis.get.mockResolvedValueOnce(null); // cache miss- mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);+ promptFindFirstMock.mockResolvedValue(mockPrompt);mockRedis.get.mockResolvedValueOnce("epoch-1"); // getOrCreateEpoch for cache writeconst result = await promptService.getPrompt({@@ -99,7 +103,7 @@ describe("PromptService", () => {});it("should bypass cache entirely when resolve is false", async () => {- mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);+ promptFindFirstMock.mockResolvedValue(mockPrompt);const result = await promptService.getPrompt({projectId: "project1",@@ -143,7 +147,7 @@ describe("PromptService", () => {});it("should not use cache when disabled", async () => {- mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);+ promptFindFirstMock.mockResolvedValue(mockPrompt);const result = await promptService.getPrompt({projectId: "project1",@@ -168,7 +172,7 @@ describe("PromptService", () => {});it("should not use cache with null Redis instance", async () => {- mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);+ promptFindFirstMock.mockResolvedValue(mockPrompt);const result = await promptService.getPrompt({projectId: "project1",@@ -186,7 +190,7 @@ describe("PromptService", () => {describe("getPrompt with Redis errors", () => {it("should fallback to database if Redis.get throws an error", async () => {mockRedis.get.mockRejectedValue(new Error("Redis error"));- mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);+ promptFindFirstMock.mockResolvedValue(mockPrompt);const result = await promptService.getPrompt({projectId: "project1",@@ -206,7 +210,7 @@ describe("PromptService", () => {it("should not cache if Redis.set throws an error after database fetch", async () => {mockRedis.get.mockResolvedValueOnce("epoch-1"); // getOrCreateEpochmockRedis.get.mockResolvedValueOnce(null); // cache miss- mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);+ promptFindFirstMock.mockResolvedValue(mockPrompt);mockRedis.set.mockRejectedValue(new Error("Redis error"));const result = await promptService.getPrompt({diff --git a/web/src/__tests__/server/prompts-trpc.servertest.ts b/web/src/__tests__/server/prompts-trpc.servertest.tsindex f2411c8b5f..0cd7422314 100644--- a/web/src/__tests__/server/prompts-trpc.servertest.ts+++ b/web/src/__tests__/server/prompts-trpc.servertest.ts@@ -24,14 +24,18 @@ async function prepare() {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: project.id,role: "ADMIN",retentionDays: 30,deletedAt: null,+ hasTraces: false,name: project.name,metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -39,6 +43,10 @@ async function prepare() {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},diff --git a/web/src/__tests__/server/prompts.v2.servertest.ts b/web/src/__tests__/server/prompts.v2.servertest.tsindex 95eb5c4d1e..9bae491ffd 100644--- a/web/src/__tests__/server/prompts.v2.servertest.ts+++ b/web/src/__tests__/server/prompts.v2.servertest.ts@@ -112,9 +112,13 @@ const setupTriggerAndAction = async (projectId: string) => {};};+// The v2 prompts API returns the prompt with its dependency resolution graph+// attached, which the Prisma-derived Prompt type does not carry.+type PromptWithResolutionGraph = Prompt & { resolutionGraph?: unknown };+const testPromptEquality = (promptParams: CreatePromptInDBParams,- prompt: Prompt,+ prompt: PromptWithResolutionGraph,) => {if (promptParams.promptId) {expect(prompt.id).toBe(promptParams.promptId);@@ -595,7 +599,7 @@ describe("/api/public/v2/prompts API Endpoint", () => {// Verify the placeholder message structure is preservedconst messages = validatedPrompt.prompt as ChatMessage[];- const placeholderMessage = messages[1] as {+ const placeholderMessage = messages[1] as unknown as {type: ChatMessageType.Placeholder;name: string;};@@ -913,7 +917,7 @@ describe("/api/public/v2/prompts API Endpoint", () => {expectedError: string,auth?: string,) => {- const response = await makeAPICall(+ const response = await makeAPICall<{ message: string; error: unknown }>("POST",baseURI,{@@ -1668,7 +1672,7 @@ describe("/api/public/v2/prompts API Endpoint", () => {);expect(response.status).toBe(200);- const body = response.body as Prompt;+ const body = response.body as unknown as PromptWithResolutionGraph;// Should be resolved (no @@@langfusePrompt tags)expect(body.prompt).not.toContain("@@@langfusePrompt");expect(body.prompt).toContain("I am a child prompt");@@ -1712,7 +1716,7 @@ describe("/api/public/v2/prompts API Endpoint", () => {);expect(response.status).toBe(200);- const body = response.body as Prompt;+ const body = response.body as unknown as PromptWithResolutionGraph;expect(body.prompt).not.toContain("@@@langfusePrompt");expect(body.prompt).toContain("Child content");});@@ -1755,7 +1759,7 @@ describe("/api/public/v2/prompts API Endpoint", () => {);expect(response.status).toBe(200);- const body = response.body as Prompt;+ const body = response.body as unknown as PromptWithResolutionGraph;// Should be unresolved (keep @@@langfusePrompt tags)expect(body.prompt).toContain("@@@langfusePrompt");expect(body.prompt).toContain(@@ -1809,7 +1813,7 @@ describe("/api/public/v2/prompts API Endpoint", () => {);expect(response.status).toBe(200);- const body = response.body as Prompt;+ const body = response.body as unknown as PromptWithResolutionGraph;expect(body.type).toBe("chat");// Verify the chat messages still contain unresolved tagsconst messages = body.prompt as Array<{ role: string; content: string }>;@@ -1857,7 +1861,7 @@ describe("/api/public/v2/prompts API Endpoint", () => {);expect(response.status).toBe(200);- const body = response.body as Prompt;+ const body = response.body as unknown as PromptWithResolutionGraph;expect(body.labels).toContain("production");expect(body.prompt).toContain("@@@langfusePrompt");expect(body.resolutionGraph).toBeNull();@@ -1888,7 +1892,7 @@ describe("/api/public/v2/prompts API Endpoint", () => {);expect(response.status).toBe(200);- const body = response.body as Prompt;+ const body = response.body as unknown as PromptWithResolutionGraph;expect(body.prompt).toBe(parentContent);expect(body.resolutionGraph).toBeNull();});@@ -2189,7 +2193,8 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {);expect(getResponse.status).toBe(200);- const responseBody = getResponse.body as unknown as Prompt;+ const responseBody =+ getResponse.body as unknown as PromptWithResolutionGraph;const parsedPrompt = responseBody.prompt as string;// Verify the resolution graph is returned with the correct structure@@ -2241,7 +2246,7 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {expect(getResponseAfterUpdate.status).toBe(200);const responseBodyAfterUpdate =- getResponseAfterUpdate.body as unknown as Prompt;+ getResponseAfterUpdate.body as unknown as PromptWithResolutionGraph;const parsedPromptAfterUpdate = responseBodyAfterUpdate.prompt as string;expect(parsedPromptAfterUpdate).toBe(diff --git a/web/src/__tests__/server/queryBuilder.servertest.ts b/web/src/__tests__/server/queryBuilder.servertest.tsindex 9fb80b5691..793e4b44d5 100644--- a/web/src/__tests__/server/queryBuilder.servertest.ts+++ b/web/src/__tests__/server/queryBuilder.servertest.ts@@ -324,7 +324,12 @@ describe("queryBuilder", () => {trace_id: data.traceId,observation_id: data.observationId,name: data.name,- value: data.dataType === "NUMERIC" ? data.value || 0 : null,+ // Non-numeric scores store NULL in the Nullable(Float64) value+ // column; the insert schema types value as number, hence the cast.+ value:+ data.dataType === "NUMERIC"+ ? data.value || 0+ : (null as unknown as number),string_value: ["CATEGORICAL", "BOOLEAN", "TEXT"].includes(data.dataType,)@@ -3146,7 +3151,7 @@ describe("queryBuilder", () => {// Create traces with observations that have different costsconst traces = [];- const observations = [];+ const observations: ReturnType<typeof createObservation>[] = [];// Create trace for cost distribution testconst trace = createTrace({diff --git a/web/src/__tests__/server/queryBuilderDashboards.servertest.ts b/web/src/__tests__/server/queryBuilderDashboards.servertest.tsindex c2cf9a7619..eb55e0c2ca 100644--- a/web/src/__tests__/server/queryBuilderDashboards.servertest.ts+++ b/web/src/__tests__/server/queryBuilderDashboards.servertest.ts@@ -479,8 +479,8 @@ describe("selfServeDashboards", () => {);expect(modelRow).toBeDefined();- expect(modelRow.sum_totalCost).toBeDefined();- expect(modelRow.sum_totalTokens).toBeDefined();+ expect(modelRow!.sum_totalCost).toBeDefined();+ expect(modelRow!.sum_totalTokens).toBeDefined();// We could add more specific assertions about the expected costs and tokens// if we had that information calculated from our sample data@@ -569,8 +569,8 @@ describe("selfServeDashboards", () => {);expect(modelRow).toBeDefined();- expect(modelRow.sum_totalCost).toBeGreaterThan(500);- expect(Number(modelRow.sum_totalTokens)).toBeGreaterThan(10000);+ expect(modelRow!.sum_totalCost).toBeGreaterThan(500);+ expect(Number(modelRow!.sum_totalTokens)).toBeGreaterThan(10000);});});});@@ -852,11 +852,11 @@ describe("selfServeDashboards", () => {);expect(userRow).toBeDefined();- expect(userRow.count_count).toBeDefined();+ expect(userRow!.count_count).toBeDefined();// Verify the count matches what we expect based on our sample data// We could add more specific assertions if needed- expect(Number(userRow.count_count)).toBeGreaterThan(0);+ expect(Number(userRow!.count_count)).toBeGreaterThan(0);});// Verify the total number of traces across all users matches our expected totaldiff --git a/web/src/__tests__/server/queryBuilderSQLI.servertest.ts b/web/src/__tests__/server/queryBuilderSQLI.servertest.tsindex 20327655fc..fe55e6382c 100644--- a/web/src/__tests__/server/queryBuilderSQLI.servertest.ts+++ b/web/src/__tests__/server/queryBuilderSQLI.servertest.ts@@ -47,8 +47,9 @@ describe("QueryBuilder SQL Injection Tests", () => {// Comment: The view property is restricted to specific enum values,// but a determined attacker might try to bypass zod validation or// supply a maliciously crafted view name+ // Intentionally invalid payload: bypasses the QueryType view enum.const maliciousQuery = {- view: "traces; DROP TABLE users" as any,+ view: "traces; DROP TABLE users",dimensions: [],metrics: [{ measure: "count", aggregation: "count" }],filters: [],@@ -56,7 +57,7 @@ describe("QueryBuilder SQL Injection Tests", () => {fromTimestamp: defaultFromTime,toTimestamp: defaultToTime,orderBy: null,- };+ } as unknown as QueryType;// Should throw an error rather than allow the injectionawait expect(diff --git a/web/src/__tests__/server/rate-limit.servertest.ts b/web/src/__tests__/server/rate-limit.servertest.tsindex 9bfb33b243..ee86733b8e 100644--- a/web/src/__tests__/server/rate-limit.servertest.ts+++ b/web/src/__tests__/server/rate-limit.servertest.ts@@ -4,6 +4,8 @@ import {RateLimitService,} from "@/src/features/public-api/server/RateLimitService";import { randomUUID } from "crypto";+import type { Redis } from "ioredis";+import type { ApiAccessScope } from "@langfuse/shared/src/server";import {clearRedisKeysByPatternSafely,createRedisTestClient,@@ -11,6 +13,16 @@ import {type RedisTestClient,} from "@/src/__tests__/server/redis-test-utils";+// The rate limiter only reads these scope fields; the cast keeps the test+// fixtures minimal without changing them at runtime.+type TestApiAccessScope = Pick<+ ApiAccessScope,+ "orgId" | "plan" | "projectId" | "accessLevel" | "rateLimitOverrides"+>;++const asScope = (scope: TestApiAccessScope): ApiAccessScope =>+ scope as ApiAccessScope;+describe("RateLimitService", () => {const orgId = `rate-limit-test-org-${randomUUID()}`;const projectId = `rate-limit-test-project-${randomUUID()}`;@@ -55,13 +67,13 @@ describe("RateLimitService", () => {remainingPoints: 999,msBeforeNext: 1000,resource: "public-api" as const,- scope: {+ scope: asScope({orgId: orgId,plan: "cloud:hobby" as const,projectId,accessLevel: "project" as const,rateLimitOverrides: [],- },+ }),consumedPoints: 1,isFirstInDuration: true,};@@ -87,8 +99,11 @@ describe("RateLimitService", () => {expect(redis).toBeDefined();- const rateLimitService = RateLimitService.getInstance(redis);- const result = await rateLimitService.rateLimitRequest(scope, "public-api");+ const rateLimitService = RateLimitService.getInstance(redis as Redis);+ const result = await rateLimitService.rateLimitRequest(+ asScope(scope),+ "public-api",+ );expect(result?.res).toEqual({scope: scope,@@ -120,10 +135,13 @@ describe("RateLimitService", () => {rateLimitOverrides: [],};- const rateLimitService = RateLimitService.getInstance(redis);- await rateLimitService.rateLimitRequest(scope, "public-api");+ const rateLimitService = RateLimitService.getInstance(redis as Redis);+ await rateLimitService.rateLimitRequest(asScope(scope), "public-api");- const result = await rateLimitService.rateLimitRequest(scope, "public-api");+ const result = await rateLimitService.rateLimitRequest(+ asScope(scope),+ "public-api",+ );expect(result?.res).toEqual({scope: scope,@@ -148,11 +166,11 @@ describe("RateLimitService", () => {],};- const rateLimitService = RateLimitService.getInstance(redis);- await rateLimitService.rateLimitRequest(scope, "public-api");+ const rateLimitService = RateLimitService.getInstance(redis as Redis);+ await rateLimitService.rateLimitRequest(asScope(scope), "public-api");const firstResult = await rateLimitService.rateLimitRequest(- scope,+ asScope(scope),"public-api",);expect(firstResult?.isRateLimited()).toBe(false);@@ -170,7 +188,7 @@ describe("RateLimitService", () => {await redis.del(`${RATE_LIMIT_REDIS_KEY_PREFIX}:public-api:${orgId}`);const secondResult = await rateLimitService.rateLimitRequest(- scope,+ asScope(scope),"public-api",);@@ -198,13 +216,16 @@ describe("RateLimitService", () => {],};- const rateLimitService = RateLimitService.getInstance(redis);+ const rateLimitService = RateLimitService.getInstance(redis as Redis);for (let i = 0; i < 5; i++) {- await rateLimitService.rateLimitRequest(scope, "public-api");+ await rateLimitService.rateLimitRequest(asScope(scope), "public-api");}- const result = await rateLimitService.rateLimitRequest(scope, "public-api");+ const result = await rateLimitService.rateLimitRequest(+ asScope(scope),+ "public-api",+ );expect(result?.res).toEqual({scope: scope,@@ -229,9 +250,12 @@ describe("RateLimitService", () => {],};- const rateLimitService = RateLimitService.getInstance(redis);+ const rateLimitService = RateLimitService.getInstance(redis as Redis);- const result = await rateLimitService.rateLimitRequest(scope, "public-api");+ const result = await rateLimitService.rateLimitRequest(+ asScope(scope),+ "public-api",+ );expect(result?.res).toEqual({scope: scope,@@ -255,9 +279,12 @@ describe("RateLimitService", () => {],};- const rateLimitService = RateLimitService.getInstance(redis);+ const rateLimitService = RateLimitService.getInstance(redis as Redis);- const result = await rateLimitService.rateLimitRequest(scope, "prompts");+ const result = await rateLimitService.rateLimitRequest(+ asScope(scope),+ "prompts",+ );expect(result?.res).toBeUndefined();expect(result?.isRateLimited()).toBe(false);@@ -274,9 +301,12 @@ describe("RateLimitService", () => {],};- const rateLimitService = RateLimitService.getInstance(redis);+ const rateLimitService = RateLimitService.getInstance(redis as Redis);- const result = await rateLimitService.rateLimitRequest(scope, "ingestion");+ const result = await rateLimitService.rateLimitRequest(+ asScope(scope),+ "ingestion",+ );expect(result?.res).toBeUndefined();});@@ -295,7 +325,7 @@ describe("RateLimitService", () => {//// const rateLimitService = new RateLimitService(null);//- // const result = await rateLimitService.rateLimitRequest(scope, "public-api");+ // const result = await rateLimitService.rateLimitRequest(asScope(scope), "public-api");//// expect(result?.res).toBeUndefined();// expect(result?.isRateLimited()).toBe(false);@@ -310,9 +340,12 @@ describe("RateLimitService", () => {rateLimitOverrides: [],};- const rateLimitService = RateLimitService.getInstance(redis);+ const rateLimitService = RateLimitService.getInstance(redis as Redis);- const result = await rateLimitService.rateLimitRequest(scope, "public-api");+ const result = await rateLimitService.rateLimitRequest(+ asScope(scope),+ "public-api",+ );expect(result?.res).toBeUndefined();expect(result?.isRateLimited()).toBe(false);@@ -327,9 +360,9 @@ describe("RateLimitService", () => {rateLimitOverrides: [],};- const rateLimitService = RateLimitService.getInstance(redis);+ const rateLimitService = RateLimitService.getInstance(redis as Redis);const result = await rateLimitService.rateLimitRequest(- scope,+ asScope(scope),"score-delete",);@@ -354,7 +387,7 @@ describe("RateLimitService", () => {{ plan: "cloud:enterprise" as const, points: 100 },];- const rateLimitService = RateLimitService.getInstance(redis);+ const rateLimitService = RateLimitService.getInstance(redis as Redis);for (const testCase of cases) {await redis.del(@@ -370,7 +403,7 @@ describe("RateLimitService", () => {};const result = await rateLimitService.rateLimitRequest(- scope,+ asScope(scope),"public-api-legacy",);@@ -396,7 +429,7 @@ describe("RateLimitService", () => {{ plan: "cloud:enterprise" as const, points: 500, durationInSec: 3600 },];- const rateLimitService = RateLimitService.getInstance(redis);+ const rateLimitService = RateLimitService.getInstance(redis as Redis);for (const testCase of cases) {const activeKey = `${RATE_LIMIT_REDIS_KEY_PREFIX}:public-api-v2-metrics:${orgId}`;@@ -412,7 +445,7 @@ describe("RateLimitService", () => {};const result = await rateLimitService.rateLimitRequest(- scope,+ asScope(scope),"public-api-v2-metrics",);@@ -444,13 +477,13 @@ describe("RateLimitService", () => {rateLimitOverrides: [],};- const rateLimitService = RateLimitService.getInstance(redis);+ const rateLimitService = RateLimitService.getInstance(redis as Redis);const mediaResult = await rateLimitService.rateLimitRequest(- scope,+ asScope(scope),"media-upload",);const ingestionResult = await rateLimitService.rateLimitRequest(- scope,+ asScope(scope),"ingestion",);diff --git a/web/src/__tests__/server/repositories/clickhouse-insert-strings.servertest.ts b/web/src/__tests__/server/repositories/clickhouse-insert-strings.servertest.tsindex 15ef538cdc..91d6e54342 100644--- a/web/src/__tests__/server/repositories/clickhouse-insert-strings.servertest.ts+++ b/web/src/__tests__/server/repositories/clickhouse-insert-strings.servertest.ts@@ -40,7 +40,8 @@ describe("ClickHouse insert string edge cases", () => {maybeIt("should handle prompt_version as numeric string '42'", async () => {const event = createEvent({project_id: projectId,- prompt_version: "42",+ // Intentionally invalid type: exercises ClickHouse string parsing.+ prompt_version: "42" as unknown as number,});await expect(createEventsCh([event])).resolves.not.toThrow();});@@ -60,7 +61,8 @@ describe("ClickHouse insert string edge cases", () => {// prompt_version = "local" cannot be parsed as UInt16 by ClickHouse.const event = createEvent({project_id: projectId,- prompt_version: "local",+ // Intentionally invalid type: reproduces the production error.+ prompt_version: "local" as unknown as number,});await expect(createEventsCh([event])).rejects.toThrow(/Cannot parse/);@@ -72,7 +74,8 @@ describe("ClickHouse insert string edge cases", () => {async () => {const event = createEvent({project_id: projectId,- prompt_version: "v1.0.0",+ // Intentionally invalid type: exercises ClickHouse string parsing.+ prompt_version: "v1.0.0" as unknown as number,});await expect(createEventsCh([event])).rejects.toThrow(/Cannot parse/);diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.tsindex 10c890e779..726bc23781 100644--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts@@ -350,7 +350,11 @@ describe("Clickhouse Events Repository Test", () => {name: "io-metadata-test",input: "Test input content",output: "Test output content",- metadata: { key: "value" },+ // events_full has no `metadata` map column; ClickHouse skips unknown+ // JSONEachRow fields on insert, so this extra key is inert.+ ...({ metadata: { key: "value" } } as Partial<+ Parameters<typeof createEvent>[0]+ >),});await createEventsCh([event]);@@ -817,7 +821,7 @@ describe("Clickhouse Events Repository Test", () => {const options = await getEventFilterOptions({projectId: uniqueProjectId,});- expect(options.level.map((level) => level.value)).toContain(+ expect(options.level!.map((level) => level.value)).toContain(recentLevel,);});@@ -825,7 +829,7 @@ describe("Clickhouse Events Repository Test", () => {const defaultOptions = await getEventFilterOptions({projectId: uniqueProjectId,});- const defaultLevels = defaultOptions.level.map((level) => level.value);+ const defaultLevels = defaultOptions.level!.map((level) => level.value);expect(defaultLevels).toContain(recentLevel);expect(defaultLevels).not.toContain(oldLevel);@@ -841,7 +845,7 @@ describe("Clickhouse Events Repository Test", () => {},],});- const upperOnlyLevels = upperOnlyOptions.level.map(+ const upperOnlyLevels = upperOnlyOptions.level!.map((level) => level.value,);@@ -860,7 +864,7 @@ describe("Clickhouse Events Repository Test", () => {},],});- const explicitLevels = explicitOptions.level.map(+ const explicitLevels = explicitOptions.level!.map((level) => level.value,);@@ -1569,7 +1573,9 @@ describe("Clickhouse Events Repository Test", () => {});const filteredObservations = result.filter((o) =>- [traceId1, traceId2, traceId3].includes(o.traceId ?? ""),+ ([traceId1, traceId2, traceId3] as string[]).includes(+ o.traceId ?? "",+ ),);expect(filteredObservations.length).toBe(2);const traceIds = filteredObservations.map((o) => o.traceId).sort();@@ -1683,7 +1689,9 @@ describe("Clickhouse Events Repository Test", () => {});const filteredObservations = result.filter((o) =>- [traceId1, traceId2, traceId3].includes(o.traceId ?? ""),+ ([traceId1, traceId2, traceId3] as string[]).includes(+ o.traceId ?? "",+ ),);expect(filteredObservations.length).toBe(2);const names = filteredObservations.map((o) => o.name).sort();@@ -1871,7 +1879,9 @@ describe("Clickhouse Events Repository Test", () => {});const filteredObservations = result.filter((o) =>- [traceId1, traceId2, traceId3].includes(o.traceId ?? ""),+ ([traceId1, traceId2, traceId3] as string[]).includes(+ o.traceId ?? "",+ ),);expect(filteredObservations.length).toBe(1);expect(filteredObservations[0].name).toBe("new-user-1");@@ -3306,10 +3316,14 @@ describe("Clickhouse Events Repository Test", () => {});it("should handle empty observation array", async () => {+ // minStartTime/maxStartTime are intentionally omitted: the function+ // early-returns on an empty observations array before touching them.const result = await getObservationsBatchIOFromEventsTable({projectId,observations: [],- });+ } as unknown as Parameters<+ typeof getObservationsBatchIOFromEventsTable+ >[0]);expect(result).toBeDefined();expect(result).toEqual([]);@@ -3735,8 +3749,8 @@ describe("Clickhouse Events Repository Test", () => {projectId: uniqueProjectId,});- const scoreCategoryLabels = options.score_categories.map((c) => c.label);- const traceScoreCategoryLabels = options.trace_score_categories.map(+ const scoreCategoryLabels = options.score_categories!.map((c) => c.label);+ const traceScoreCategoryLabels = options.trace_score_categories!.map((c) => c.label,);diff --git a/web/src/__tests__/server/repositories/experiment-repository.servertest.ts b/web/src/__tests__/server/repositories/experiment-repository.servertest.tsindex 3e64dc48bb..b70f25b38a 100644--- a/web/src/__tests__/server/repositories/experiment-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/experiment-repository.servertest.ts@@ -201,7 +201,9 @@ describe("Clickhouse Experiment Repository Test", () => {// Filter to only our test experimentsconst testExperiments = result.filter((e) =>- [experimentId1, experimentId2, experimentId3].includes(e.id),+ ([experimentId1, experimentId2, experimentId3] as string[]).includes(+ e.id,+ ),);expect(testExperiments.length).toBe(3);@@ -1318,7 +1320,9 @@ describe("Clickhouse Experiment Repository Test", () => {trace_id: traceId,observation_id: null,name: "quality",- value: null,+ // Categorical scores store NULL in the Nullable(Float64) value column;+ // the insert schema types value as number, so cast to keep the fixture.+ value: null as unknown as number,string_value: "good",source: "API",data_type: "CATEGORICAL",@@ -1385,7 +1389,9 @@ describe("Clickhouse Experiment Repository Test", () => {trace_id: traceId,observation_id: rootSpanId,name: "sentiment",- value: null,+ // Categorical scores store NULL in the Nullable(Float64) value column;+ // the insert schema types value as number, so cast to keep the fixture.+ value: null as unknown as number,string_value: "positive",source: "API",data_type: "CATEGORICAL",@@ -1547,7 +1553,9 @@ describe("Clickhouse Experiment Repository Test", () => {trace_id: traceId1,observation_id: null,name: "rating",- value: null,+ // Categorical scores store NULL in the Nullable(Float64) value column;+ // the insert schema types value as number, so cast to keep the fixture.+ value: null as unknown as number,string_value: "excellent",source: "API",data_type: "CATEGORICAL",@@ -1558,7 +1566,9 @@ describe("Clickhouse Experiment Repository Test", () => {trace_id: traceId2,observation_id: null,name: "rating",- value: null,+ // Categorical scores store NULL in the Nullable(Float64) value column;+ // the insert schema types value as number, so cast to keep the fixture.+ value: null as unknown as number,string_value: "poor",source: "API",data_type: "CATEGORICAL",@@ -1617,7 +1627,9 @@ describe("Clickhouse Experiment Repository Test", () => {project_id: projectId,dataset_run_id: experimentId,name: "run_grade",- value: null,+ // Categorical scores store NULL in the Nullable(Float64) value column;+ // the insert schema types value as number, so cast to keep the fixture.+ value: null as unknown as number,string_value: "pass",source: "API",data_type: "CATEGORICAL",diff --git a/web/src/__tests__/server/scim-api.servertest.ts b/web/src/__tests__/server/scim-api.servertest.tsindex b7fb8006b0..539aa81fcc 100644--- a/web/src/__tests__/server/scim-api.servertest.ts+++ b/web/src/__tests__/server/scim-api.servertest.ts@@ -173,7 +173,7 @@ describe("SCIM API", () => {});it("should return 401 when invalid API keys are provided", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("GET","/api/public/scim/ServiceProviderConfig",undefined,@@ -184,7 +184,7 @@ describe("SCIM API", () => {});it("should return 403 when using project API key instead of organization API key", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("GET","/api/public/scim/ServiceProviderConfig",undefined,@@ -197,7 +197,7 @@ describe("SCIM API", () => {});it("should return 405 for non-GET methods", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("POST","/api/public/scim/ServiceProviderConfig",{},@@ -230,7 +230,7 @@ describe("SCIM API", () => {});it("should return 401 when invalid API keys are provided", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("GET","/api/public/scim/Schemas",undefined,@@ -241,7 +241,7 @@ describe("SCIM API", () => {});it("should return 403 when using project API key instead of organization API key", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("GET","/api/public/scim/Schemas",undefined,@@ -254,7 +254,7 @@ describe("SCIM API", () => {});it("should return 405 for non-GET methods", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("POST","/api/public/scim/Schemas",{},@@ -288,7 +288,7 @@ describe("SCIM API", () => {});it("should return 401 when invalid API keys are provided", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("GET","/api/public/scim/ResourceTypes",undefined,@@ -299,7 +299,7 @@ describe("SCIM API", () => {});it("should return 403 when using project API key instead of organization API key", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("GET","/api/public/scim/ResourceTypes",undefined,@@ -312,7 +312,7 @@ describe("SCIM API", () => {});it("should return 405 for non-GET methods", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("POST","/api/public/scim/ResourceTypes",{},@@ -358,7 +358,7 @@ describe("SCIM API", () => {it("should support filtering by userName", async () => {// First create a test userconst uniqueEmail = `test.user.${randomUUID().substring(0, 8)}@example.com`;- const createResponse = await makeAPICall(+ const createResponse = await makeAPICall<{ id: string }>("POST","/api/public/scim/Users",{@@ -397,7 +397,7 @@ describe("SCIM API", () => {});it("should return 401 when invalid API keys are provided", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("GET","/api/public/scim/Users",undefined,@@ -408,7 +408,7 @@ describe("SCIM API", () => {});it("should return 403 when using project API key instead of organization API key", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("GET","/api/public/scim/Users",undefined,@@ -421,7 +421,7 @@ describe("SCIM API", () => {});it("should return 405 for non-GET/POST methods", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("PUT","/api/public/scim/Users",{},@@ -459,8 +459,8 @@ describe("SCIM API", () => {expect(response.status).toBe(201);expect(response.body.userName).toBe(uniqueEmail);- expect(response.body.name.formatted).toBe("Test User");- expect(response.body.emails[0].value).toBe(uniqueEmail);+ expect(response.body.name!.formatted).toBe("Test User");+ expect(response.body.emails![0].value).toBe(uniqueEmail);testUserId = response.body.id;@@ -501,10 +501,12 @@ describe("SCIM API", () => {expect(response.status).toBe(201);expect(response.body.userName).toBe(uniqueEmail);- expect(response.body.name.formatted).toBe("Test User With Password");- expect(response.body.emails[0].value).toBe(uniqueEmail);+ expect(response.body.name!.formatted).toBe("Test User With Password");+ expect(response.body.emails![0].value).toBe(uniqueEmail);// Password should not be returned in the response- expect(response.body.password).toBeUndefined();+ expect(+ (response.body as unknown as { password?: string }).password,+ ).toBeUndefined();testUserId = response.body.id;@@ -521,7 +523,7 @@ describe("SCIM API", () => {});it("should return 400 when userName is missing", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("POST","/api/public/scim/Users",{@@ -562,7 +564,7 @@ describe("SCIM API", () => {expect(response.status).toBe(201);expect(response.body.userName).toBe(uniqueEmail);- expect(response.body.name.formatted).toBe("Test User With Role");+ expect(response.body.name!.formatted).toBe("Test User With Role");testUserId = response.body.id;@@ -576,7 +578,7 @@ describe("SCIM API", () => {it("should write an audit log entry when creating a user", async () => {const uniqueEmail = `test.user.${randomUUID().substring(0, 8)}@example.com`;- const response = await makeAPICall(+ const response = await makeAPICall<{ id: string }>("POST","/api/public/scim/Users",{@@ -615,7 +617,7 @@ describe("SCIM API", () => {const uniqueEmail = `test.user.${randomUUID().substring(0, 8)}@example.com`;// First create a user- const createResponse = await makeAPICall(+ const createResponse = await makeAPICall<{ id: string }>("POST","/api/public/scim/Users",{@@ -630,7 +632,7 @@ describe("SCIM API", () => {testUserId = createResponse.body.id;// Try to create another user with the same userName- const duplicateResult = await makeAPICall(+ const duplicateResult = await makeAPICall<{ detail: string }>("POST","/api/public/scim/Users",{@@ -651,7 +653,7 @@ describe("SCIM API", () => {const lowerCaseEmail = `${localPart.toLowerCase()}@example.com`;// Create with mixed-case userName- const createResponse = await makeAPICall(+ const createResponse = await makeAPICall<{ id: string }>("POST","/api/public/scim/Users",{@@ -672,7 +674,7 @@ describe("SCIM API", () => {expect(storedUser?.email).toBe(lowerCaseEmail);// Re-POST with a case-variant userName: must be detected as duplicate- const duplicateResult = await makeAPICall(+ const duplicateResult = await makeAPICall<{ detail: string }>("POST","/api/public/scim/Users",{@@ -727,12 +729,12 @@ describe("SCIM API", () => {expect(response.status).toBe(200);expect(response.body.id).toBe(testUserId);- expect(response.body.name.formatted).toBe("Test User");+ expect(response.body.name!.formatted).toBe("Test User");});it("should return 404 when user does not exist", async () => {const nonExistentUserId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("GET",`/api/public/scim/Users/${nonExistentUserId}`,undefined,@@ -975,7 +977,7 @@ describe("SCIM API", () => {});it("should return 400 when SCIM schema is missing", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("PUT",`/api/public/scim/Users/${testUserId}`,{@@ -991,7 +993,7 @@ describe("SCIM API", () => {it("should return 404 when user does not exist", async () => {const nonExistentUserId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("PUT",`/api/public/scim/Users/${nonExistentUserId}`,{@@ -1128,7 +1130,7 @@ describe("SCIM API", () => {it("should return 404 when user does not exist", async () => {const nonExistentUserId = randomUUID();- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("DELETE",`/api/public/scim/Users/${nonExistentUserId}`,undefined,@@ -1313,7 +1315,7 @@ describe("SCIM API", () => {});it("DELETE rejects removing the only remaining OWNER", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("DELETE",`/api/public/scim/Users/${scopedOwnerUserId}`,undefined,@@ -1333,7 +1335,7 @@ describe("SCIM API", () => {});it("PUT active:false rejects removing the only remaining OWNER", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("PUT",`/api/public/scim/Users/${scopedOwnerUserId}`,{@@ -1358,7 +1360,7 @@ describe("SCIM API", () => {});it("PATCH active:false rejects removing the only remaining OWNER", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("PATCH",`/api/public/scim/Users/${scopedOwnerUserId}`,{@@ -1381,7 +1383,7 @@ describe("SCIM API", () => {});it("PUT active:true with a lower role rejects demoting the only remaining OWNER", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("PUT",`/api/public/scim/Users/${scopedOwnerUserId}`,{@@ -1549,7 +1551,7 @@ describe("SCIM API", () => {it("POST /Users is rejected on a plan without admin-api and creates no account", async () => {const uniqueEmail = `scim.gate.${randomUUID().substring(0, 8)}@example.com`;- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("POST","/api/public/scim/Users",{@@ -1574,7 +1576,7 @@ describe("SCIM API", () => {});it("GET /Users is rejected on a plan without admin-api", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("GET","/api/public/scim/Users",undefined,@@ -1586,7 +1588,7 @@ describe("SCIM API", () => {});it("PUT /Users/{id} is rejected on a plan without admin-api (before user lookup)", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("PUT",`/api/public/scim/Users/${randomUUID()}`,{@@ -1603,7 +1605,7 @@ describe("SCIM API", () => {});it("DELETE /Users/{id} is rejected on a plan without admin-api", async () => {- const result = await makeAPICall(+ const result = await makeAPICall<{ detail: string }>("DELETE",`/api/public/scim/Users/${randomUUID()}`,undefined,@@ -1616,7 +1618,7 @@ describe("SCIM API", () => {it("POST /Users still succeeds on a plan with admin-api", async () => {const uniqueEmail = `scim.gate.ok.${randomUUID().substring(0, 8)}@example.com`;- const result = await makeAPICall(+ const result = await makeAPICall<{ userName: string }>("POST","/api/public/scim/Users",{diff --git a/web/src/__tests__/server/score-comparison-analytics.servertest.ts b/web/src/__tests__/server/score-comparison-analytics.servertest.tsindex 4b2335d91d..b51a0d60aa 100644--- a/web/src/__tests__/server/score-comparison-analytics.servertest.ts+++ b/web/src/__tests__/server/score-comparison-analytics.servertest.ts@@ -35,7 +35,9 @@ describe("Score Comparison Analytics tRPC", () => {retentionDays: 30,deletedAt: null,name: "Test Project",+ hasTraces: false,metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -43,6 +45,10 @@ describe("Score Comparison Analytics tRPC", () => {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},diff --git a/web/src/__tests__/server/scores-api-v1.servertest.ts b/web/src/__tests__/server/scores-api-v1.servertest.tsindex 9df6ef2cea..fd0c0791b1 100644--- a/web/src/__tests__/server/scores-api-v1.servertest.ts+++ b/web/src/__tests__/server/scores-api-v1.servertest.ts@@ -60,6 +60,13 @@ const getScoreIngestionAttribution = async (return rows[0];};+// GetScoreResponseV1 is a union whose TEXT variant carries no `value`; the+// scores asserted below are NUMERIC, so narrow to the value-carrying variants.+type APIScoreV1WithValue = Extract<+ z.infer<typeof GetScoreResponseV1>,+ { value: number }+>;+describe("/api/public/scores API Endpoint", () => {describe("GET /api/public/scores/:scoreId", () => {it("should GET a score", async () => {@@ -263,7 +270,7 @@ describe("/api/public/scores API Endpoint", () => {expect(fetchedScore.body?.id).toBe(scoreId);expect(fetchedScore.body?.traceId).toBe(traceId);expect(fetchedScore.body?.name).toBe("score-name");- expect(fetchedScore.body?.value).toBe(100.5);+ expect((fetchedScore.body as APIScoreV1WithValue)?.value).toBe(100.5);expect(fetchedScore.body?.observationId).toBeNull();expect(fetchedScore.body?.comment).toBe("comment");expect(fetchedScore.body?.source).toBe("API");@@ -319,7 +326,7 @@ describe("/api/public/scores API Endpoint", () => {expect(fetchedScore.body?.id).toBe(scoreId);expect(fetchedScore.body?.traceId).toBe(traceId);expect(fetchedScore.body?.name).toBe("score-name");- expect(fetchedScore.body?.value).toBe(200.5);+ expect((fetchedScore.body as APIScoreV1WithValue)?.value).toBe(200.5);expect(fetchedScore.body?.observationId).toBeNull();expect(fetchedScore.body?.comment).toBe("comment");expect(fetchedScore.body?.source).toBe("API");@@ -381,7 +388,7 @@ describe("/api/public/scores API Endpoint", () => {expect(fetchedScore.body?.id).toBe(scoreId);expect(fetchedScore.body?.traceId).toBe(traceId);expect(fetchedScore.body?.name).toBe("score-name");- expect(fetchedScore.body?.value).toBe(100);+ expect((fetchedScore.body as APIScoreV1WithValue)?.value).toBe(100);expect(fetchedScore.body?.configId).toBe(configId);expect(fetchedScore.body?.observationId).toBeNull();expect(fetchedScore.body?.comment).toBe("comment");@@ -472,7 +479,9 @@ describe("/api/public/scores API Endpoint", () => {dataType: "NUMERIC",});expect(score.name).toMatch(/^score-\d+$/);- expect(score.value).toBe(parseInt(score.name.split("-")[1]));+ expect((score as APIScoreV1WithValue).value).toBe(+ parseInt(score.name.split("-")[1]),+ );}// Check if we need to fetch more pagesdiff --git a/web/src/__tests__/server/scores-api-v2.servertest.ts b/web/src/__tests__/server/scores-api-v2.servertest.tsindex b44f558dfb..c3c4747dc1 100644--- a/web/src/__tests__/server/scores-api-v2.servertest.ts+++ b/web/src/__tests__/server/scores-api-v2.servertest.ts@@ -17,6 +17,17 @@ import { prisma } from "@langfuse/shared/src/db";import { v4 } from "uuid";import { z } from "zod";+// GetScoresResponseV2 rows are a union where only the trace-enriched branch+// carries `trace`; narrow to that branch for assertions on trace fields.+type ScoreV2WithTrace = z.infer<typeof GetScoresResponseV2>["data"][number] & {+ trace?: {+ userId?: string | null;+ tags?: string[] | null;+ environment?: string | null;+ sessionId?: string | null;+ } | null;+};+describe("/api/public/v2/scores API Endpoint", () => {describe("GET /api/public/v2/scores/:scoreId", () => {let auth: string;@@ -625,9 +636,10 @@ describe("/api/public/v2/scores API Endpoint", () => {totalPages: 1,});for (const val of getAllScore.body.data) {- expect(val.traceId).toBe(traceId);- expect(val.trace?.tags?.sort()).toEqual(["prod", "test"].sort());- expect(val.trace?.userId).toBe("user-name");+ const score = val as ScoreV2WithTrace;+ expect(score.traceId).toBe(traceId);+ expect(score.trace?.tags?.sort()).toEqual(["prod", "test"].sort());+ expect(score.trace?.userId).toBe("user-name");}});@@ -1842,7 +1854,7 @@ describe("/api/public/v2/scores API Endpoint", () => {expect(getScores.body.data).toHaveLength(3);// All scores should have trace as nullfor (const score of getScores.body.data) {- expect(score.trace).toBeNull();+ expect((score as ScoreV2WithTrace).trace).toBeNull();}});});diff --git a/web/src/__tests__/server/scores-trpc-events-only.servertest.ts b/web/src/__tests__/server/scores-trpc-events-only.servertest.tsindex ecd5a20078..9a4535aeaf 100644--- a/web/src/__tests__/server/scores-trpc-events-only.servertest.ts+++ b/web/src/__tests__/server/scores-trpc-events-only.servertest.ts@@ -74,6 +74,9 @@ maybe(role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: projectId,@@ -81,6 +84,9 @@ maybe(retentionDays: 30,deletedAt: null,name: "Test Project",+ hasTraces: false,+ metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -88,13 +94,17 @@ maybe(featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });const caller = appRouter.createCaller({ ...ctx, prisma });// Seed a single root event for a session into the events table and wait untildiff --git a/web/src/__tests__/server/scores-trpc.servertest.ts b/web/src/__tests__/server/scores-trpc.servertest.tsindex e8175acf74..b0ce247ae8 100644--- a/web/src/__tests__/server/scores-trpc.servertest.ts+++ b/web/src/__tests__/server/scores-trpc.servertest.ts@@ -79,6 +79,9 @@ describe("scores trpc", () => {role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: projectId,@@ -86,6 +89,9 @@ describe("scores trpc", () => {retentionDays: 30,deletedAt: null,name: "Test Project",+ hasTraces: false,+ metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -93,13 +99,17 @@ describe("scores trpc", () => {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });caller = appRouter.createCaller({ ...ctx, prisma });});@@ -146,15 +156,15 @@ describe("scores trpc", () => {filter: [{column: "booleanValue",- type: "stringOptions",- operator: "none of",+ type: "stringOptions" as const,+ operator: "none of" as const,value: ["false"],},],- orderBy: { column: "timestamp", order: "DESC" },+ orderBy: { column: "timestamp", order: "DESC" as const },page: 0,limit: 50,- } as const;+ };const result = await caller.scores.all(payload);const resultFromEvents = await caller.scores.allFromEvents(payload);@@ -418,7 +428,7 @@ describe("scores trpc", () => {describe("scoreConfigs.all", () => {it("should paginate score configs deterministically when createdAt timestamps tie", async () => {const sharedCreatedAt = new Date("2100-05-12T00:00:00.000Z");- const configIds = [randomUUID(), randomUUID(), randomUUID()];+ const configIds: string[] = [randomUUID(), randomUUID(), randomUUID()];await prisma.scoreConfig.createMany({data: configIds.map((id, index) => ({diff --git a/web/src/__tests__/server/sessions-comment-filter.servertest.ts b/web/src/__tests__/server/sessions-comment-filter.servertest.tsindex a9771b849b..0975317b52 100644--- a/web/src/__tests__/server/sessions-comment-filter.servertest.ts+++ b/web/src/__tests__/server/sessions-comment-filter.servertest.ts@@ -30,6 +30,9 @@ describe("Sessions Comment Filtering", () => {role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: projectId,@@ -37,6 +40,9 @@ describe("Sessions Comment Filtering", () => {retentionDays: 30,deletedAt: null,name: "Test Project",+ hasTraces: false,+ metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -44,13 +50,17 @@ describe("Sessions Comment Filtering", () => {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });caller = appRouter.createCaller({ ...ctx, prisma });});@@ -325,8 +335,6 @@ describe("Sessions Comment Filtering", () => {},],orderBy: null as any,- page: 0,- limit: 10,});expect(typeof countResult.totalCount).toBe("number");diff --git a/web/src/__tests__/server/sessions-trpc-events-only.servertest.ts b/web/src/__tests__/server/sessions-trpc-events-only.servertest.tsindex 63d53eb61c..d283f53a17 100644--- a/web/src/__tests__/server/sessions-trpc-events-only.servertest.ts+++ b/web/src/__tests__/server/sessions-trpc-events-only.servertest.ts@@ -69,6 +69,9 @@ maybe("sessions trpc (events_only write mode)", () => {role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: projectId,@@ -76,6 +79,9 @@ maybe("sessions trpc (events_only write mode)", () => {retentionDays: 30,deletedAt: null,name: "Test Project",+ hasTraces: false,+ metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -83,13 +89,17 @@ maybe("sessions trpc (events_only write mode)", () => {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });const caller = appRouter.createCaller({ ...ctx, prisma });// Seed a single root event for a session into the events table and wait untildiff --git a/web/src/__tests__/server/sessions-trpc.servertest.ts b/web/src/__tests__/server/sessions-trpc.servertest.tsindex d36b5c7403..27504b1d20 100644--- a/web/src/__tests__/server/sessions-trpc.servertest.ts+++ b/web/src/__tests__/server/sessions-trpc.servertest.ts@@ -26,6 +26,9 @@ describe("traces trpc", () => {role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: projectId,@@ -33,6 +36,9 @@ describe("traces trpc", () => {retentionDays: 30,deletedAt: null,name: "Test Project",+ hasTraces: false,+ metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -40,13 +46,17 @@ describe("traces trpc", () => {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });const caller = appRouter.createCaller({ ...ctx, prisma });describe("sessions.byIdWithScores", () => {@@ -225,8 +235,6 @@ describe("traces trpc", () => {// Whenconst sessions = await caller.sessions.countAll({projectId,- limit: 50,- page: 0,filter: null,orderBy: null,});diff --git a/web/src/__tests__/server/sessions-ui-table.servertest.ts b/web/src/__tests__/server/sessions-ui-table.servertest.tsindex 6f6ae1d3a5..8632624f0c 100644--- a/web/src/__tests__/server/sessions-ui-table.servertest.ts+++ b/web/src/__tests__/server/sessions-ui-table.servertest.ts@@ -37,10 +37,7 @@ async function sessionsWithMetrics(props: {if (!isEventsPath) {return getSessionsWithMetrics(props);}- const idFilter = props.filter.find(- (f): f is Extract<FilterState[number], { column: "id" }> =>- f.column === "id",- );+ const idFilter = props.filter.find((f) => f.column === "id");const sessionIds =idFilter && "value" in idFilter ? (idFilter.value as string[]) : [];return getSessionMetricsFromEvents({@@ -49,6 +46,22 @@ async function sessionsWithMetrics(props: {});}+/**+ * Type-level shim for event fixtures that pass `metadata` (and a stringified+ * `prompt_version`), which EventRecordInsertType does not model. events_full+ * has no `metadata` map column — ClickHouse skips unknown JSONEachRow fields+ * on insert — so the extra key is inert; the cast keeps the fixture unchanged.+ */+type EventInsertInput = Parameters<typeof createEvent>[0];+function asEventInsert(+ event: Omit<EventInsertInput, "prompt_version"> & {+ metadata?: Record<string, string>;+ prompt_version?: string | number | null;+ },+): EventInsertInput {+ return event as unknown as EventInsertInput;+}+/*** Derive v2 events from v1 traces + observations.* Reused from dashboard-v1-v2-consistency.servertest.ts.@@ -67,36 +80,38 @@ function buildMatchingEvents(// Root events — one per trace.for (const t of traces) {events.push(- createEvent({- id: `t-${t.id}`,- span_id: `t-${t.id}`,- trace_id: t.id,- project_id: t.project_id,- parent_span_id: "",- name: t.name ?? "",- type: "SPAN",- environment: t.environment,- trace_name: t.name ?? "",- user_id: t.user_id ?? "",- session_id: t.session_id ?? null,- tags: t.tags ?? [],- release: t.release ?? null,- version: t.version ?? null,- public: t.public,- bookmarked: t.bookmarked,- input: t.input ?? null,- output: t.output ?? null,- metadata: t.metadata ?? {},- start_time: t.timestamp * 1000,- end_time: null,- cost_details: {},- provided_cost_details: {},- usage_details: {},- provided_usage_details: {},- created_at: t.created_at * 1000,- updated_at: t.updated_at * 1000,- event_ts: t.event_ts * 1000,- }),+ createEvent(+ asEventInsert({+ id: `t-${t.id}`,+ span_id: `t-${t.id}`,+ trace_id: t.id,+ project_id: t.project_id,+ parent_span_id: "",+ name: t.name ?? "",+ type: "SPAN",+ environment: t.environment,+ trace_name: t.name ?? "",+ user_id: t.user_id ?? "",+ session_id: t.session_id ?? null,+ tags: t.tags ?? [],+ release: t.release ?? null,+ version: t.version ?? null,+ public: t.public,+ bookmarked: t.bookmarked,+ input: t.input ?? null,+ output: t.output ?? null,+ metadata: t.metadata ?? {},+ start_time: t.timestamp * 1000,+ end_time: null,+ cost_details: {},+ provided_cost_details: {},+ usage_details: {},+ provided_usage_details: {},+ created_at: t.created_at * 1000,+ updated_at: t.updated_at * 1000,+ event_ts: t.event_ts * 1000,+ }),+ ),);}@@ -105,47 +120,49 @@ function buildMatchingEvents(const traceId = o.trace_id!;const t = traceMap.get(traceId)!;events.push(- createEvent({- id: o.id,- span_id: o.id,- trace_id: traceId,- project_id: o.project_id,- parent_span_id: o.parent_observation_id ?? `t-${traceId}`,- name: o.name ?? "",- type: o.type as string,- environment: o.environment,- trace_name: t.name ?? "",- user_id: t.user_id ?? "",- session_id: t.session_id ?? undefined,- tags: t.tags ?? [],- release: t.release ?? null,- version: o.version ?? null,- level: o.level ?? "DEFAULT",- status_message: o.status_message ?? null,- provided_model_name: o.provided_model_name ?? null,- model_parameters: o.model_parameters ?? "{}",- input: o.input ?? null,- output: o.output ?? null,- metadata: { ...(t.metadata ?? {}), ...(o.metadata ?? {}) },- provided_usage_details: o.provided_usage_details ?? {},- usage_details: o.usage_details ?? {},- provided_cost_details: o.provided_cost_details ?? {},- cost_details: o.cost_details ?? {},- prompt_id: o.prompt_id ?? null,- prompt_name: o.prompt_name ?? null,- prompt_version: o.prompt_version ? String(o.prompt_version) : null,- tool_definitions: o.tool_definitions ?? {},- tool_calls: o.tool_calls ?? [],- tool_call_names: o.tool_call_names ?? [],- start_time: o.start_time * 1000,- end_time: o.end_time ? o.end_time * 1000 : null,- completion_start_time: o.completion_start_time- ? o.completion_start_time * 1000- : null,- created_at: o.created_at * 1000,- updated_at: o.updated_at * 1000,- event_ts: o.event_ts * 1000,- }),+ createEvent(+ asEventInsert({+ id: o.id,+ span_id: o.id,+ trace_id: traceId,+ project_id: o.project_id,+ parent_span_id: o.parent_observation_id ?? `t-${traceId}`,+ name: o.name ?? "",+ type: o.type as string,+ environment: o.environment,+ trace_name: t.name ?? "",+ user_id: t.user_id ?? "",+ session_id: t.session_id ?? undefined,+ tags: t.tags ?? [],+ release: t.release ?? null,+ version: o.version ?? null,+ level: o.level ?? "DEFAULT",+ status_message: o.status_message ?? null,+ provided_model_name: o.provided_model_name ?? null,+ model_parameters: o.model_parameters ?? "{}",+ input: o.input ?? null,+ output: o.output ?? null,+ metadata: { ...(t.metadata ?? {}), ...(o.metadata ?? {}) },+ provided_usage_details: o.provided_usage_details ?? {},+ usage_details: o.usage_details ?? {},+ provided_cost_details: o.provided_cost_details ?? {},+ cost_details: o.cost_details ?? {},+ prompt_id: o.prompt_id ?? null,+ prompt_name: o.prompt_name ?? null,+ prompt_version: o.prompt_version ? String(o.prompt_version) : null,+ tool_definitions: o.tool_definitions ?? {},+ tool_calls: o.tool_calls ?? [],+ tool_call_names: o.tool_call_names ?? [],+ start_time: o.start_time * 1000,+ end_time: o.end_time ? o.end_time * 1000 : null,+ completion_start_time: o.completion_start_time+ ? o.completion_start_time * 1000+ : null,+ created_at: o.created_at * 1000,+ updated_at: o.updated_at * 1000,+ event_ts: o.event_ts * 1000,+ }),+ ),);}diff --git a/web/src/__tests__/server/slack-integration.servertest.ts b/web/src/__tests__/server/slack-integration.servertest.tsindex ffcc5787fd..b7914392c3 100644--- a/web/src/__tests__/server/slack-integration.servertest.ts+++ b/web/src/__tests__/server/slack-integration.servertest.ts@@ -38,6 +38,8 @@ const prepare = async () => {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: project.id,@@ -45,14 +47,20 @@ const prepare = async () => {retentionDays: 30,deletedAt: null,name: project.name,+ hasTraces: false,metadata: {},+ createdAt: new Date().toISOString(),},],},],featureFlags: {- excludeClickhouseRead: false,+ searchBar: false,templateFlag: true,+ excludeClickhouseRead: false,+ observationEvals: false,+ v4BetaToggleVisible: false,+ experimentsV4Enabled: false,},admin: true,},diff --git a/web/src/__tests__/server/ssoConfigRouter.servertest.ts b/web/src/__tests__/server/ssoConfigRouter.servertest.tsindex b4d6d9751c..a3c440fa42 100644--- a/web/src/__tests__/server/ssoConfigRouter.servertest.ts+++ b/web/src/__tests__/server/ssoConfigRouter.servertest.ts@@ -86,6 +86,7 @@ function createSession(v4BetaToggleVisible: false,observationEvals: false,experimentsV4Enabled: false,+ searchBar: false,},admin: false,},diff --git a/web/src/__tests__/server/table-view-namespace-compat.servertest.ts b/web/src/__tests__/server/table-view-namespace-compat.servertest.tsindex 6ddacc4c11..cf88f8742a 100644--- a/web/src/__tests__/server/table-view-namespace-compat.servertest.ts+++ b/web/src/__tests__/server/table-view-namespace-compat.servertest.ts@@ -1,6 +1,6 @@/** @jest-environment node */-import { prisma } from "@langfuse/shared/src/db";+import { prisma, type Prisma } from "@langfuse/shared/src/db";import {createOrgProjectAndApiKey,DefaultViewService,@@ -33,7 +33,9 @@ const createTableViewPreset = async ({columnOrder: [],columnVisibility: {},searchQuery: null,- orderBy: null,+ // Preserve the runtime value; Prisma's types only accept+ // Prisma.JsonNull/DbNull for nullable Json inputs.+ orderBy: null as unknown as Prisma.NullableJsonNullValueInput,},});diff --git a/web/src/__tests__/server/table-view-presets-trpc.servertest.ts b/web/src/__tests__/server/table-view-presets-trpc.servertest.tsindex 94b660a45d..4ddb7c6990 100644--- a/web/src/__tests__/server/table-view-presets-trpc.servertest.ts+++ b/web/src/__tests__/server/table-view-presets-trpc.servertest.ts@@ -3,7 +3,7 @@import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import { TableViewPresetTableName } from "@langfuse/shared";-import { prisma } from "@langfuse/shared/src/db";+import { prisma, type Prisma } from "@langfuse/shared/src/db";import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";import type { Session } from "next-auth";import { randomUUID } from "node:crypto";@@ -24,21 +24,29 @@ const prepare = async () => {plan: "cloud:hobby",cloudConfig: undefined,metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: true,projects: [{id: project.id,role: "ADMIN",retentionDays: 30,deletedAt: null,+ hasTraces: false,name: project.name,metadata: {},+ createdAt: new Date().toISOString(),},],},],featureFlags: {+ searchBar: false,excludeClickhouseRead: false,templateFlag: true,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: false,},@@ -69,7 +77,9 @@ describe("table view presets tRPC", () => {columnOrder: [],columnVisibility: {},searchQuery: null,- orderBy: null,+ // Preserve the runtime value; Prisma's types only accept+ // Prisma.JsonNull/DbNull for nullable Json inputs.+ orderBy: null as unknown as Prisma.NullableJsonNullValueInput,},});await prisma.defaultView.create({diff --git a/web/src/__tests__/server/traces-batch-delete-trpc.servertest.ts b/web/src/__tests__/server/traces-batch-delete-trpc.servertest.tsindex 251725f508..4aa1f11197 100644--- a/web/src/__tests__/server/traces-batch-delete-trpc.servertest.ts+++ b/web/src/__tests__/server/traces-batch-delete-trpc.servertest.ts@@ -50,6 +50,7 @@ const createCaller = async (opts: { v4BetaEnabled?: boolean } = {}) => {user: {id: `user-${randomUUID()}`,name: "Batch Delete Test User",+ canCreateOrganizations: true,admin: true,v4BetaEnabled: opts.v4BetaEnabled ?? false,organizations: [@@ -59,6 +60,9 @@ const createCaller = async (opts: { v4BetaEnabled?: boolean } = {}) => {role: "OWNER",plan: "cloud:team",cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: project.id,@@ -66,6 +70,9 @@ const createCaller = async (opts: { v4BetaEnabled?: boolean } = {}) => {retentionDays: 30,deletedAt: null,name: project.name,+ hasTraces: true,+ metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -73,12 +80,16 @@ const createCaller = async (opts: { v4BetaEnabled?: boolean } = {}) => {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},},environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });return {projectId: project.id,session,@@ -111,7 +122,7 @@ describe("traces.deleteMany batch action", () => {});expect(batchAction).toMatchObject({projectId,- userId: session.user.id,+ userId: session.user!.id,actionType: "trace-delete",tableName: "traces",status: BatchActionStatus.Queued,@@ -143,7 +154,7 @@ describe("traces.deleteMany batch action", () => {data: {id: batchActionId,projectId,- userId: session.user.id,+ userId: session.user!.id,actionType: "trace-delete",tableName: "traces",status: BatchActionStatus.Processing,@@ -195,7 +206,7 @@ describe("traces.deleteMany batch action", () => {data: {id: batchActionId,projectId,- userId: session.user.id,+ userId: session.user!.id,actionType: "trace-delete",tableName: "traces",status: BatchActionStatus.Completed,@@ -263,7 +274,7 @@ describe("traces.deleteMany batch action", () => {data: {id: batchActionId,projectId,- userId: session.user.id,+ userId: session.user!.id,actionType: "trace-delete",tableName: "traces",status: BatchActionStatus.Processing,diff --git a/web/src/__tests__/server/traces-comment-filter.servertest.ts b/web/src/__tests__/server/traces-comment-filter.servertest.tsindex d5cb4f0c58..284d3f2e8b 100644--- a/web/src/__tests__/server/traces-comment-filter.servertest.ts+++ b/web/src/__tests__/server/traces-comment-filter.servertest.ts@@ -30,6 +30,9 @@ describe("Traces Comment Filtering", () => {role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: projectId,@@ -37,6 +40,9 @@ describe("Traces Comment Filtering", () => {retentionDays: 30,deletedAt: null,name: "Test Project",+ hasTraces: true,+ metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -44,13 +50,17 @@ describe("Traces Comment Filtering", () => {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });caller = appRouter.createCaller({ ...ctx, prisma });});diff --git a/web/src/__tests__/server/traces-trpc-events-only.servertest.ts b/web/src/__tests__/server/traces-trpc-events-only.servertest.tsindex 90d69fa6e3..7292f5a103 100644--- a/web/src/__tests__/server/traces-trpc-events-only.servertest.ts+++ b/web/src/__tests__/server/traces-trpc-events-only.servertest.ts@@ -71,6 +71,9 @@ maybe("traces trpc (events_only write mode)", () => {role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: projectId,@@ -78,6 +81,9 @@ maybe("traces trpc (events_only write mode)", () => {retentionDays: 30,deletedAt: null,name: "Test Project",+ hasTraces: true,+ metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -85,13 +91,17 @@ maybe("traces trpc (events_only write mode)", () => {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });const caller = appRouter.createCaller({ ...ctx, prisma });// Sanity check that the forced write mode reached the parsed shared env that@@ -130,13 +140,19 @@ maybe("traces trpc (events_only write mode)", () => {retentionDays: null,deletedAt: null,name: "events-only-onboarding",+ hasTraces: false,+ metadata: {},+ createdAt: new Date().toISOString(),},],},],},};- const freshCtx = createInnerTRPCContext({ session: freshSession });+ const freshCtx = createInnerTRPCContext({+ session: freshSession,+ headers: {},+ });const freshCaller = appRouter.createCaller({ ...freshCtx, prisma });try {diff --git a/web/src/__tests__/server/traces-trpc.servertest.ts b/web/src/__tests__/server/traces-trpc.servertest.tsindex a2bfae364b..2078df5db6 100644--- a/web/src/__tests__/server/traces-trpc.servertest.ts+++ b/web/src/__tests__/server/traces-trpc.servertest.ts@@ -42,6 +42,9 @@ describe("traces trpc", () => {role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: projectId,@@ -49,6 +52,9 @@ describe("traces trpc", () => {retentionDays: 30,deletedAt: null,name: "Test Project",+ hasTraces: true,+ metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -56,13 +62,17 @@ describe("traces trpc", () => {featureFlags: {excludeClickhouseRead: false,templateFlag: true,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: true,},environment: {} as any,};- const ctx = createInnerTRPCContext({ session });+ const ctx = createInnerTRPCContext({ session, headers: {} });const caller = appRouter.createCaller({ ...ctx, prisma });afterEach(() => {@@ -378,8 +388,10 @@ describe("traces trpc", () => {it("should search traces by input only", async () => {const trace = createTrace({project_id: projectId,- input: { query: "unique_trace_input_keyword" },- output: { result: "different output" },+ // The insert type declares IO as string, but the ClickHouse client+ // serializes object fixtures on insert — keep them via casts.+ input: { query: "unique_trace_input_keyword" } as unknown as string,+ output: { result: "different output" } as unknown as string,name: "input-search-trace",});@@ -412,8 +424,11 @@ describe("traces trpc", () => {it("should search traces by output only", async () => {const trace = createTrace({project_id: projectId,- input: { query: "simple input" },- output: { result: "unique_trace_output_keyword for testing" },+ // See input-search test above for why these fixtures are cast.+ input: { query: "simple input" } as unknown as string,+ output: {+ result: "unique_trace_output_keyword for testing",+ } as unknown as string,name: "output-search-trace",});@@ -475,8 +490,6 @@ describe("traces trpc", () => {],searchQuery: null,searchType: ["id"],- page: 0,- limit: 50,orderBy: {column: "timestamp",order: "DESC",@@ -550,7 +563,10 @@ describe("traces trpc", () => {});it("access trace without any authentication", async () => {- const unAuthedSession = createInnerTRPCContext({ session: null });+ const unAuthedSession = createInnerTRPCContext({+ session: null,+ headers: {},+ });const unAuthedCaller = appRouter.createCaller({...unAuthedSession,prisma,@@ -814,10 +830,14 @@ describe("traces trpc", () => {});expect(metrics).toHaveLength(1);- expect(metrics[0]?.scores[aggregateKey]?.average).toBeCloseTo(0.6, 5);- expect(metrics[0]?.scores[aggregateKey]?.values).toEqual(- expect.arrayContaining([0.4, 0.8]),- );+ const aggregate = metrics[0]?.scores[aggregateKey];+ if (aggregate?.type !== "NUMERIC") {+ throw new Error(+ `Expected a NUMERIC aggregate for ${aggregateKey}, got ${aggregate?.type}`,+ );+ }+ expect(aggregate.average).toBeCloseTo(0.6, 5);+ expect(aggregate.values).toEqual(expect.arrayContaining([0.4, 0.8]));});});@@ -847,7 +867,10 @@ describe("traces trpc", () => {describe("traces.getAgentGraphData", () => {it("should allow unauthenticated access to public trace agent graph data", async () => {- const unAuthedSession = createInnerTRPCContext({ session: null });+ const unAuthedSession = createInnerTRPCContext({+ session: null,+ headers: {},+ });const unAuthedCaller = appRouter.createCaller({...unAuthedSession,prisma,@@ -886,7 +909,10 @@ describe("traces trpc", () => {});it("should deny unauthenticated access to private trace agent graph data", async () => {- const unAuthedSession = createInnerTRPCContext({ session: null });+ const unAuthedSession = createInnerTRPCContext({+ session: null,+ headers: {},+ });const unAuthedCaller = appRouter.createCaller({...unAuthedSession,prisma,@@ -956,13 +982,19 @@ describe("traces trpc", () => {retentionDays: null,deletedAt: null,name: "legacy-onboarding",+ hasTraces: false,+ metadata: {},+ createdAt: new Date().toISOString(),},],},],},};- const freshCtx = createInnerTRPCContext({ session: freshSession });+ const freshCtx = createInnerTRPCContext({+ session: freshSession,+ headers: {},+ });const freshCaller = appRouter.createCaller({ ...freshCtx, prisma });try {diff --git a/web/src/__tests__/server/unit/evaluator-preflight.servertest.ts b/web/src/__tests__/server/unit/evaluator-preflight.servertest.tsindex e9da73cdf6..5b0854230b 100644--- a/web/src/__tests__/server/unit/evaluator-preflight.servertest.ts+++ b/web/src/__tests__/server/unit/evaluator-preflight.servertest.ts@@ -25,6 +25,14 @@ const numericOutputDefinition = createNumericEvalOutputDefinition({scoreDescription: "A score between 0 and 1",});+// The real config carries a full parsed LLM API key record plus the adapter;+// the preflight only reads the connection fields stubbed below, so the+// fixture stays minimal behind a cast.+type ValidModelConfig = Extract<+ Awaited<ReturnType<typeof DefaultEvalModelService.fetchValidModelConfig>>,+ { valid: true }+>["config"];+describe("evaluator preflight", () => {const mockFetchValidModelConfig = vi.mocked(DefaultEvalModelService.fetchValidModelConfig,@@ -49,7 +57,7 @@ describe("evaluator preflight", () => {config: null,adapter: LLMAdapter.OpenAI,},- },+ } as unknown as ValidModelConfig,});});diff --git a/web/src/__tests__/server/unit/observations-converters.servertest.ts b/web/src/__tests__/server/unit/observations-converters.servertest.tsindex 9ea6d3a3af..69d94736e7 100644--- a/web/src/__tests__/server/unit/observations-converters.servertest.ts+++ b/web/src/__tests__/server/unit/observations-converters.servertest.ts@@ -11,6 +11,7 @@ vi.mock("@langfuse/shared/src/db", () => ({ prisma: {} }));import {type EventsObservationRecordReadType,convertEventsObservation,+ DEFAULT_RENDERING_PROPS,} from "@langfuse/shared/src/server";const TRACE_CONTEXT_FIELDS = [@@ -67,7 +68,11 @@ describe("convertEventsObservation", () => {// did not request the trace_context field group};- const result = convertEventsObservation(record, undefined, false);+ const result = convertEventsObservation(+ record,+ DEFAULT_RENDERING_PROPS,+ false,+ );for (const field of TRACE_CONTEXT_FIELDS) {expect(@@ -93,7 +98,11 @@ describe("convertEventsObservation", () => {public: false,};- const result = convertEventsObservation(record, undefined, false);+ const result = convertEventsObservation(+ record,+ DEFAULT_RENDERING_PROPS,+ false,+ );expect(result).toHaveProperty("userId", null);expect(result).toHaveProperty("sessionId", null);@@ -120,7 +129,11 @@ describe("convertEventsObservation", () => {public: true,};- const result = convertEventsObservation(record, undefined, false);+ const result = convertEventsObservation(+ record,+ DEFAULT_RENDERING_PROPS,+ false,+ );expect(result).toHaveProperty("userId", "user-42");expect(result).toHaveProperty("sessionId", "session-99");@@ -139,10 +152,16 @@ describe("convertEventsObservation", () => {session_id: null,trace_name: null,release: null,- tags: null,+ // The V1 read path can surface a null tags column; the insert-oriented+ // type only allows string[], so keep the null fixture via a cast.+ tags: null as unknown as string[],});- const result = convertEventsObservation(record, undefined, true);+ const result = convertEventsObservation(+ record,+ DEFAULT_RENDERING_PROPS,+ true,+ );expect(result).toHaveProperty("userId", null);expect(result).toHaveProperty("sessionId", null);diff --git a/web/src/__tests__/server/unit/onboardingService.servertest.ts b/web/src/__tests__/server/unit/onboardingService.servertest.tsindex d791263836..487c6e9cf5 100644--- a/web/src/__tests__/server/unit/onboardingService.servertest.ts+++ b/web/src/__tests__/server/unit/onboardingService.servertest.ts@@ -50,7 +50,7 @@ const makeMembership = ({metadata: orgMetadata,projects,},- }) as RealOrganizationMembership;+ }) as unknown as RealOrganizationMembership;const makePrisma = (organizationMemberships: RealOrganizationMembership[]) =>({@@ -136,7 +136,9 @@ describe("getCloudSignupOnboardingStatus", () => {it("uses the onboarding survey as the completion marker", async () => {const incomplete = makeCompletionPrisma();- await expect(getStatus(incomplete.tx)).resolves.toEqual({+ await expect(+ getStatus(incomplete.tx as unknown as StatusPrisma),+ ).resolves.toEqual({completed: false,});@@ -150,7 +152,9 @@ describe("getCloudSignupOnboardingStatus", () => {],});- await expect(getStatus(completed.tx)).resolves.toEqual({+ await expect(+ getStatus(completed.tx as unknown as StatusPrisma),+ ).resolves.toEqual({completed: true,redirectTo: "/project/project-1",});diff --git a/web/src/__tests__/server/unit/sfdc-sync.servertest.ts b/web/src/__tests__/server/unit/sfdc-sync.servertest.tsindex 48e15b1fdd..1bf6f27fe2 100644--- a/web/src/__tests__/server/unit/sfdc-sync.servertest.ts+++ b/web/src/__tests__/server/unit/sfdc-sync.servertest.ts@@ -505,8 +505,12 @@ function buildOwnerSession(orgId: string): Session {},],featureFlags: {+ searchBar: false,excludeClickhouseRead: false,templateFlag: true,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: false,},diff --git a/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts b/web/src/__tests__/server/unit/unstable-evals-contract.servertest.tsindex ac4aba2c9b..c83beaf2b2 100644--- a/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts+++ b/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts@@ -845,7 +845,9 @@ describe("unstable public eval adapters", () => {jsonSelector: null,},],- sampling: 1,+ // Stored configs carry a Prisma Decimal; the adapter only reads it as a+ // number, so a plain 1 is a faithful stand-in.+ sampling: 1 as unknown as StoredPublicEvaluationRuleConfig["sampling"],status: JobConfigState.ACTIVE,blockedAt: null,blockReason: null,diff --git a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.tsindex f71b402457..8a2aa66076 100644--- a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts+++ b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts@@ -113,24 +113,29 @@ const projectId = "project-v4-transition";const orgId = "org-v4-transition";const secondProjectId = "project-v4-transition-second";+// Mocked Prisma delegates only implement the methods a test exercises, so+// accept any subset of PrismaClient keys with loosely typed values.+type MockPrismaClient = Partial<Record<keyof PrismaClient, unknown>>;+const createCaller = (- prisma?: Partial<PrismaClient>,+ prisma?: MockPrismaClient,callerSession: Session = session,) =>v4TransitionRouter.createCaller({...createInnerTRPCContext({ session: callerSession, headers: {} }),- ...(prisma ? { prisma: prisma as PrismaClient } : {}),+ ...(prisma ? { prisma: prisma as unknown as PrismaClient } : {}),});-type OrganizationRole = Session["user"]["organizations"][number]["role"];+type SessionUser = NonNullable<Session["user"]>;+type OrganizationRole = SessionUser["organizations"][number]["role"];type ProjectRole =- Session["user"]["organizations"][number]["projects"][number]["role"];+ SessionUser["organizations"][number]["projects"][number]["role"];const createSessionWithOrgRole = (role: OrganizationRole): Session => ({...session,user: {- ...session.user,- organizations: session.user.organizations.map((organization) => ({+ ...session.user!,+ organizations: session.user!.organizations.map((organization) => ({...organization,role,})),@@ -140,8 +145,8 @@ const createSessionWithOrgRole = (role: OrganizationRole): Session => ({const createSessionWithProjectRole = (role: ProjectRole): Session => ({...session,user: {- ...session.user,- organizations: session.user.organizations.map((organization) => ({+ ...session.user!,+ organizations: session.user!.organizations.map((organization) => ({...organization,projects: organization.projects.map((project) => ({...project,diff --git a/web/src/__tests__/server/validate-config-against-body.servertest.ts b/web/src/__tests__/server/validate-config-against-body.servertest.tsindex 2883576942..53db0742f3 100644--- a/web/src/__tests__/server/validate-config-against-body.servertest.ts+++ b/web/src/__tests__/server/validate-config-against-body.servertest.ts@@ -1,8 +1,5 @@-import {- validateConfigAgainstBody,- type ScoreConfigDomain,- type ScoreDomain,-} from "@langfuse/shared/src/server";+import { validateConfigAgainstBody } from "@langfuse/shared/src/server";+import { type ScoreConfigDomain, type ScoreDomain } from "@langfuse/shared";const baseTextConfig: ScoreConfigDomain = {id: "config-1",diff --git a/web/src/__tests__/server/verifiedDomainRouter.servertest.ts b/web/src/__tests__/server/verifiedDomainRouter.servertest.tsindex 5ddca17a30..4c490674bb 100644--- a/web/src/__tests__/server/verifiedDomainRouter.servertest.ts+++ b/web/src/__tests__/server/verifiedDomainRouter.servertest.ts@@ -69,6 +69,7 @@ function createSession(v4BetaToggleVisible: false,observationEvals: false,experimentsV4Enabled: false,+ searchBar: false,},admin: false,},diff --git a/web/src/__tests__/server/web-callouts-trpc.servertest.ts b/web/src/__tests__/server/web-callouts-trpc.servertest.tsindex e241af9129..ef8d45b5a1 100644--- a/web/src/__tests__/server/web-callouts-trpc.servertest.ts+++ b/web/src/__tests__/server/web-callouts-trpc.servertest.ts@@ -78,6 +78,8 @@ const buildSession = ({plan: "cloud:hobby",cloudConfig: undefined,metadata: {},+ aiFeaturesEnabled: false,+ aiTelemetryEnabled: false,projects: [{id: projectId,@@ -85,7 +87,9 @@ const buildSession = ({name: "Test Project",deletedAt: null,retentionDays: null,+ hasTraces: false,metadata: {},+ createdAt: new Date().toISOString(),},],},@@ -93,6 +97,10 @@ const buildSession = ({featureFlags: {templateFlag: true,excludeClickhouseRead: false,+ searchBar: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,},admin: false,v4BetaEnabled: false,diff --git a/web/src/__tests__/sse-dashboard-query.clienttest.ts b/web/src/__tests__/sse-dashboard-query.clienttest.tsindex aa10a14c14..9efabeb5b8 100644--- a/web/src/__tests__/sse-dashboard-query.clienttest.ts+++ b/web/src/__tests__/sse-dashboard-query.clienttest.ts@@ -318,7 +318,10 @@ describe("useSSEDashboardQuery", () => {expect(releaseSecondResponse).not.toBeNull();});- releaseSecondResponse?.();+ // TS control-flow analysis cannot see the assignment inside the mock's+ // closure and narrows the variable to `null`; widen it back to its+ // declared type.+ (releaseSecondResponse as (() => void) | null)?.();await waitFor(() => {expect(result.current.isError).toBe(true);diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.tsindex 7efca98938..5a1749e1ca 100644--- a/web/src/__tests__/test-utils.ts+++ b/web/src/__tests__/test-utils.ts@@ -179,7 +179,12 @@ export async function makeZodVerifiedAPICall<T extends z.ZodType>(auth?: string,statusCode = 200,): Promise<{ body: z.infer<T>; status: number }> {- const { body: resBody, status } = await makeAPICall(method, url, body, auth);+ const { body: resBody, status } = await makeAPICall<z.infer<T>>(+ method,+ url,+ body,+ auth,+ );if (status !== statusCode) {throw new Error(`API call did not return ${statusCode}, returned status ${status}, body ${JSON.stringify(resBody)}`,@@ -202,7 +207,12 @@ export async function makeZodVerifiedAPICallSilent<T extends z.ZodType>(body?: unknown,auth?: string,): Promise<{ body: z.infer<T>; status: number }> {- const { body: resBody, status } = await makeAPICall(method, url, body, auth);+ const { body: resBody, status } = await makeAPICall<z.infer<T>>(+ method,+ url,+ body,+ auth,+ );if (status === 200) {const typeCheckResult = responseZodSchema.safeParse(resBody);diff --git a/web/src/__tests__/transformScores.clienttest.ts b/web/src/__tests__/transformScores.clienttest.tsindex 5b982a6f11..7de167b801 100644--- a/web/src/__tests__/transformScores.clienttest.ts+++ b/web/src/__tests__/transformScores.clienttest.ts@@ -4,6 +4,7 @@ import {type ScoreAggregate,type ScoreConfigDomain,} from "@langfuse/shared";+import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";const mockConfigs: ScoreConfigDomain[] = [{@@ -34,7 +35,7 @@ const mockConfigs: ScoreConfigDomain[] = [describe("transformToAnnotationScores - flat scores", () => {it("should transform flat annotation scores correctly", () => {- const flatScores: ScoreDomain[] = [+ const flatScores: WithStringifiedMetadata<ScoreDomain>[] = [{id: "score-1",name: "quality",@@ -56,7 +57,8 @@ describe("transformToAnnotationScores - flat scores", () => {queueId: null,datasetRunId: null,executionTraceId: null,- metadata: {},+ metadata: null,+ longStringValue: "",},{id: "score-2",@@ -79,7 +81,8 @@ describe("transformToAnnotationScores - flat scores", () => {queueId: null,datasetRunId: null,executionTraceId: null,- metadata: {},+ metadata: null,+ longStringValue: "",},];@@ -117,7 +120,7 @@ describe("transformToAnnotationScores - flat scores", () => {});it("should filter out non-ANNOTATION scores", () => {- const flatScores: ScoreDomain[] = [+ const flatScores: WithStringifiedMetadata<ScoreDomain>[] = [{id: "score-1",name: "quality",@@ -139,7 +142,8 @@ describe("transformToAnnotationScores - flat scores", () => {queueId: null,datasetRunId: null,executionTraceId: null,- metadata: {},+ metadata: null,+ longStringValue: "",},{id: "score-2",@@ -162,7 +166,8 @@ describe("transformToAnnotationScores - flat scores", () => {queueId: null,datasetRunId: null,executionTraceId: null,- metadata: {},+ metadata: null,+ longStringValue: "",},];@@ -174,7 +179,7 @@ describe("transformToAnnotationScores - flat scores", () => {});it("should filter out scores without matching config", () => {- const flatScores: ScoreDomain[] = [+ const flatScores: WithStringifiedMetadata<ScoreDomain>[] = [{id: "score-1",name: "unknown",@@ -196,7 +201,8 @@ describe("transformToAnnotationScores - flat scores", () => {queueId: null,datasetRunId: null,executionTraceId: null,- metadata: {},+ metadata: null,+ longStringValue: "",},];diff --git a/web/src/features/search-bar/store/observedMetadataStore.clienttest.ts b/web/src/features/search-bar/store/observedMetadataStore.clienttest.tsindex dcc027df6f..a79155404b 100644--- a/web/src/features/search-bar/store/observedMetadataStore.clienttest.ts+++ b/web/src/features/search-bar/store/observedMetadataStore.clienttest.ts@@ -179,8 +179,8 @@ describe("mergeIntoProject", () => {// "mixed" forever (review find: greptile/claude on PR #14771). Built from// tuples, not an object literal: TS contextual typing breaks on literal// properties named after Object.prototype members (the values widen to- // `string` and fail assignability — broke the `next build` type pass,- // which unlike tsconfig.build.json includes clienttest files).+ // `string` and fail assignability — broke the `next build` type pass+ // before clienttest files were covered by the regular typecheck).const shadowing = new Map<string, StoredKeyInfo>([["toString", { type: "string", values: ["hello"] }],["constructor", { type: "number", values: ["1"] }],diff --git a/web/tsconfig.build.json b/web/tsconfig.build.jsondeleted file mode 100644index ba7a401832..0000000000--- a/web/tsconfig.build.json+++ /dev/null@@ -1,10 +0,0 @@-{- "extends": "./tsconfig.json",- "exclude": [- "node_modules",- "sdk",- "src/__tests__/**",- "**/*.clienttest.*",- "**/*.servertest.*"- ]-}diff --git a/web/tsconfig.json b/web/tsconfig.jsonindex 19e590a533..7fd438227b 100644--- a/web/tsconfig.json+++ b/web/tsconfig.json@@ -3,7 +3,6 @@"compilerOptions": {"declaration": false,"declarationMap": false,- "outDir": "dist","plugins": [{"name": "next"