Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
test(client): raise Jest branch coverage from ~80% to 96%+ (#1529)
Aman Agarwal07882efbde14
diff --git a/src/client/jest.setup.ts b/src/client/jest.setup.tsindex bb1c4815..d6f0b4dd 100644--- a/src/client/jest.setup.ts+++ b/src/client/jest.setup.ts@@ -7,3 +7,15 @@ if (typeof globalThis.structuredClone !== 'function') {globalThis.structuredClone = <T>(value: T): T =>JSON.parse(JSON.stringify(value)) as T;}++// jsdom's global scope does not include Node's TextEncoder/TextDecoder.+// The safe-fetch streaming helpers decode response bodies with them.+if (typeof globalThis.TextEncoder === 'undefined' || typeof globalThis.TextDecoder === 'undefined') {+ const { TextEncoder, TextDecoder } = require('node:util');+ if (typeof globalThis.TextEncoder === 'undefined') {+ globalThis.TextEncoder = TextEncoder;+ }+ if (typeof globalThis.TextDecoder === 'undefined') {+ globalThis.TextDecoder = TextDecoder as unknown as typeof globalThis.TextDecoder;+ }+}diff --git a/src/client/src/__tests__/helpers/client/connector-analytics.test.ts b/src/client/src/__tests__/helpers/client/connector-analytics.test.tsindex 34250d19..2024f01f 100644--- a/src/client/src/__tests__/helpers/client/connector-analytics.test.ts+++ b/src/client/src/__tests__/helpers/client/connector-analytics.test.ts@@ -6,10 +6,13 @@ jest.mock("@/lib/platform/connectors/memory/registry", () => ({getMemoryTypeDescriptor: jest.fn(() => undefined),}));+import { getSourceTypeDescriptor } from "@/lib/platform/connectors/datasource/registry";+import { getMemoryTypeDescriptor } from "@/lib/platform/connectors/memory/registry";import {BUILTIN_ROUTING_VALUE,classifySignalRoutingChange,connectorCreateEventProps,+ resolveConnectorDisplayName,signalRoutingChangedEventProps,} from "@/helpers/client/connector-analytics";@@ -59,4 +62,57 @@ describe("connector analytics helpers", () => {next_connector_name: "Jaeger",});});++ it("returns null for a blank or missing connector type", () => {+ expect(resolveConnectorDisplayName(null)).toBeNull();+ expect(resolveConnectorDisplayName(undefined)).toBeNull();+ expect(resolveConnectorDisplayName(" ")).toBeNull();+ });++ it("prefers a datasource registry display name over the static map", () => {+ (getSourceTypeDescriptor as jest.Mock).mockReturnValueOnce({+ displayName: "Custom Datasource",+ });+ expect(resolveConnectorDisplayName("clickhouse")).toBe(+ "Custom Datasource"+ );+ });++ it("falls back to a memory registry display name when no datasource matches", () => {+ (getMemoryTypeDescriptor as jest.Mock).mockReturnValueOnce({+ displayName: "Custom Memory",+ });+ expect(resolveConnectorDisplayName("mem0")).toBe("Custom Memory");+ });++ it("title-cases an unknown connector slug not present in the static map", () => {+ expect(resolveConnectorDisplayName("weaviate")).toBe("Weaviate");+ });++ it("defaults connector type to 'unknown' and environment to 'production' when omitted", () => {+ expect(connectorCreateEventProps({ type: "" })).toEqual({+ connector_type: "unknown",+ connector_name: "Unknown",+ environment: "production",+ });+ });++ it("defaults optional signal routing fields when omitted", () => {+ expect(+ signalRoutingChangedEventProps({+ signal: "logs",+ nextSourceId: "",+ })+ ).toEqual({+ signal: "logs",+ environment: "production",+ change: "cleared",+ previous_source_id: null,+ next_source_id: null,+ previous_connector_type: null,+ next_connector_type: null,+ previous_connector_name: null,+ next_connector_name: null,+ });+ });});diff --git a/src/client/src/__tests__/helpers/client/database-config.test.ts b/src/client/src/__tests__/helpers/client/database-config.test.tsindex a3cdd750..33cf3c64 100644--- a/src/client/src/__tests__/helpers/client/database-config.test.ts+++ b/src/client/src/__tests__/helpers/client/database-config.test.ts@@ -141,6 +141,35 @@ describe('changeActiveDatabaseConfig', () => {expect(toast.error).toHaveBeenCalled();expect(successCb).not.toHaveBeenCalled();});++ it('defaults to an empty list when the store has no existing list', async () => {+ (useRootStore.getState as jest.Mock).mockReturnValue({+ databaseConfig: {+ setIsLoading: mockSetIsLoading,+ setList: mockSetList,+ setPing: mockSetPing,+ list: undefined,+ },+ });+ (asaw as jest.Mock).mockResolvedValue([null, {}]);+ const successCb = jest.fn();++ await changeActiveDatabaseConfig('db1', successCb);++ expect(mockSetList).toHaveBeenCalledWith([]);+ });++ it('skips the success toast when called with silent: true', async () => {+ const list = [{ id: 'db1', isCurrent: false }];+ (useRootStore.getState as jest.Mock).mockReturnValue(makeGetState(list));+ (asaw as jest.Mock).mockResolvedValue([null, {}]);+ const successCb = jest.fn();++ await changeActiveDatabaseConfig('db1', successCb, { silent: true });++ expect(successCb).toHaveBeenCalled();+ expect(toast.success).not.toHaveBeenCalled();+ });});describe('deleteDatabaseConfig', () => {@@ -171,4 +200,20 @@ describe('deleteDatabaseConfig', () => {expect(toast.error).toHaveBeenCalled();expect(mockSetList).not.toHaveBeenCalled();});++ it('defaults to an empty list when the store has no existing list', async () => {+ (useRootStore.getState as jest.Mock).mockReturnValue({+ databaseConfig: {+ setIsLoading: mockSetIsLoading,+ setList: mockSetList,+ setPing: mockSetPing,+ list: undefined,+ },+ });+ (asaw as jest.Mock).mockResolvedValue([null, {}]);++ await deleteDatabaseConfig('db1');++ expect(mockSetList).toHaveBeenCalledWith([]);+ });});diff --git a/src/client/src/__tests__/helpers/client/evaluation-type.test.ts b/src/client/src/__tests__/helpers/client/evaluation-type.test.tsindex 9ef37afb..2026baef 100644--- a/src/client/src/__tests__/helpers/client/evaluation-type.test.ts+++ b/src/client/src/__tests__/helpers/client/evaluation-type.test.ts@@ -1,5 +1,6 @@import {displayEvaluationTypeName,+ getEvaluationStoredNameVariants,normalizeEvaluationStoredName,resolveEvaluationType,} from "@/helpers/client/evaluation-type";@@ -50,4 +51,63 @@ describe("evaluation-type resolve", () => {"Hallucination");});++ it("resolves a built-in type by its multi-word label when the id uses underscores", () => {+ expect(resolveEvaluationType("Instruction Following")).toEqual({+ id: "instruction_following",+ label: "Instruction Following",+ });+ });++ it("falls back to a formatted label when a custom type matched by id has no label", () => {+ const custom = [{ id: "no_label_type", label: "" }];+ expect(resolveEvaluationType("no_label_type", custom)).toEqual({+ id: "no_label_type",+ label: "No Label Type",+ });+ });++ it("matches a custom type by its compact label even when its label is empty", () => {+ const custom = [{ id: "weird", label: "" }];+ expect(resolveEvaluationType("___", custom)).toEqual({+ id: "weird",+ label: "Weird",+ });+ });++ it("resolves an empty stored value to an empty display name", () => {+ expect(resolveEvaluationType("")).toBeNull();+ expect(displayEvaluationTypeName("")).toBe("");+ });+});++describe("getEvaluationStoredNameVariants", () => {+ it("uses the provided label to build stored-name variants", () => {+ const variants = getEvaluationStoredNameVariants("custom_id", "Custom Label");+ expect(variants).toEqual([+ "custom_id",+ "Custom Label",+ "Custom Label evaluation context",+ "custom_id evaluation context",+ ]);+ });++ it("looks up the built-in label when none is provided", () => {+ const variants = getEvaluationStoredNameVariants("hallucination");+ expect(variants).toEqual(+ expect.arrayContaining([+ "hallucination",+ "Hallucination",+ "Hallucination evaluation context",+ ])+ );+ });++ it("falls back to the id when no label is provided and no built-in type matches", () => {+ const variants = getEvaluationStoredNameVariants("custom_unmatched_id");+ expect(variants).toEqual([+ "custom_unmatched_id",+ "custom_unmatched_id evaluation context",+ ]);+ });});diff --git a/src/client/src/__tests__/helpers/server/sdk-intelligence.test.ts b/src/client/src/__tests__/helpers/server/sdk-intelligence.test.tsindex 94c74fa4..9c4ce051 100644--- a/src/client/src/__tests__/helpers/server/sdk-intelligence.test.ts+++ b/src/client/src/__tests__/helpers/server/sdk-intelligence.test.ts@@ -90,6 +90,24 @@ describe("resolveSdkIntelligenceDatabaseConfig", () => {expect(resolveSignalSource).not.toHaveBeenCalled();});+ it("short-circuits when the explicit database-config header matches the key's own binding", async () => {+ await expect(+ resolveSdkIntelligenceDatabaseConfig(+ makeRequest({+ [OPENLIT_CONTEXT_HEADERS.databaseConfigId]: "db-key",+ }),+ "openlit-test"+ )+ ).resolves.toEqual([+ null,+ expect.objectContaining({+ databaseConfigId: "db-key",+ via: "databaseConfigHeader",+ }),+ ]);+ expect(getDBConfigByIdInternal).not.toHaveBeenCalled();+ });+it("falls back to the API key bound database config for existing SDKs", async () => {await expect(resolveSdkIntelligenceDatabaseConfig(makeRequest(), "openlit-test")@@ -101,4 +119,178 @@ describe("resolveSdkIntelligenceDatabaseConfig", () => {}),]);});++ it("prefers the middleware-injected database-config header over the key binding for the apiKey path", async () => {+ await expect(+ resolveSdkIntelligenceDatabaseConfig(+ makeRequest({ "x-database-config-id": "db-middleware" }),+ "openlit-test"+ )+ ).resolves.toEqual([+ null,+ expect.objectContaining({+ databaseConfigId: "db-middleware",+ via: "apiKey",+ }),+ ]);+ });++ it("returns NO_API_KEY when the trimmed apiKey is empty", async () => {+ await expect(+ resolveSdkIntelligenceDatabaseConfig(makeRequest(), " ")+ ).resolves.toEqual(["No API key", null]);+ expect(getAPIKeyInfo).not.toHaveBeenCalled();+ });++ it("returns NO_API_KEY when getAPIKeyInfo errors", async () => {+ (getAPIKeyInfo as jest.Mock).mockResolvedValue(["boom", null]);++ await expect(+ resolveSdkIntelligenceDatabaseConfig(makeRequest(), "openlit-test")+ ).resolves.toEqual(["No API key", null]);+ });++ it("returns NO_API_KEY when the API key has no bound database config", async () => {+ (getAPIKeyInfo as jest.Mock).mockResolvedValue([+ null,+ { id: "key-1", createdByUserId: "u1" },+ ]);++ await expect(+ resolveSdkIntelligenceDatabaseConfig(makeRequest(), "openlit-test")+ ).resolves.toEqual(["No API key", null]);+ });++ it("infers the project id from the key's database config when the project header is absent", async () => {+ (getDBConfigByIdInternal as jest.Mock).mockResolvedValue({+ id: "db-key",+ projectId: "proj-inferred",+ });+ (resolveSignalSource as jest.Mock).mockResolvedValue({+ hasSource: true,+ descriptor: {+ type: "clickhouse",+ dbConfigId: "db-intelligence",+ },+ });++ await expect(+ resolveSdkIntelligenceDatabaseConfig(+ makeRequest({ [OPENLIT_CONTEXT_HEADERS.environment]: "staging" }),+ "openlit-test"+ )+ ).resolves.toEqual([+ null,+ expect.objectContaining({+ databaseConfigId: "db-intelligence",+ via: "signalRouting",+ }),+ ]);+ expect(getDBConfigByIdInternal).toHaveBeenCalledWith({ id: "db-key" });+ expect(resolveSignalSource).toHaveBeenCalledWith(+ "intelligence",+ expect.objectContaining({ projectId: "proj-inferred" })+ );+ });++ it("returns an error when the environment has no resolvable project id", async () => {+ (getDBConfigByIdInternal as jest.Mock).mockResolvedValue(null);++ await expect(+ resolveSdkIntelligenceDatabaseConfig(+ makeRequest({ [OPENLIT_CONTEXT_HEADERS.environment]: "staging" }),+ "openlit-test"+ )+ ).resolves.toEqual([+ null,+ expect.objectContaining({+ databaseConfigId: "db-key",+ via: "apiKey",+ }),+ ]);+ });++ it("returns an error when intelligence ClickHouse is not configured for the project environment", async () => {+ (getDBConfigByIdInternal as jest.Mock).mockResolvedValue({+ id: "db-key",+ projectId: "proj-1",+ });+ (resolveSignalSource as jest.Mock).mockResolvedValue({+ hasSource: false,+ descriptor: { type: "clickhouse", dbConfigId: "db-intelligence" },+ });++ await expect(+ resolveSdkIntelligenceDatabaseConfig(+ makeRequest({+ [OPENLIT_CONTEXT_HEADERS.environment]: "staging",+ [OPENLIT_CONTEXT_HEADERS.projectId]: "proj-1",+ }),+ "openlit-test"+ )+ ).resolves.toEqual([+ "Intelligence ClickHouse is not configured for the selected project environment.",+ null,+ ]);+ });++ it("returns an error when the resolved signal source descriptor is not clickhouse", async () => {+ (getDBConfigByIdInternal as jest.Mock).mockResolvedValue({+ id: "db-key",+ projectId: "proj-1",+ });+ (resolveSignalSource as jest.Mock).mockResolvedValue({+ hasSource: true,+ descriptor: { type: "tempo", dbConfigId: undefined },+ });++ await expect(+ resolveSdkIntelligenceDatabaseConfig(+ makeRequest({+ [OPENLIT_CONTEXT_HEADERS.environment]: "staging",+ [OPENLIT_CONTEXT_HEADERS.projectId]: "proj-1",+ }),+ "openlit-test"+ )+ ).resolves.toEqual([+ "Intelligence ClickHouse is not configured for the selected project environment.",+ null,+ ]);+ });++ it("rejects an explicit database-config header when the requested project does not match the key's project", async () => {+ (getDBConfigByIdInternal as jest.Mock)+ .mockResolvedValueOnce({ id: "db-key", projectId: "proj-1" })+ .mockResolvedValueOnce({ id: "db-other", projectId: "proj-2" });++ await expect(+ resolveSdkIntelligenceDatabaseConfig(+ makeRequest({+ [OPENLIT_CONTEXT_HEADERS.databaseConfigId]: "db-other",+ }),+ "openlit-test"+ )+ ).resolves.toEqual([+ "The selected database configuration is not available for this API key.",+ null,+ ]);+ });++ it("rejects an explicit database-config header when either database config lookup is missing a project id", async () => {+ (getDBConfigByIdInternal as jest.Mock)+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({ id: "db-other", projectId: "proj-1" });++ await expect(+ resolveSdkIntelligenceDatabaseConfig(+ makeRequest({+ [OPENLIT_CONTEXT_HEADERS.databaseConfigId]: "db-other",+ }),+ "openlit-test"+ )+ ).resolves.toEqual([+ "The selected database configuration is not available for this API key.",+ null,+ ]);+ });});diff --git a/src/client/src/__tests__/helpers/server/trace.test.ts b/src/client/src/__tests__/helpers/server/trace.test.tsindex bcfa70da..cc5a2c9e 100644--- a/src/client/src/__tests__/helpers/server/trace.test.ts+++ b/src/client/src/__tests__/helpers/server/trace.test.ts@@ -89,4 +89,27 @@ describe('buildHierarchy', () => {expect(result.SpanId).toBe('root');expect(result.children).toHaveLength(1);});++ it('returns null when every item is missing a SpanId', () => {+ const data = [{ ParentSpanId: '' }, { ParentSpanId: 'root' }];+ expect(buildHierarchy(data)).toBeNull();+ });++ it('skips items missing a SpanId while still building the hierarchy for valid items', () => {+ const data = [+ { SpanId: 'root', ParentSpanId: '' },+ { ParentSpanId: 'root' },+ ];+ const result = buildHierarchy(data) as any;+ expect(result.SpanId).toBe('root');+ expect(result.children).toHaveLength(0);+ });++ it('returns null when every span forms a cycle with no root or orphan top', () => {+ const data = [+ { SpanId: 'a', ParentSpanId: 'b' },+ { SpanId: 'b', ParentSpanId: 'a' },+ ];+ expect(buildHierarchy(data)).toBeNull();+ });});diff --git a/src/client/src/__tests__/lib/access/connector-route.test.ts b/src/client/src/__tests__/lib/access/connector-route.test.tsnew file mode 100644index 00000000..a4c5324d--- /dev/null+++ b/src/client/src/__tests__/lib/access/connector-route.test.ts@@ -0,0 +1,40 @@+import { withConnectorAccess, withConnectorAudit } from "@/lib/access/connector-route";++describe("CE connector route fallback", () => {+ it("withConnectorAccess returns the handler unchanged regardless of action", () => {+ const handler = jest.fn().mockResolvedValue({ status: 204 });++ const wrapped = withConnectorAccess("read", handler);++ expect(wrapped).toBe(handler);+ });++ it("withConnectorAccess is a pass-through identity wrapper for any action", () => {+ const handler = { name: "sample-handler" };++ expect(withConnectorAccess("create", handler)).toBe(handler);+ expect(withConnectorAccess("update", handler)).toBe(handler);+ expect(withConnectorAccess("delete", handler)).toBe(handler);+ expect(withConnectorAccess("test", handler)).toBe(handler);+ expect(withConnectorAccess("bind", handler)).toBe(handler);+ });++ it("withConnectorAudit returns the handler unchanged", () => {+ const handler = jest.fn();++ const wrapped = withConnectorAudit(handler);++ expect(wrapped).toBe(handler);+ });++ it("wrapped handlers behave exactly like the original", async () => {+ const handler = jest.fn().mockResolvedValue("ok");++ const accessWrapped = withConnectorAccess("read", handler);+ const auditWrapped = withConnectorAudit(handler);++ await expect(accessWrapped()).resolves.toBe("ok");+ await expect(auditWrapped()).resolves.toBe("ok");+ expect(handler).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/client/src/__tests__/lib/db-config.test.ts b/src/client/src/__tests__/lib/db-config.test.tsindex 42d83015..982f1a64 100644--- a/src/client/src/__tests__/lib/db-config.test.ts+++ b/src/client/src/__tests__/lib/db-config.test.ts@@ -33,6 +33,13 @@ jest.mock('@/lib/prisma', () => ({upsert: jest.fn(),deleteMany: jest.fn(),},+ telemetrySourceBinding: {+ findUnique: jest.fn(),+ create: jest.fn(),+ },+ projectEnvironment: {+ upsert: jest.fn(),+ },},}));jest.mock('@/lib/session', () => ({@@ -74,6 +81,7 @@ import {getDBConfigByIdInternal,getDBConfigByIdForUser,getDBConfigByIdForBackground,+ getFirstDBConfig,upsertDBConfig,deleteDBConfig,setCurrentDBConfig,@@ -114,6 +122,9 @@ beforeEach(() => {(prisma.databaseConfigUser.count as jest.Mock).mockResolvedValue(0);(prisma.connectorInstance.upsert as jest.Mock).mockResolvedValue({});(prisma.connectorInstance.deleteMany as jest.Mock).mockResolvedValue({ count: 1 });+ (prisma.telemetrySourceBinding.findUnique as jest.Mock).mockResolvedValue(null);+ (prisma.telemetrySourceBinding.create as jest.Mock).mockResolvedValue({});+ (prisma.projectEnvironment.upsert as jest.Mock).mockResolvedValue({});});describe('getDBConfigByUser', () => {@@ -250,6 +261,23 @@ describe('getDBConfigByIdForUser', () => {expect(prisma.databaseConfigUser.findFirst).not.toHaveBeenCalled();});+ it('scopes to orphaned (null-project) configs when there is no current organisation', async () => {+ (getCurrentOrganisation as jest.Mock).mockResolvedValue(null);+ (prisma.databaseConfigUser.findFirst as jest.Mock).mockResolvedValue({+ databaseConfig: mockDbConfig,+ });++ const result = await getDBConfigByIdForUser({ id: 'db1', userId: 'u1' });++ expect(result).toEqual(mockDbConfig);+ expect(getCurrentProjectForOrganisation).not.toHaveBeenCalled();+ expect(prisma.databaseConfigUser.findFirst).toHaveBeenCalledWith(+ expect.objectContaining({+ where: expect.objectContaining({ databaseConfig: { projectId: null } }),+ })+ );+ });+it('filters explicit db config access by user and current project', async () => {(prisma.databaseConfigUser.findFirst as jest.Mock).mockResolvedValue({databaseConfig: mockDbConfig,@@ -270,6 +298,23 @@ describe('getDBConfigByIdForUser', () => {});});+describe('getFirstDBConfig', () => {+ it('returns the earliest-created database config', async () => {+ (prisma.databaseConfig.findFirst as jest.Mock).mockResolvedValue(mockDbConfig);+ const result = await getFirstDBConfig();+ expect(result).toEqual(mockDbConfig);+ expect(prisma.databaseConfig.findFirst).toHaveBeenCalledWith(+ expect.objectContaining({ orderBy: { createdAt: 'asc' } })+ );+ });++ it('returns null when no configs exist', async () => {+ (prisma.databaseConfig.findFirst as jest.Mock).mockResolvedValue(null);+ const result = await getFirstDBConfig();+ expect(result).toBeNull();+ });+});+describe('upsertDBConfig', () => {const validConfig = {name: 'My DB',@@ -319,6 +364,21 @@ describe('upsertDBConfig', () => {await expect(upsertDBConfig(validConfig)).rejects.toThrow('DB config Name already exists');});+ it('throws when the host fails SSRF validation', async () => {+ await expect(+ upsertDBConfig({ ...validConfig, host: 'http://evil.example.com' })+ ).rejects.toThrow('Host must not contain a URL scheme');+ });++ it('coerces a numeric port to a string before persisting', async () => {+ (asaw as jest.Mock).mockResolvedValueOnce([null, { id: 'new-db', projectId: 'project1' }]);+ (prisma.databaseConfig.findUnique as jest.Mock).mockResolvedValue({ projectId: 'project1' });+ (prisma.databaseConfigUser.create as jest.Mock).mockResolvedValue({});++ const result = await upsertDBConfig({ ...validConfig, port: 8123 as any });+ expect(result).toBe('Added db details successfully');+ });+it('creates new config with project (project upsert path)', async () => {(asaw as jest.Mock).mockResolvedValueOnce([null, { id: 'new-db', projectId: 'project1' }]);(prisma.databaseConfig.findUnique as jest.Mock).mockResolvedValue({ projectId: 'project1' });@@ -373,6 +433,42 @@ describe('upsertDBConfig', () => {await expect(upsertDBConfig(validConfig)).rejects.toThrow('DB error');});+ it('does not fail the save when environment binding projection throws', async () => {+ (asaw as jest.Mock).mockResolvedValueOnce([null, { id: 'new-db', projectId: 'project1' }]);+ (prisma.databaseConfig.findUnique as jest.Mock).mockResolvedValue({ projectId: 'project1' });+ (prisma.databaseConfigUser.create as jest.Mock).mockResolvedValue({});+ (prisma.telemetrySourceBinding.findUnique as jest.Mock).mockRejectedValue(+ new Error('binding table missing')+ );+ const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});++ const result = await upsertDBConfig(validConfig);+ expect(result).toBe('Added db details successfully');+ expect(consoleErrorSpy).toHaveBeenCalledWith(+ '[connectors] ClickHouse signal binding projection failed',+ expect.objectContaining({ databaseConfigId: 'new-db' })+ );+ consoleErrorSpy.mockRestore();+ });++ it('does not fail the save when connector projection throws', async () => {+ (asaw as jest.Mock).mockResolvedValueOnce([null, { id: 'new-db', projectId: 'project1' }]);+ (prisma.databaseConfig.findUnique as jest.Mock).mockResolvedValue({ projectId: 'project1' });+ (prisma.databaseConfigUser.create as jest.Mock).mockResolvedValue({});+ (prisma.connectorInstance.upsert as jest.Mock).mockRejectedValue(+ new Error('connector table missing')+ );+ const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});++ const result = await upsertDBConfig(validConfig);+ expect(result).toBe('Added db details successfully');+ expect(consoleErrorSpy).toHaveBeenCalledWith(+ '[connectors] ClickHouse connector projection failed',+ expect.objectContaining({ databaseConfigId: 'new-db' })+ );+ consoleErrorSpy.mockRestore();+ });+it('throws when user lacks edit permission (covers line 509 in checkPermissionForDbAction)', async () => {// checkPermissionForDbAction(userId, id, "EDIT") internally calls asaw(prisma.findFirst)// mock that inner asaw to return a config with canEdit=false@@ -449,6 +545,20 @@ describe('setCurrentDBConfig', () => {await expect(setCurrentDBConfig('db1')).rejects.toThrow('Unauthorized');});+ it('scopes to orphaned configs when there is no current organisation', async () => {+ (getCurrentOrganisation as jest.Mock).mockResolvedValue(null);+ (prisma.databaseConfig.findFirst as jest.Mock).mockResolvedValue({ id: 'new-db' });+ (prisma.databaseConfigUser.findFirst as jest.Mock).mockResolvedValue(null);+ (prisma.databaseConfigUser.update as jest.Mock).mockResolvedValue({});++ const result = await setCurrentDBConfig('new-db');+ expect(result).toBe('Current DB config set successfully!');+ expect(getCurrentProjectForOrganisation).not.toHaveBeenCalled();+ expect(prisma.databaseConfig.findFirst).toHaveBeenCalledWith(+ expect.objectContaining({ where: { id: 'new-db', projectId: null } })+ );+ });+it('rejects configs outside the current project', async () => {(prisma.databaseConfig.findFirst as jest.Mock).mockResolvedValue(null);diff --git a/src/client/src/__tests__/lib/organisation.test.ts b/src/client/src/__tests__/lib/organisation.test.tsindex d76a9906..963e681e 100644--- a/src/client/src/__tests__/lib/organisation.test.ts+++ b/src/client/src/__tests__/lib/organisation.test.ts@@ -10,10 +10,12 @@ jest.mock('@/lib/prisma', () => ({project: {findFirst: jest.fn(),findUnique: jest.fn(),+ findMany: jest.fn(),create: jest.fn(),},projectUser: {create: jest.fn(),+ upsert: jest.fn(),},organisationUser: {findFirst: jest.fn(),@@ -65,6 +67,7 @@ jest.mock('@/constants/messages', () => ({ONLY_ADMIN_CAN_UPDATE_ORGANISATION: 'Only admin can update',ORGANISATION_NOTHING_TO_UPDATE: 'Nothing to update',PROJECT_NAME_LENGTH_RANGE_ERROR: 'Project name must be between 1 and 120 characters',+ PROJECT_NOT_FOUND: 'Project not found',EMAIL_REQUIRED: 'Email cannot be empty',INVALID_EMAIL_FORMAT: 'Invalid email format',ONLY_ADMIN_CAN_INVITE: 'Only admin can invite',@@ -88,6 +91,9 @@ jest.mock('@/utils/error', () => ({if (condition) throw new Error(msg);}),}));+jest.mock('@/features/organisation-access', () => ({+ canManageOrganisation: jest.fn(),+}));import {createOrganisation,@@ -107,11 +113,16 @@ import {getOrganisationPendingInvites,cancelInvitation,getOrganisationById,+ getDefaultProjectForOrganisation,+ getCurrentProjectForOrganisation,+ setCurrentProject,+ createOrganisationProject,} from '@/lib/organisation';import prisma from '@/lib/prisma';import { getCurrentUser } from '@/lib/session';import { throwIfError } from '@/utils/error';import getMessage from '@/constants/messages';+import { canManageOrganisation } from '@/features/organisation-access';const mockUser = { id: 'u1', email: '[email protected]' };const mockProject = {@@ -147,6 +158,7 @@ beforeEach(() => {ONLY_ADMIN_CAN_UPDATE_ORGANISATION: 'Only admin can update',ORGANISATION_NOTHING_TO_UPDATE: 'Nothing to update',PROJECT_NAME_LENGTH_RANGE_ERROR: 'Project name must be between 1 and 120 characters',+ PROJECT_NOT_FOUND: 'Project not found',EMAIL_REQUIRED: 'Email cannot be empty',INVALID_EMAIL_FORMAT: 'Invalid email format',ONLY_ADMIN_CAN_INVITE: 'Only admin can invite',@@ -170,6 +182,8 @@ beforeEach(() => {(prisma.project.findFirst as jest.Mock).mockResolvedValue(mockProject);(prisma.project.findUnique as jest.Mock).mockResolvedValue(mockProject);(prisma.project.create as jest.Mock).mockResolvedValue(mockProject);+ (prisma.projectUser.upsert as jest.Mock).mockResolvedValue({});+ (prisma.project.findMany as jest.Mock).mockResolvedValue([mockProject]);(prisma.$queryRaw as jest.Mock).mockResolvedValue([{ current_project_id: 'project1' }]);(prisma.$executeRaw as jest.Mock).mockResolvedValue(1);// Default: findUnique on organisationUser returns null (not a member by default)@@ -188,6 +202,8 @@ beforeEach(() => {// Default: invited user operations return null/[](prisma.organisationInvitedUser.findUnique as jest.Mock).mockResolvedValue(null);(prisma.organisationInvitedUser.findMany as jest.Mock).mockResolvedValue([]);+ // Default: no enterprise extension override (undefined -> fall back to role-based check)+ (canManageOrganisation as jest.Mock).mockResolvedValue(undefined);});describe('createOrganisation', () => {@@ -369,11 +385,26 @@ describe('updateOrganisation', () => {);});+ it('throws when user has no membership at all', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue(null);+ await expect(updateOrganisation('org1', { name: 'New Name' })).rejects.toThrow(+ 'Only admin can update'+ );+ });+it('throws when nothing to update', async () => {(prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ role: 'owner' });await expect(updateOrganisation('org1', {})).rejects.toThrow('Nothing to update');});+ it('allows admin role to update organisation name', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ role: 'admin' });+ (prisma.organisation.update as jest.Mock).mockResolvedValue({ id: 'org1', name: 'New Name' });++ const result = await updateOrganisation('org1', { name: 'New Name' });+ expect(result).toEqual({ id: 'org1', name: 'New Name' });+ });+it('updates organisation name', async () => {(prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ role: 'owner' });(prisma.organisation.update as jest.Mock).mockResolvedValue({@@ -978,3 +1009,357 @@ describe('getOrganisationById', () => {expect(result!.memberCount).toBe(2);});});++describe('getDefaultProjectForOrganisation', () => {+ it('returns existing default project when found', async () => {+ (prisma.project.findFirst as jest.Mock).mockResolvedValue(mockProject);+ const result = await getDefaultProjectForOrganisation('org1');+ expect(result).toEqual(mockProject);+ expect(prisma.project.create).not.toHaveBeenCalled();+ });++ it('creates a default project when none exists', async () => {+ (prisma.project.findFirst as jest.Mock).mockResolvedValue(null);+ (prisma.project.create as jest.Mock).mockResolvedValue(mockProject);++ const result = await getDefaultProjectForOrganisation('org1');+ expect(result).toEqual(mockProject);+ expect(prisma.project.create).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ organisationId: 'org1',+ name: 'Default Project',+ slug: 'default',+ isDefault: true,+ }),+ })+ );+ });+});++describe('getCurrentProjectForOrganisation', () => {+ it('throws when user is not authenticated', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue(null);+ await expect(getCurrentProjectForOrganisation('org1')).rejects.toThrow('Unauthorized');+ });++ it('throws when user is not a member', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue(null);+ await expect(getCurrentProjectForOrganisation('org1')).rejects.toThrow('Not a member');+ });++ it('returns the current project when set and valid', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ id: 'ou1' });+ (prisma.$queryRaw as jest.Mock).mockResolvedValue([{ current_project_id: 'project1' }]);+ (prisma.project.findFirst as jest.Mock).mockResolvedValue(mockProject);++ const result = await getCurrentProjectForOrganisation('org1');+ expect(result).toEqual(mockProject);+ });++ it('falls back to default project when current project id points to a missing/foreign project', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ id: 'ou1' });+ (prisma.$queryRaw as jest.Mock).mockResolvedValue([{ current_project_id: 'stale-project' }]);+ // First findFirst call (lookup by id+org) misses, second (getDefaultProjectForOrganisation) hits+ (prisma.project.findFirst as jest.Mock)+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce(mockProject);+ (prisma.$executeRaw as jest.Mock).mockResolvedValue(1);++ const result = await getCurrentProjectForOrganisation('org1');+ expect(result).toEqual(mockProject);+ expect(prisma.$executeRaw).toHaveBeenCalled();+ });++ it('falls back to default project when no current project id is set', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ id: 'ou1' });+ (prisma.$queryRaw as jest.Mock).mockResolvedValue([{ current_project_id: null }]);+ (prisma.project.findFirst as jest.Mock).mockResolvedValue(mockProject);++ const result = await getCurrentProjectForOrganisation('org1');+ expect(result).toEqual(mockProject);+ expect(prisma.$executeRaw).toHaveBeenCalled();+ });+});++describe('setCurrentProject', () => {+ it('throws when user is not authenticated', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue(null);+ await expect(setCurrentProject('org1', 'project1')).rejects.toThrow('Unauthorized');+ });++ it('throws when user is not a member', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue(null);+ await expect(setCurrentProject('org1', 'project1')).rejects.toThrow('Not a member');+ });++ it('throws when project does not exist', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ id: 'ou1' });+ (prisma.project.findUnique as jest.Mock).mockResolvedValue(null);+ await expect(setCurrentProject('org1', 'missing')).rejects.toThrow('Project not found');+ });++ it('throws when project belongs to a different organisation', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ id: 'ou1' });+ (prisma.project.findUnique as jest.Mock).mockResolvedValue({+ id: 'project1',+ organisationId: 'other-org',+ });+ await expect(setCurrentProject('org1', 'project1')).rejects.toThrow('Project not found');+ });++ it('sets the current project successfully', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ id: 'ou1' });+ (prisma.project.findUnique as jest.Mock).mockResolvedValue(mockProject);++ const result = await setCurrentProject('org1', 'project1');+ expect(result).toEqual({ success: true });+ expect(prisma.$executeRaw).toHaveBeenCalled();+ });+});++describe('createOrganisationProject', () => {+ it('throws when user is not authenticated', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue(null);+ await expect(createOrganisationProject('org1', 'My Project')).rejects.toThrow('Unauthorized');+ });++ it('throws when name is empty after trimming', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ role: 'owner' });+ await expect(createOrganisationProject('org1', ' ')).rejects.toThrow(+ 'Project name must be between 1 and 120 characters'+ );+ });++ it('throws when name exceeds 120 characters', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ role: 'owner' });+ await expect(+ createOrganisationProject('org1', 'a'.repeat(121))+ ).rejects.toThrow('Project name must be between 1 and 120 characters');+ });++ it('throws when user is not admin/owner', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ role: 'member' });+ await expect(createOrganisationProject('org1', 'My Project')).rejects.toThrow(+ 'Only admin can update'+ );+ });++ it('creates a project and assigns all org members to it', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ role: 'owner' });+ (prisma.project.findUnique as jest.Mock).mockResolvedValue(null); // slug is unique+ (prisma.project.create as jest.Mock).mockResolvedValue({+ id: 'project2',+ organisationId: 'org1',+ name: 'My Project',+ slug: 'my-project-abc123',+ });+ (prisma.organisationUser.findMany as jest.Mock).mockResolvedValue([+ { id: 'ou1', userId: 'u1' },+ ]);+ (prisma.projectUser.create as jest.Mock).mockResolvedValue({});++ const result = await createOrganisationProject('org1', 'My Project');+ expect(result).toEqual(+ expect.objectContaining({ id: 'project2', name: 'My Project' })+ );+ expect(prisma.projectUser.upsert).toHaveBeenCalledWith(+ expect.objectContaining({+ create: expect.objectContaining({ projectId: 'project2', userId: 'u1' }),+ })+ );+ });++ it('falls back to "project" base slug when name has no alphanumeric characters', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ role: 'owner' });+ (prisma.project.findUnique as jest.Mock).mockResolvedValue(null);+ (prisma.project.create as jest.Mock).mockResolvedValue({+ id: 'project3',+ organisationId: 'org1',+ name: '!!!',+ slug: 'project-abc123',+ });+ (prisma.organisationUser.findMany as jest.Mock).mockResolvedValue([]);++ await createOrganisationProject('org1', '!!!');+ expect(prisma.project.create).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ slug: expect.stringMatching(/^project-/),+ }),+ })+ );+ });++ it('throws when slug generation exhausts retries', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ role: 'owner' });+ (prisma.project.findUnique as jest.Mock).mockResolvedValue({ id: 'existing' }); // always collides+ await expect(createOrganisationProject('org1', 'My Project')).rejects.toThrow(+ 'Unable to generate a unique project slug'+ );+ });+});++describe('removeUserFromOrganisation with enterprise extension hook', () => {+ it('honors a true extension decision even if current user is only a member', async () => {+ (prisma.organisation.findUnique as jest.Mock).mockResolvedValue({+ id: 'org1',+ createdByUserId: 'owner-id',+ });+ (prisma.organisationUser.findUnique as jest.Mock)+ .mockResolvedValueOnce({ role: 'member' }) // currentUserRole+ .mockResolvedValueOnce({ role: 'member' }) // targetUserRole+ .mockResolvedValueOnce({ isCurrent: false }); // membership check at end+ (canManageOrganisation as jest.Mock).mockResolvedValue(true);+ (prisma.databaseConfigUser.deleteMany as jest.Mock).mockResolvedValue({});+ (prisma.organisationUser.delete as jest.Mock).mockResolvedValue({});++ const result = await removeUserFromOrganisation('org1', 'u2');+ expect(result).toEqual({ success: true });+ });++ it('honors a false extension decision even if current user is admin', async () => {+ (prisma.organisation.findUnique as jest.Mock).mockResolvedValue({+ id: 'org1',+ createdByUserId: 'owner-id',+ });+ (prisma.organisationUser.findUnique as jest.Mock)+ .mockResolvedValueOnce({ role: 'admin' }) // currentUserRole+ .mockResolvedValueOnce({ role: 'member' }); // targetUserRole+ (canManageOrganisation as jest.Mock).mockResolvedValue(false);++ await expect(removeUserFromOrganisation('org1', 'u2')).rejects.toThrow(+ 'Only admin can remove'+ );+ });+});++describe('updateMemberRole with enterprise extension hook', () => {+ it('honors a true extension decision even if current user is only a member', async () => {+ (prisma.organisation.findUnique as jest.Mock).mockResolvedValue(mockOrg);+ (prisma.organisationUser.findUnique as jest.Mock)+ .mockResolvedValueOnce({ role: 'member' }) // currentUserRole+ .mockResolvedValueOnce({ role: 'member' }); // targetUserRole+ (canManageOrganisation as jest.Mock).mockResolvedValue(true);+ (prisma.organisationUser.update as jest.Mock).mockResolvedValue({});++ const result = await updateMemberRole('org1', 'u2', 'admin');+ expect(result).toEqual({ success: true });+ });++ it('honors a false extension decision even if current user is owner', async () => {+ (prisma.organisation.findUnique as jest.Mock).mockResolvedValue(mockOrg);+ (prisma.organisationUser.findUnique as jest.Mock)+ .mockResolvedValueOnce({ role: 'owner' }) // currentUserRole+ .mockResolvedValueOnce({ role: 'member' }); // targetUserRole+ (canManageOrganisation as jest.Mock).mockResolvedValue(false);++ await expect(updateMemberRole('org1', 'u2', 'admin')).rejects.toThrow(+ 'Only admin/owner can update'+ );+ });+});++describe('hasAdminOrOwnerRole extension hook (via updateOrganisation)', () => {+ it('honors a true extension decision even when user has no membership', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue(null);+ (canManageOrganisation as jest.Mock).mockResolvedValue(true);+ (prisma.organisation.update as jest.Mock).mockResolvedValue({ id: 'org1', name: 'New Name' });++ const result = await updateOrganisation('org1', { name: 'New Name' });+ expect(result).toEqual({ id: 'org1', name: 'New Name' });+ });+});++describe('setCurrentOrganisation project id fallback', () => {+ it('falls back to the default project id when membership has no current project id', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ id: 'ou1' });+ (prisma.$queryRaw as jest.Mock).mockResolvedValue([{ current_project_id: null }]);+ (prisma.project.findFirst as jest.Mock).mockResolvedValue(mockProject);+ (prisma.$transaction as jest.Mock).mockResolvedValue([{}, {}]);++ const result = await setCurrentOrganisation('org1');+ expect(result).toEqual({ success: true });+ expect(prisma.$executeRaw).toHaveBeenCalled();+ });+});++describe('getOrganisationMembers role mapping', () => {+ it('reports actual role for non-creator members', async () => {+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValue({ id: 'ou1' });+ (prisma.organisationUser.findMany as jest.Mock).mockResolvedValue([+ {+ user: { id: 'u2', email: '[email protected]', name: 'Member', image: null },+ role: 'member',+ createdAt: new Date(),+ },+ ]);+ (prisma.organisation.findUnique as jest.Mock).mockResolvedValue({+ id: 'org1',+ createdByUserId: 'u1',+ });++ const result = await getOrganisationMembers('org1');+ expect(result[0].isCreator).toBe(false);+ expect(result[0].role).toBe('member');+ });+});++describe('assignUserToAllOrganisationProjects (via acceptInvitation)', () => {+ it('adds user to all projects and sets current project when none is set', async () => {+ (prisma.organisationInvitedUser.findUnique as jest.Mock).mockResolvedValue({+ id: 'inv-assign-1',+ email: '[email protected]',+ organisationId: 'org1',+ });+ (prisma.organisationUser.create as jest.Mock).mockResolvedValue({});+ (prisma.organisationInvitedUser.delete as jest.Mock).mockResolvedValue({});+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValueOnce({ id: 'ou-membership' });+ (prisma.project.findMany as jest.Mock).mockResolvedValue([{ id: 'p1' }, { id: 'p2' }]);+ (prisma.$queryRaw as jest.Mock).mockResolvedValueOnce([{ current_project_id: null }]);++ const result = await acceptInvitation('inv-assign-1');+ expect(result).toEqual({ success: true });+ expect(prisma.projectUser.upsert).toHaveBeenCalledTimes(2);+ expect(prisma.$executeRaw).toHaveBeenCalled();+ });++ it('skips setting current project when organisation has no projects yet', async () => {+ (prisma.organisationInvitedUser.findUnique as jest.Mock).mockResolvedValue({+ id: 'inv-assign-2',+ email: '[email protected]',+ organisationId: 'org1',+ });+ (prisma.organisationUser.create as jest.Mock).mockResolvedValue({});+ (prisma.organisationInvitedUser.delete as jest.Mock).mockResolvedValue({});+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValueOnce({ id: 'ou-membership' });+ (prisma.project.findMany as jest.Mock).mockResolvedValue([]);++ const result = await acceptInvitation('inv-assign-2');+ expect(result).toEqual({ success: true });+ expect(prisma.projectUser.upsert).not.toHaveBeenCalled();+ });+});++describe('createOrganisation migration edge cases', () => {+ it('keeps existing membership as-is (no update) when shared user already has a current org', async () => {+ (prisma.organisation.create as jest.Mock).mockResolvedValue(mockOrg);+ (prisma.organisationUser.create as jest.Mock).mockResolvedValue({});++ (prisma.databaseConfigUser.findMany as jest.Mock)+ .mockResolvedValueOnce([{ databaseConfigId: 'cfg1' }]) // userConfigLinks+ .mockResolvedValueOnce([{ userId: 'u5' }]); // sharedUserLinks+ (prisma.databaseConfig.updateMany as jest.Mock).mockResolvedValue({});++ // u5 already a member AND already has a current org+ (prisma.organisationUser.findUnique as jest.Mock).mockResolvedValueOnce({ id: 'ou5' });+ (prisma.organisationUser.findFirst as jest.Mock).mockResolvedValueOnce({ id: 'ou-current' });+ (prisma.databaseConfig.findMany as jest.Mock).mockResolvedValue([]);+ (prisma.user.update as jest.Mock).mockResolvedValue({});+ (prisma.organisationUser.findMany as jest.Mock).mockResolvedValue([]); // assign-to-all-projects: no membership match branch++ const result = await createOrganisation('My Org');+ expect(result).toBeDefined();+ expect(prisma.organisationUser.update).not.toHaveBeenCalled();+ });+});diff --git a/src/client/src/__tests__/lib/platform/agent-loop/classify.test.ts b/src/client/src/__tests__/lib/platform/agent-loop/classify.test.tsindex fa041e81..8dc7bedc 100644--- a/src/client/src/__tests__/lib/platform/agent-loop/classify.test.ts+++ b/src/client/src/__tests__/lib/platform/agent-loop/classify.test.ts@@ -7,7 +7,13 @@ import {fingerprintToolArgs,hasAgentLoopFilter,listedSpansMatchingAgentLoop,+ loopGroupIdentity,loopHitsByTraceId,+ spanCostOf,+ spanLoopAttrs,+ spanTokensOf,+ spanTraceId,+ uniqueTraceCount,worstLoop,} from "@/lib/platform/agent-loop/classify";import { agentLoopWhereSql } from "@/lib/platform/agent-loop/sql";@@ -45,6 +51,16 @@ describe("hasAgentLoopFilter", () => {expect(hasAgentLoopFilter([])).toBe(false);expect(hasAgentLoopFilter(undefined)).toBe(false);});++ it("accepts array items that are boolean true or the string 'true'", () => {+ expect(hasAgentLoopFilter([true])).toBe(true);+ expect(hasAgentLoopFilter(["true"])).toBe(true);+ });++ it("rejects arrays with no matching chip values", () => {+ expect(hasAgentLoopFilter(["other"])).toBe(false);+ expect(hasAgentLoopFilter([false, "0"])).toBe(false);+ });});describe("fingerprintToolArgs", () => {@@ -53,6 +69,40 @@ describe("fingerprintToolArgs", () => {expect(fingerprintToolArgs("a b")).toBe("a b");expect(collapseWhitespace(" a\n b ")).toBe("a b");});++ it("returns an empty string for undefined or null input", () => {+ expect(fingerprintToolArgs(undefined)).toBe("");+ expect(fingerprintToolArgs(null)).toBe("");+ });++ it("JSON-stringifies non-string input before collapsing whitespace", () => {+ expect(fingerprintToolArgs({ q: "foo" })).toBe('{"q":"foo"}');+ });+});++describe("spanLoopAttrs", () => {+ it("prefers lowercase attribute bags, falling back to capitalized ones", () => {+ expect(+ spanLoopAttrs({+ SpanAttributes: { a: 1 },+ ResourceAttributes: { b: 2 },+ })+ ).toEqual({ a: 1, b: 2 });+ });++ it("returns an empty object when no attribute bags are present", () => {+ expect(spanLoopAttrs({})).toEqual({});+ });+});++describe("spanTraceId", () => {+ it("falls back to the capitalized TraceId field", () => {+ expect(spanTraceId({ TraceId: "t-cap" }, 2)).toBe("t-cap");+ });++ it("falls back to a synthetic span:index id when no trace id is present", () => {+ expect(spanTraceId({}, 5)).toBe("span:5");+ });});describe("conversationGroupKey", () => {@@ -68,6 +118,20 @@ describe("conversationGroupKey", () => {);expect(conversationGroupKey({}, "t-1")).toBe("t:t-1");});++ it("returns an empty string when no attributes or trace id are present", () => {+ expect(conversationGroupKey({}, "")).toBe("");+ expect(conversationGroupKey(undefined, "")).toBe("");+ });+});++describe("spanCostOf / spanTokensOf number parsing", () => {+ it("treats non-numeric cost/token values as 0", () => {+ expect(spanCostOf({ "gen_ai.usage.cost": "not-a-number" })).toBe(0);+ expect(+ spanTokensOf({ "gen_ai.usage.total_tokens": "not-a-number" })+ ).toBe(0);+ });});describe("detectAgentLoops", () => {@@ -116,6 +180,37 @@ describe("detectAgentLoops", () => {).toHaveLength(0);});+ it("orders repeats by a valid ISO timestamp when present", () => {+ const loops = detectAgentLoops([+ toolSpan("t-1", "search", '{"q":"orders"}', {+ conversation: "c1",+ timestamp: "2026-01-01T00:00:02.000Z",+ }),+ toolSpan("t-1", "search", '{"q":"orders"}', {+ conversation: "c1",+ timestamp: "2026-01-01T00:00:01.000Z",+ }),+ toolSpan("t-1", "search", '{"q":"orders"}', {+ conversation: "c1",+ timestamp: "2026-01-01T00:00:03.000Z",+ }),+ ]);+ expect(loops).toHaveLength(1);+ expect(loops[0].count).toBe(3);+ });++ it("treats an unparsable timestamp as 0 without throwing", () => {+ const loops = detectAgentLoops([+ toolSpan("t-1", "search", '{"q":"orders"}', {+ conversation: "c1",+ timestamp: "not-a-date",+ }),+ toolSpan("t-1", "search", '{"q":"orders"}', { conversation: "c1" }),+ toolSpan("t-1", "search", '{"q":"orders"}', { conversation: "c1" }),+ ]);+ expect(loops).toHaveLength(1);+ });+it("groups across traces that share a conversation id", () => {const loops = detectAgentLoops([toolSpan("t-1", "read_file", '{"path":"a.ts"}', {@@ -149,6 +244,11 @@ describe("listedSpansMatchingAgentLoop", () => {const spans = [toolSpan("t-1", "search", "{}")];expect(listedSpansMatchingAgentLoop(spans, false)).toEqual(spans);});++ it("returns an empty array when enabled but no loops are detected", () => {+ const spans = [toolSpan("t-1", "search", "{}")];+ expect(listedSpansMatchingAgentLoop(spans, true)).toEqual([]);+ });});describe("loopHitsByTraceId", () => {@@ -176,12 +276,123 @@ describe("asAgentLoopHit", () => {asAgentLoopHit({ toolName: "search", count: AGENT_LOOP_THRESHOLD })).toMatchObject({ toolName: "search", count: 3 });});++ it("rejects non-object values", () => {+ expect(asAgentLoopHit(null)).toBeUndefined();+ expect(asAgentLoopHit(undefined)).toBeUndefined();+ expect(asAgentLoopHit("search")).toBeUndefined();+ });++ it("rejects rows with a missing/blank tool name", () => {+ expect(asAgentLoopHit({ toolName: "", count: 5 })).toBeUndefined();+ expect(asAgentLoopHit({ count: 5 })).toBeUndefined();+ });++ it("rejects rows with a non-finite count", () => {+ expect(asAgentLoopHit({ toolName: "search", count: "abc" })).toBeUndefined();+ });++ it("defaults wastedTokens/wastedCost to 0 when not numeric", () => {+ expect(+ asAgentLoopHit({ toolName: "search", count: 5 })+ ).toEqual({ toolName: "search", count: 5, wastedTokens: 0, wastedCost: 0 });+ });});describe("worstLoop", () => {it("returns undefined when there are no loops", () => {expect(worstLoop([])).toBeUndefined();});++ it("returns the top loop's hit summary when loops exist", () => {+ const loops = detectAgentLoops([+ toolSpan("t-1", "search", '{"q":"orders"}', { conversation: "c1" }),+ toolSpan("t-1", "search", '{"q":"orders"}', { conversation: "c1" }),+ toolSpan("t-1", "search", '{"q":"orders"}', { conversation: "c1" }),+ ]);+ const hit = worstLoop(loops);+ expect(hit?.toolName).toBe("search");+ expect(hit?.count).toBe(3);+ expect(hit?.wastedTokens).toBe(20);+ expect(hit?.wastedCost).toBeCloseTo(0.02);+ });+});++describe("loopGroupIdentity", () => {+ it("prefers conversation id when present", () => {+ expect(+ loopGroupIdentity({ "gen_ai.conversation.id": "chat-1" })+ ).toEqual({ key: "gen_ai.conversation.id", value: "chat-1" });+ });++ it("falls back to coding_agent.session.id", () => {+ expect(+ loopGroupIdentity({ "coding_agent.session.id": "sess-1" })+ ).toEqual({ key: "coding_agent.session.id", value: "sess-1" });+ });++ it("falls back to generic session.id", () => {+ expect(loopGroupIdentity({ "session.id": "native-1" })).toEqual({+ key: "session.id",+ value: "native-1",+ });+ });++ it("returns undefined when no identity attribute is present", () => {+ expect(loopGroupIdentity({})).toBeUndefined();+ expect(loopGroupIdentity(undefined)).toBeUndefined();+ });+});++describe("spanTokensOf", () => {+ it("uses total tokens when present and positive", () => {+ expect(+ spanTokensOf({ "gen_ai.usage.total_tokens": "42" })+ ).toBe(42);+ });++ it("falls back to input+output tokens when total is absent", () => {+ expect(+ spanTokensOf({+ "gen_ai.usage.input_tokens": "10",+ "gen_ai.usage.output_tokens": "5",+ })+ ).toBe(15);+ });++ it("falls back to prompt/completion token aliases", () => {+ expect(+ spanTokensOf({+ "gen_ai.usage.prompt_tokens": "3",+ "gen_ai.usage.completion_tokens": "4",+ })+ ).toBe(7);+ });++ it("returns 0 when no token attributes are present", () => {+ expect(spanTokensOf({})).toBe(0);+ expect(spanTokensOf(undefined)).toBe(0);+ });+});++describe("uniqueTraceCount", () => {+ it("counts distinct trace ids", () => {+ expect(+ uniqueTraceCount([+ { traceId: "t-1" },+ { traceId: "t-1" },+ { TraceId: "t-2" },+ ])+ ).toBe(2);+ });++ it("falls back to span count when no trace ids are present", () => {+ expect(uniqueTraceCount([{}, {}])).toBe(2);+ });++ it("returns 0 for an empty span list", () => {+ expect(uniqueTraceCount([])).toBe(0);+ });});describe("agentLoopWhereSql", () => {diff --git a/src/client/src/__tests__/lib/platform/agent-loop/clickhouse.test.ts b/src/client/src/__tests__/lib/platform/agent-loop/clickhouse.test.tsnew file mode 100644index 00000000..7b51e110--- /dev/null+++ b/src/client/src/__tests__/lib/platform/agent-loop/clickhouse.test.ts@@ -0,0 +1,144 @@+const mockDataCollector = jest.fn();++jest.mock("@/lib/platform/common", () => ({+ dataCollector: (...a: unknown[]) => mockDataCollector(...a),+ OTEL_TRACES_TABLE_NAME: "otel_traces",+}));++import {+ fetchLoopHitsByTraceIds,+ fetchLoopHitsByGroupIds,+} from "@/lib/platform/agent-loop/clickhouse";++beforeEach(() => {+ jest.clearAllMocks();+});++describe("fetchLoopHitsByTraceIds", () => {+ it("returns an empty map without querying when there are no trace ids", async () => {+ const result = await fetchLoopHitsByTraceIds("1 = 1", []);+ expect(result).toEqual(new Map());+ expect(mockDataCollector).not.toHaveBeenCalled();+ });++ it("returns an empty map without querying when every id is blank/whitespace", async () => {+ const result = await fetchLoopHitsByTraceIds("1 = 1", [" ", ""]);+ expect(result).toEqual(new Map());+ expect(mockDataCollector).not.toHaveBeenCalled();+ });++ it("returns an empty map without querying when baseWhere is empty", async () => {+ const result = await fetchLoopHitsByTraceIds("", ["t1"]);+ expect(result).toEqual(new Map());+ expect(mockDataCollector).not.toHaveBeenCalled();+ });++ it("returns an empty map when dataCollector reports an error", async () => {+ mockDataCollector.mockResolvedValue({ err: "boom", data: [] });++ const result = await fetchLoopHitsByTraceIds("1 = 1", ["t1"]);++ expect(result).toEqual(new Map());+ expect(mockDataCollector).toHaveBeenCalledWith(+ expect.objectContaining({ query: expect.stringContaining("otel_traces") }),+ "query",+ undefined+ );+ });++ it("builds a Map keyed by TraceId, skipping blank ids and deduping repeats", async () => {+ mockDataCollector.mockResolvedValue({+ err: null,+ data: [+ { TraceId: "t1", toolName: "search", count: 4, wastedTokens: 10, wastedCost: 0.1 },+ { TraceId: " ", toolName: "search", count: 5, wastedTokens: 1, wastedCost: 0.01 },+ { TraceId: "t1", toolName: "search", count: 8, wastedTokens: 30, wastedCost: 0.3 },+ { TraceId: "t2", toolName: "bash", count: 1, wastedTokens: 0, wastedCost: 0 },+ ],+ });++ const result = await fetchLoopHitsByTraceIds("1 = 1", ["t1", "t2"], "db-1");++ expect(result.size).toBe(1);+ expect(result.get("t1")).toEqual({+ toolName: "search",+ count: 8,+ wastedTokens: 30,+ wastedCost: 0.3,+ });+ expect(result.has("t2")).toBe(false);+ expect(mockDataCollector).toHaveBeenCalledWith(expect.anything(), "query", "db-1");+ });++ it("dedupes and trims the requested trace ids before building the query", async () => {+ mockDataCollector.mockResolvedValue({ err: null, data: [] });++ await fetchLoopHitsByTraceIds("1 = 1", [" t1 ", "t1", "t2"]);++ const { query } = mockDataCollector.mock.calls[0][0];+ expect(query).toContain("'t1'");+ expect(query).toContain("'t2'");+ expect(query.match(/'t1'/g)?.length).toBe(1);+ });+});++describe("fetchLoopHitsByGroupIds", () => {+ it("returns an empty map without querying when there are no group ids", async () => {+ const result = await fetchLoopHitsByGroupIds("1 = 1", []);+ expect(result).toEqual(new Map());+ expect(mockDataCollector).not.toHaveBeenCalled();+ });++ it("returns an empty map without querying when baseWhere is empty", async () => {+ const result = await fetchLoopHitsByGroupIds("", ["g1"]);+ expect(result).toEqual(new Map());+ expect(mockDataCollector).not.toHaveBeenCalled();+ });++ it("returns an empty map when dataCollector reports an error", async () => {+ mockDataCollector.mockResolvedValue({ err: "boom", data: [] });++ const result = await fetchLoopHitsByGroupIds("1 = 1", ["g1"]);++ expect(result).toEqual(new Map());+ });++ it("builds a Map keyed by groupId, skipping blank ids and deduping repeats", async () => {+ mockDataCollector.mockResolvedValue({+ err: null,+ data: [+ { groupId: "g1", toolName: "search", count: 4, wastedTokens: 10, wastedCost: 0.1 },+ { groupId: "", toolName: "search", count: 5, wastedTokens: 1, wastedCost: 0.01 },+ { groupId: "g1", toolName: "search", count: 9, wastedTokens: 40, wastedCost: 0.4 },+ ],+ });++ const result = await fetchLoopHitsByGroupIds("1 = 1", ["g1"], "db-2");++ expect(result.size).toBe(1);+ expect(result.get("g1")).toEqual({+ toolName: "search",+ count: 9,+ wastedTokens: 40,+ wastedCost: 0.4,+ });+ expect(mockDataCollector).toHaveBeenCalledWith(expect.anything(), "query", "db-2");+ });++ it("skips rows whose fields do not satisfy asAgentLoopHit (below threshold)", async () => {+ mockDataCollector.mockResolvedValue({+ err: null,+ data: [{ groupId: "g1", toolName: "search", count: 1, wastedTokens: 0, wastedCost: 0 }],+ });++ const result = await fetchLoopHitsByGroupIds("1 = 1", ["g1"]);+ expect(result.size).toBe(0);+ });++ it("tolerates a successful result with no data array", async () => {+ mockDataCollector.mockResolvedValue({ err: null, data: undefined });++ const result = await fetchLoopHitsByGroupIds("1 = 1", ["g1"]);+ expect(result).toEqual(new Map());+ });+});diff --git a/src/client/src/__tests__/lib/platform/agent-loop/sql.test.ts b/src/client/src/__tests__/lib/platform/agent-loop/sql.test.tsnew file mode 100644index 00000000..e858f357--- /dev/null+++ b/src/client/src/__tests__/lib/platform/agent-loop/sql.test.ts@@ -0,0 +1,139 @@+import {+ TOOL_NAME_SQL,+ IS_TOOL_SPAN_SQL,+ ARGS_FINGERPRINT_SQL,+ GROUP_KEY_SQL,+ SPAN_COST_SQL,+ SPAN_TOKENS_SQL,+ agentLoopToolRowsSql,+ agentLoopGroupsSql,+ agentLoopWhereSql,+ agentLoopStatsSql,+ agentLoopHitsByTraceSql,+ agentLoopHitsByGroupSql,+} from "@/lib/platform/agent-loop/sql";++describe("SQL fragment constants", () => {+ it("builds a trimmed tool-name fallback chain", () => {+ expect(TOOL_NAME_SQL).toContain("gen_ai.tool.name");+ expect(TOOL_NAME_SQL).toContain("gen_ai.tool.call.name");+ expect(TOOL_NAME_SQL).toMatch(/^trim\(BOTH ' ' FROM/);+ });++ it("derives IS_TOOL_SPAN_SQL from the tool name fragment", () => {+ expect(IS_TOOL_SPAN_SQL).toBe(`notEmpty(${TOOL_NAME_SQL})`);+ });++ it("builds an args fingerprint that collapses whitespace", () => {+ expect(ARGS_FINGERPRINT_SQL).toContain("gen_ai.tool.args");+ expect(ARGS_FINGERPRINT_SQL).toContain("replaceRegexpAll");+ });++ it("builds a group key that prefers conversation, then session, then trace", () => {+ expect(GROUP_KEY_SQL).toContain("'c:'");+ expect(GROUP_KEY_SQL).toContain("'s:'");+ expect(GROUP_KEY_SQL).toContain("'t:'");+ expect(GROUP_KEY_SQL).toContain("TraceId");+ });++ it("builds cost and token aggregation fragments", () => {+ expect(SPAN_COST_SQL).toContain("gen_ai.usage.cost");+ expect(SPAN_TOKENS_SQL).toContain("gen_ai.usage.total_tokens");+ expect(SPAN_TOKENS_SQL).toContain("gen_ai.usage.input_tokens");+ expect(SPAN_TOKENS_SQL).toContain("gen_ai.usage.output_tokens");+ });+});++describe("agentLoopToolRowsSql", () => {+ it("filters by base where and tool-span predicate", () => {+ const sql = agentLoopToolRowsSql("otel_traces", "Timestamp >= now() - 1");+ expect(sql).toContain("FROM otel_traces");+ expect(sql).toContain("Timestamp >= now() - 1");+ expect(sql).toContain(IS_TOOL_SPAN_SQL);+ });++ it("omits an empty base where clause from the AND chain", () => {+ const sql = agentLoopToolRowsSql("otel_traces", "");+ expect(sql).not.toContain("AND " + IS_TOOL_SPAN_SQL);+ expect(sql).toContain(`WHERE ${IS_TOOL_SPAN_SQL}`);+ });+});++describe("agentLoopGroupsSql", () => {+ it("uses the default threshold when not provided", () => {+ const sql = agentLoopGroupsSql("otel_traces", "1=1");+ expect(sql).toContain("HAVING count() >= 3");+ });++ it("honors a custom threshold", () => {+ const sql = agentLoopGroupsSql("otel_traces", "1=1", 5);+ expect(sql).toContain("HAVING count() >= 5");+ });+});++describe("agentLoopWhereSql", () => {+ it("wraps the groups/rows join in a TraceId IN(...) predicate", () => {+ const sql = agentLoopWhereSql("otel_traces", "1=1");+ expect(sql).toMatch(/^TraceId IN \(/);+ expect(sql).toContain("INNER JOIN");+ });+});++describe("agentLoopStatsSql", () => {+ it("aggregates tool trace and loop counts", () => {+ const sql = agentLoopStatsSql("otel_traces", "1=1", 4);+ expect(sql).toContain("uniqExact(TraceId) AS tool_traces");+ expect(sql).toContain("uniqExactIf(TraceId");+ expect(sql).toContain("HAVING count() >= 4");+ });++ it("defaults to the standard threshold", () => {+ const sql = agentLoopStatsSql("otel_traces", "1=1");+ expect(sql).toContain("HAVING count() >= 3");+ });+});++describe("agentLoopHitsByTraceSql", () => {+ it("filters by the provided trace ids and escapes quotes/backslashes", () => {+ const sql = agentLoopHitsByTraceSql("otel_traces", "1=1", ["t-1", "t'2", "t\\3"]);+ expect(sql).toContain("WHERE tool_rows.TraceId IN ('t-1', 't\\'2', 't\\\\3')");+ expect(sql).toContain("GROUP BY TraceId");+ });++ it("honors a custom threshold", () => {+ const sql = agentLoopHitsByTraceSql("otel_traces", "1=1", ["t-1"], 7);+ expect(sql).toContain("HAVING count() >= 7");+ });++ it("produces an empty id list for an empty trace id array", () => {+ const sql = agentLoopHitsByTraceSql("otel_traces", "1=1", []);+ expect(sql).toContain("WHERE tool_rows.TraceId IN ()");+ });+});++describe("agentLoopHitsByGroupSql", () => {+ it("expands each group id into conversation and session key variants", () => {+ const sql = agentLoopHitsByGroupSql("otel_traces", "1=1", ["group-1"]);+ expect(sql).toContain("'c:group-1'");+ expect(sql).toContain("'s:group-1'");+ expect(sql).toContain("substring(group_key, 3) AS groupId");+ });++ it("escapes quotes/backslashes in group ids", () => {+ const sql = agentLoopHitsByGroupSql("otel_traces", "1=1", ["g'1", "g\\2"]);+ expect(sql).toContain("'c:g\\'1'");+ expect(sql).toContain("'s:g\\\\2'");+ });++ it("returns a short-circuit empty-result query when there are no group ids", () => {+ const sql = agentLoopHitsByGroupSql("otel_traces", "1=1", []);+ expect(sql).toBe(+ "SELECT '' AS groupId, '' AS toolName, 0 AS count, 0 AS wastedTokens, 0 AS wastedCost WHERE 0"+ );+ });++ it("honors a custom threshold", () => {+ const sql = agentLoopHitsByGroupSql("otel_traces", "1=1", ["group-1"], 9);+ expect(sql).toContain("HAVING count() >= 9");+ });+});diff --git a/src/client/src/__tests__/lib/platform/agents/external-discovery.test.ts b/src/client/src/__tests__/lib/platform/agents/external-discovery.test.tsnew file mode 100644index 00000000..acd344ab--- /dev/null+++ b/src/client/src/__tests__/lib/platform/agents/external-discovery.test.ts@@ -0,0 +1,978 @@+/**+ * Tests for adapter-backed agent discovery (`external-discovery.ts`).+ *+ * `discoverSdkRowsFromAdapter`/`discoverCodingRowsFromAdapter`/+ * `fetchRequestCountsFromAdapter`/`deriveSnapshotFromAdapter` only depend on+ * the `DataSourceAdapter` contract plus pure helpers (`computeAgentKey`,+ * `fingerprint`, `mergeProviders`), so we exercise them against a minimal+ * fake adapter rather than mocking modules.+ */++// `external-discovery.ts` imports `fingerprint` from `./snapshot`, which in+// turn imports `@/lib/platform/common` -> `@/lib/db-config` -> `@/lib/session`+// -> next-auth's ESM-only `openid-client`/`jose` chain. That chain isn't+// transformable under Jest's CJS transform, so we stub the leaf module the+// same way `materialize.test.ts`/`snapshot.test.ts` do to keep this a pure+// unit test of the discovery logic.+jest.mock("@/lib/platform/common", () => ({+ dataCollector: jest.fn(),+ intelligenceDataCollector: jest.fn(),+ OTEL_TRACES_TABLE_NAME: "otel_traces",+ OTEL_LOGS_TABLE_NAME: "otel_logs",+}));++import type {+ DataSourceAdapter,+ DiscoveredService,+ NormalizedSpan,+ ServiceRollup,+} from "@/lib/platform/connectors/datasource/types";+import {+ discoverSdkRowsFromAdapter,+ discoverCodingRowsFromAdapter,+ fetchRequestCountsFromAdapter,+ deriveSnapshotFromAdapter,+} from "@/lib/platform/agents/external-discovery";+import { computeAgentKey } from "@/lib/platform/agents/agent-key";+import { fingerprint } from "@/lib/platform/agents/snapshot";++function fakeAdapter(overrides: Partial<DataSourceAdapter> = {}): DataSourceAdapter {+ return {+ type: "fake",+ capabilities: jest.fn(),+ healthCheck: jest.fn(),+ validateAISignal: jest.fn(),+ listSpans: jest.fn(),+ getSpan: jest.fn(),+ getTraceSpans: jest.fn(),+ getSpansBySession: jest.fn(),+ aggregateSpans: jest.fn(),+ spanTimeSeries: jest.fn(),+ distinctValues: jest.fn(),+ attributeKeys: jest.fn(),+ listLogs: jest.fn(),+ getLog: jest.fn(),+ logTimeSeries: jest.fn(),+ listMetricSeries: jest.fn(),+ metricTimeSeries: jest.fn(),+ metricNames: jest.fn(),+ discoverServices: jest.fn(),+ aggregateByService: jest.fn(),+ sampleTracesForGraph: jest.fn(),+ ...overrides,+ } as unknown as DataSourceAdapter;+}++function makeService(overrides: Partial<DiscoveredService> = {}): DiscoveredService {+ return {+ serviceName: "checkout-service",+ environment: "production",+ clusterId: "cluster-1",+ ...overrides,+ };+}++function makeSpan(overrides: Partial<NormalizedSpan> = {}): NormalizedSpan {+ return {+ traceId: "trace-1",+ spanId: "span-1",+ parentSpanId: "",+ name: "chat",+ serviceName: "svc",+ timestamp: "2026-05-11T22:00:00.000Z",+ durationNs: 1_000_000,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ ...overrides,+ };+}++describe("discoverSdkRowsFromAdapter", () => {+ it("maps discovered services into SDK discovery rows, filling in defaults for missing fields", async () => {+ const discoverServices = jest.fn().mockResolvedValue([+ makeService({+ serviceName: "checkout-service",+ environment: "",+ clusterId: "",+ workloadKey: undefined,+ sdkVersion: undefined,+ sdkLanguage: undefined,+ firstSeen: undefined,+ lastSeen: undefined,+ }),+ ]);+ const adapter = fakeAdapter({ discoverServices });++ const rows = await discoverSdkRowsFromAdapter(adapter, 45);++ expect(rows).toHaveLength(1);+ expect(rows[0]).toEqual(+ expect.objectContaining({+ service_name: "checkout-service",+ environment: "default",+ cluster_id: "default",+ workload_key: "",+ sdk_version: "",+ sdk_language: "",+ })+ );+ expect(typeof rows[0].first_seen).toBe("string");+ expect(typeof rows[0].last_seen).toBe("string");+ });++ it("preserves populated optional fields instead of overwriting with defaults", async () => {+ const discoverServices = jest.fn().mockResolvedValue([+ makeService({+ serviceName: "svc-a",+ environment: "staging",+ clusterId: "eu-west",+ workloadKey: "docker:svc-a",+ sdkVersion: "1.2.3",+ sdkLanguage: "python",+ firstSeen: "2026-01-01T00:00:00.000Z",+ lastSeen: "2026-01-02T00:00:00.000Z",+ }),+ ]);+ const adapter = fakeAdapter({ discoverServices });++ const rows = await discoverSdkRowsFromAdapter(adapter);++ expect(rows[0]).toEqual({+ service_name: "svc-a",+ environment: "staging",+ cluster_id: "eu-west",+ workload_key: "docker:svc-a",+ sdk_version: "1.2.3",+ sdk_language: "python",+ first_seen: "2026-01-01T00:00:00.000Z",+ last_seen: "2026-01-02T00:00:00.000Z",+ });+ });++ it("excludes services with an empty/missing serviceName", async () => {+ const discoverServices = jest+ .fn()+ .mockResolvedValue([makeService({ serviceName: "" })]);+ const adapter = fakeAdapter({ discoverServices });++ const rows = await discoverSdkRowsFromAdapter(adapter);++ expect(rows).toEqual([]);+ });++ it("excludes services identified as coding-agent by sdkName === 'openlit-cli'", async () => {+ const discoverServices = jest.fn().mockResolvedValue([+ makeService({ serviceName: "some-cli", sdkName: "openlit-cli" }),+ ]);+ const adapter = fakeAdapter({ discoverServices });++ const rows = await discoverSdkRowsFromAdapter(adapter);++ expect(rows).toEqual([]);+ });++ it.each(["cursor", "claude-code", "codex", "windsurf"])(+ "excludes services identified as coding-agent by serviceName === '%s'",+ async (name) => {+ const discoverServices = jest+ .fn()+ .mockResolvedValue([makeService({ serviceName: name })]);+ const adapter = fakeAdapter({ discoverServices });++ const rows = await discoverSdkRowsFromAdapter(adapter);++ expect(rows).toEqual([]);+ }+ );++ it("returns an empty array when discoverServices rejects", async () => {+ const discoverServices = jest+ .fn()+ .mockRejectedValue(new Error("adapter unreachable"));+ const adapter = fakeAdapter({ discoverServices });++ await expect(discoverSdkRowsFromAdapter(adapter)).resolves.toEqual([]);+ });++ it("clamps lookbackMinutes to a 30-minute floor when computing the query range", async () => {+ const discoverServices = jest.fn().mockResolvedValue([]);+ const adapter = fakeAdapter({ discoverServices });+ jest.useFakeTimers().setSystemTime(new Date(1_000_000_000_000));++ await discoverSdkRowsFromAdapter(adapter, 5);++ const range = discoverServices.mock.calls[0][0];+ expect(range.end.getTime()).toBe(1_000_000_000_000);+ expect(range.start.getTime()).toBe(1_000_000_000_000 - 30 * 60 * 1000);++ jest.useRealTimers();+ });++ it("uses lookbackMinutes directly when it exceeds the 30-minute floor", async () => {+ const discoverServices = jest.fn().mockResolvedValue([]);+ const adapter = fakeAdapter({ discoverServices });+ jest.useFakeTimers().setSystemTime(new Date(1_000_000_000_000));++ await discoverSdkRowsFromAdapter(adapter, 120);++ const range = discoverServices.mock.calls[0][0];+ expect(range.start.getTime()).toBe(1_000_000_000_000 - 120 * 60 * 1000);++ jest.useRealTimers();+ });+});++describe("discoverCodingRowsFromAdapter", () => {+ it("returns [] when no vendor-identifying attribute is present on any span", async () => {+ const sampleTracesForGraph = jest+ .fn()+ .mockResolvedValue([makeSpan({ serviceName: "unrelated-svc" })]);+ const adapter = fakeAdapter({ sampleTracesForGraph });++ const rows = await discoverCodingRowsFromAdapter(adapter);++ expect(rows).toEqual([]);+ });++ it("aggregates spans per vendor via spanAttributes coding_agent.client", async () => {+ const spans = [+ makeSpan({+ timestamp: "2026-05-11T22:00:00.000Z",+ spanAttributes: {+ "coding_agent.client": "cursor",+ "coding_agent.session.id": "session-1",+ "coding_agent.client.version": "1.0.0",+ "gen_ai.user.name": "alice",+ "gen_ai.usage.cost": "0.5",+ },+ }),+ makeSpan({+ timestamp: "2026-05-11T22:05:00.000Z",+ spanAttributes: {+ "coding_agent.client": "cursor",+ "coding_agent.session.id": "session-1",+ "gen_ai.user.name": "alice",+ "coding_agent.session.cost_usd": "0.25",+ },+ }),+ makeSpan({+ timestamp: "2026-05-11T21:55:00.000Z",+ spanAttributes: {+ "coding_agent.client": "cursor",+ "session.id": "session-2",+ "gen_ai.user.name": "bob",+ },+ }),+ ];+ const sampleTracesForGraph = jest.fn().mockResolvedValue(spans);+ const adapter = fakeAdapter({ sampleTracesForGraph });++ const rows = await discoverCodingRowsFromAdapter(adapter);++ expect(rows).toHaveLength(1);+ expect(rows[0].vendor).toBe("cursor");+ expect(rows[0].client_version).toBe("1.0.0");+ expect(rows[0].session_count_24h).toBe(2);+ expect(rows[0].active_users_24h).toBe(2);+ expect(rows[0].cost_usd_24h).toBeCloseTo(0.75);+ expect(rows[0].first_seen).toBe("2026-05-11T21:55:00.000Z");+ expect(rows[0].last_seen).toBe("2026-05-11T22:05:00.000Z");+ // Untracked/legacy fields degrade to zero for the trace-sampled path.+ expect(rows[0].lines_added_24h).toBe(0);+ expect(rows[0].commit_count_24h).toBe(0);+ });++ it("identifies vendor via resourceAttributes coding_agent.client", async () => {+ const sampleTracesForGraph = jest.fn().mockResolvedValue([+ makeSpan({ resourceAttributes: { "coding_agent.client": "codex" } }),+ ]);+ const adapter = fakeAdapter({ sampleTracesForGraph });++ const rows = await discoverCodingRowsFromAdapter(adapter);++ expect(rows).toHaveLength(1);+ expect(rows[0].vendor).toBe("codex");+ });++ it("identifies claude-code via resourceAttributes service.name fallback", async () => {+ const sampleTracesForGraph = jest.fn().mockResolvedValue([+ makeSpan({ resourceAttributes: { "service.name": "claude-code" } }),+ ]);+ const adapter = fakeAdapter({ sampleTracesForGraph });++ const rows = await discoverCodingRowsFromAdapter(adapter);++ expect(rows).toHaveLength(1);+ expect(rows[0].vendor).toBe("claude-code");+ });++ it("identifies cursor via top-level serviceName fallback", async () => {+ const sampleTracesForGraph = jest.fn().mockResolvedValue([+ makeSpan({ serviceName: "cursor" }),+ ]);+ const adapter = fakeAdapter({ sampleTracesForGraph });++ const rows = await discoverCodingRowsFromAdapter(adapter);++ expect(rows).toHaveLength(1);+ expect(rows[0].vendor).toBe("cursor");+ });++ it("uses coding_agent.hook.cli.version as a resource-attribute fallback for client_version", async () => {+ const sampleTracesForGraph = jest.fn().mockResolvedValue([+ makeSpan({+ spanAttributes: { "coding_agent.client": "windsurf" },+ resourceAttributes: { "coding_agent.hook.cli.version": "2.0.0" },+ }),+ ]);+ const adapter = fakeAdapter({ sampleTracesForGraph });++ const rows = await discoverCodingRowsFromAdapter(adapter);++ expect(rows[0].client_version).toBe("2.0.0");+ });++ it("defaults session_count_24h to 1 when no session id was ever observed", async () => {+ const sampleTracesForGraph = jest.fn().mockResolvedValue([+ makeSpan({ spanAttributes: { "coding_agent.client": "cursor" } }),+ ]);+ const adapter = fakeAdapter({ sampleTracesForGraph });++ const rows = await discoverCodingRowsFromAdapter(adapter);++ expect(rows[0].session_count_24h).toBe(1);+ });++ it("ignores a non-finite cost value instead of poisoning the running total", async () => {+ const sampleTracesForGraph = jest.fn().mockResolvedValue([+ makeSpan({+ spanAttributes: {+ "coding_agent.client": "cursor",+ "gen_ai.usage.cost": "not-a-number",+ },+ }),+ ]);+ const adapter = fakeAdapter({ sampleTracesForGraph });++ const rows = await discoverCodingRowsFromAdapter(adapter);++ expect(rows[0].cost_usd_24h).toBe(0);+ });++ it("filters out vendors that aren't in the allow-list even if they were tracked", async () => {+ const sampleTracesForGraph = jest.fn().mockResolvedValue([+ makeSpan({ spanAttributes: { "coding_agent.client": "some-other-tool" } }),+ ]);+ const adapter = fakeAdapter({ sampleTracesForGraph });++ const rows = await discoverCodingRowsFromAdapter(adapter);++ expect(rows).toEqual([]);+ });++ it("falls back to listSpans when sampleTracesForGraph throws", async () => {+ const sampleTracesForGraph = jest+ .fn()+ .mockRejectedValue(new Error("sampling unsupported"));+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [makeSpan({ serviceName: "cursor" })],+ });+ const adapter = fakeAdapter({ sampleTracesForGraph, listSpans });++ const rows = await discoverCodingRowsFromAdapter(adapter);++ expect(listSpans).toHaveBeenCalledTimes(1);+ expect(rows).toHaveLength(1);+ expect(rows[0].vendor).toBe("cursor");+ });++ it("returns [] when both sampleTracesForGraph and the listSpans fallback throw", async () => {+ const sampleTracesForGraph = jest+ .fn()+ .mockRejectedValue(new Error("sampling unsupported"));+ const listSpans = jest.fn().mockRejectedValue(new Error("listSpans failed"));+ const adapter = fakeAdapter({ sampleTracesForGraph, listSpans });++ await expect(discoverCodingRowsFromAdapter(adapter)).resolves.toEqual([]);+ });++ it("returns [] for an empty span sample", async () => {+ const sampleTracesForGraph = jest.fn().mockResolvedValue([]);+ const adapter = fakeAdapter({ sampleTracesForGraph });++ await expect(discoverCodingRowsFromAdapter(adapter)).resolves.toEqual([]);+ });+});++describe("fetchRequestCountsFromAdapter", () => {+ it("maps coding-source agents directly from their precomputed session count without calling aggregateByService", async () => {+ const aggregateByService = jest.fn();+ const adapter = fakeAdapter({ aggregateByService });++ const map = await fetchRequestCountsFromAdapter(adapter, [+ {+ agent_key: "coding-1",+ service_name: "cursor",+ environment: "default",+ cluster_id: "default",+ source: "coding",+ coding_session_count_24h: 7,+ },+ ]);++ expect(map.get("coding-1")).toBe(7);+ expect(aggregateByService).not.toHaveBeenCalled();+ });++ it("defaults a coding agent's count to 0 when coding_session_count_24h is missing", async () => {+ const adapter = fakeAdapter();++ const map = await fetchRequestCountsFromAdapter(adapter, [+ {+ agent_key: "coding-2",+ service_name: "codex",+ environment: "default",+ cluster_id: "default",+ source: "coding",+ },+ ]);++ expect(map.get("coding-2")).toBe(0);+ });++ it("matches traditional agents to rollups by (clusterId, environment, serviceName) agent_key", async () => {+ const rollup: ServiceRollup = {+ serviceName: "checkout-service",+ environment: "production",+ clusterId: "cluster-1",+ requestCount: 42,+ models: [],+ providers: [],+ };+ const aggregateByService = jest.fn().mockResolvedValue([rollup]);+ const adapter = fakeAdapter({ aggregateByService });+ const agentKey = computeAgentKey("cluster-1", "production", "checkout-service");++ const map = await fetchRequestCountsFromAdapter(adapter, [+ {+ agent_key: agentKey,+ service_name: "checkout-service",+ environment: "production",+ cluster_id: "cluster-1",+ source: "sdk",+ },+ ]);++ expect(map.get(agentKey)).toBe(42);+ });++ it("falls back to matching by service_name alone when env/cluster produced no direct key match", async () => {+ const rollup: ServiceRollup = {+ serviceName: "checkout-service",+ environment: "",+ clusterId: "",+ requestCount: 15,+ models: [],+ providers: [],+ };+ const aggregateByService = jest.fn().mockResolvedValue([rollup]);+ const adapter = fakeAdapter({ aggregateByService });++ const map = await fetchRequestCountsFromAdapter(adapter, [+ {+ agent_key: "agent-without-matching-rollup-key",+ service_name: "checkout-service",+ environment: "production",+ cluster_id: "cluster-1",+ source: "sdk",+ },+ ]);++ expect(map.get("agent-without-matching-rollup-key")).toBe(15);+ });++ it("defaults requestCount to 0 for a service-name-fallback match that omits it", async () => {+ const rollup = {+ serviceName: "checkout-service",+ environment: "",+ clusterId: "",+ models: [],+ providers: [],+ } as unknown as ServiceRollup;+ const aggregateByService = jest.fn().mockResolvedValue([rollup]);+ const adapter = fakeAdapter({ aggregateByService });++ const map = await fetchRequestCountsFromAdapter(adapter, [+ {+ agent_key: "no-direct-key-match",+ service_name: "checkout-service",+ environment: "production",+ cluster_id: "cluster-1",+ source: "sdk",+ },+ ]);++ expect(map.get("no-direct-key-match")).toBe(0);+ });++ it("leaves an agent unmapped when no rollup matches it by key or by service_name", async () => {+ const rollup: ServiceRollup = {+ serviceName: "unrelated-service",+ environment: "production",+ clusterId: "cluster-1",+ requestCount: 5,+ models: [],+ providers: [],+ };+ const aggregateByService = jest.fn().mockResolvedValue([rollup]);+ const adapter = fakeAdapter({ aggregateByService });++ const map = await fetchRequestCountsFromAdapter(adapter, [+ {+ agent_key: "no-match-agent",+ service_name: "checkout-service",+ environment: "production",+ cluster_id: "cluster-1",+ source: "sdk",+ },+ ]);++ expect(map.has("no-match-agent")).toBe(false);+ });++ it("does not overwrite an agent already matched by direct key with the service-name fallback", async () => {+ const agentKey = computeAgentKey("cluster-1", "production", "checkout-service");+ const rollups: ServiceRollup[] = [+ {+ serviceName: "checkout-service",+ environment: "production",+ clusterId: "cluster-1",+ requestCount: 100,+ models: [],+ providers: [],+ },+ {+ serviceName: "checkout-service",+ environment: "",+ clusterId: "",+ requestCount: 999,+ models: [],+ providers: [],+ },+ ];+ const aggregateByService = jest.fn().mockResolvedValue(rollups);+ const adapter = fakeAdapter({ aggregateByService });++ const map = await fetchRequestCountsFromAdapter(adapter, [+ {+ agent_key: agentKey,+ service_name: "checkout-service",+ environment: "production",+ cluster_id: "cluster-1",+ source: "sdk",+ },+ ]);++ expect(map.get(agentKey)).toBe(100);+ });++ it("defaults requestCount to 0 when a matched rollup omits it", async () => {+ const agentKey = computeAgentKey("cluster-1", "production", "checkout-service");+ const rollup = {+ serviceName: "checkout-service",+ environment: "production",+ clusterId: "cluster-1",+ models: [],+ providers: [],+ } as unknown as ServiceRollup;+ const aggregateByService = jest.fn().mockResolvedValue([rollup]);+ const adapter = fakeAdapter({ aggregateByService });++ const map = await fetchRequestCountsFromAdapter(adapter, [+ {+ agent_key: agentKey,+ service_name: "checkout-service",+ environment: "production",+ cluster_id: "cluster-1",+ source: "sdk",+ },+ ]);++ expect(map.get(agentKey)).toBe(0);+ });++ it("returns an empty map when the agents list is empty and does not call aggregateByService", async () => {+ const aggregateByService = jest.fn();+ const adapter = fakeAdapter({ aggregateByService });++ const map = await fetchRequestCountsFromAdapter(adapter, []);++ expect(map.size).toBe(0);+ expect(aggregateByService).not.toHaveBeenCalled();+ });++ it("returns the coding-only map (without traditional entries) when aggregateByService rejects", async () => {+ const aggregateByService = jest+ .fn()+ .mockRejectedValue(new Error("aggregate failed"));+ const adapter = fakeAdapter({ aggregateByService });++ const map = await fetchRequestCountsFromAdapter(adapter, [+ {+ agent_key: "coding-1",+ service_name: "cursor",+ environment: "default",+ cluster_id: "default",+ source: "coding",+ coding_session_count_24h: 3,+ },+ {+ agent_key: "traditional-1",+ service_name: "checkout-service",+ environment: "production",+ cluster_id: "cluster-1",+ source: "sdk",+ },+ ]);++ expect(map.get("coding-1")).toBe(3);+ expect(map.has("traditional-1")).toBe(false);+ });+});++describe("deriveSnapshotFromAdapter", () => {+ it("returns null when listSpans rejects", async () => {+ const listSpans = jest.fn().mockRejectedValue(new Error("query failed"));+ const adapter = fakeAdapter({ listSpans });++ await expect(+ deriveSnapshotFromAdapter(adapter, { serviceName: "svc" })+ ).resolves.toBeNull();+ });++ it("returns null when no spans were sampled", async () => {+ const listSpans = jest.fn().mockResolvedValue({ fields: [], rows: [] });+ const adapter = fakeAdapter({ listSpans });++ await expect(+ deriveSnapshotFromAdapter(adapter, { serviceName: "svc" })+ ).resolves.toBeNull();+ });++ it("derives a full snapshot from GenAI span attributes, defaulting environment/clusterId", async () => {+ const toolDefs = JSON.stringify([+ { name: "search", description: "Search the web", parameters: { type: "object" } },+ ]);+ const spans = [+ makeSpan({+ timestamp: "2026-05-11T22:10:00.000Z",+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.system": "openai",+ "gen_ai.tool.definitions": toolDefs,+ "gen_ai.system_instructions": "You are helpful",+ "gen_ai.request.temperature": "0.7",+ },+ }),+ makeSpan({+ timestamp: "2026-05-11T22:00:00.000Z",+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o-mini",+ "gen_ai.tool.name": "lookup",+ },+ }),+ ];+ const listSpans = jest.fn().mockResolvedValue({ fields: [], rows: spans });+ const adapter = fakeAdapter({ listSpans });++ const result = await deriveSnapshotFromAdapter(adapter, {+ serviceName: "weather-agent",+ });++ expect(result).not.toBeNull();+ expect(result?.environment).toBe("default");+ expect(result?.cluster_id).toBe("default");+ expect(result?.agent_key).toBe(+ computeAgentKey("default", "default", "weather-agent")+ );+ expect(result?.primary_model).toBe("gpt-4o");+ expect(result?.models).toEqual(+ expect.arrayContaining(["gpt-4o", "gpt-4o-mini"])+ );+ expect(result?.providers).toEqual(["openai"]);+ expect(result?.runtime_config.provider).toBe("openai");+ expect(result?.runtime_config.temperature).toBe(0.7);+ expect(result?.system_prompt).toBe("You are helpful");+ // tools includes the JSON-defined tool plus the toolName-only tool+ // merged in afterward without duplication.+ expect(result?.tools).toEqual(+ expect.arrayContaining([+ { name: "search", description: "Search the web", schema: { type: "object" } },+ { name: "lookup", description: "", schema: null },+ ])+ );+ expect(result?.request_count).toBe(2);+ // first_seen picks the *last* array element's timestamp, last_seen the first's.+ expect(result?.first_seen).toBe("2026-05-11T22:00:00.000Z");+ expect(result?.last_seen).toBe("2026-05-11T22:10:00.000Z");+ expect(result?.version_hash).toBe(+ fingerprint({+ systemPrompt: "You are helpful",+ tools: result!.tools,+ primaryModel: "gpt-4o",+ runtimeConfig: result!.runtime_config,+ providers: result!.providers,+ })+ );+ });++ it("passes through explicit environment/clusterId and a floored lookbackMinutes", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [makeSpan()],+ });+ const adapter = fakeAdapter({ listSpans });++ await deriveSnapshotFromAdapter(adapter, {+ serviceName: "svc",+ environment: "staging",+ clusterId: "eu-west",+ lookbackMinutes: -5,+ });++ const query = listSpans.mock.calls[0][0];+ expect(query.signal).toBe("traces");+ expect(query.aiSelector).toBe(true);+ expect(query.limit).toBe(100);+ expect(query.filters).toEqual([+ { target: "attribute", scope: "resource", key: "service.name", op: "eq", value: "svc" },+ ]);+ // lookbackMinutes floors to 1 minute when a non-positive value is given.+ const rangeMs = query.timeRange.end.getTime() - query.timeRange.start.getTime();+ expect(rangeMs).toBe(60 * 1000);+ });++ it("uses gen_ai.prompt as a system_prompt fallback when system_instructions is absent", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [+ makeSpan({+ spanAttributes: { "gen_ai.prompt": "fallback prompt" },+ }),+ ],+ });+ const adapter = fakeAdapter({ listSpans });++ const result = await deriveSnapshotFromAdapter(adapter, { serviceName: "svc" });++ expect(result?.system_prompt).toBe("fallback prompt");+ });++ it("keeps the first non-empty system_prompt across multiple spans", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [+ makeSpan({ spanAttributes: { "gen_ai.system_instructions": "first" } }),+ makeSpan({ spanAttributes: { "gen_ai.system_instructions": "second" } }),+ ],+ });+ const adapter = fakeAdapter({ listSpans });++ const result = await deriveSnapshotFromAdapter(adapter, { serviceName: "svc" });++ expect(result?.system_prompt).toBe("first");+ });++ it("keeps the first temperature seen and ignores later spans' values", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [+ makeSpan({ spanAttributes: { "gen_ai.request.temperature": "0.2" } }),+ makeSpan({ spanAttributes: { "gen_ai.request.temperature": "0.9" } }),+ ],+ });+ const adapter = fakeAdapter({ listSpans });++ const result = await deriveSnapshotFromAdapter(adapter, { serviceName: "svc" });++ expect(result?.runtime_config.temperature).toBe(0.2);+ });++ it("ignores malformed gen_ai.tool.definitions JSON without throwing", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [+ makeSpan({+ spanAttributes: { "gen_ai.tool.definitions": "{not-valid-json" },+ }),+ ],+ });+ const adapter = fakeAdapter({ listSpans });++ const result = await deriveSnapshotFromAdapter(adapter, { serviceName: "svc" });++ expect(result?.tools).toEqual([]);+ });++ it("ignores gen_ai.tool.definitions that don't parse to an array", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [+ makeSpan({+ spanAttributes: {+ "gen_ai.tool.definitions": JSON.stringify({ not: "an array" }),+ },+ }),+ ],+ });+ const adapter = fakeAdapter({ listSpans });++ const result = await deriveSnapshotFromAdapter(adapter, { serviceName: "svc" });++ expect(result?.tools).toEqual([]);+ });++ it("skips tool entries in the definitions array that don't carry a name", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [+ makeSpan({+ spanAttributes: {+ "gen_ai.tool.definitions": JSON.stringify([+ { description: "no name here" },+ { name: "valid_tool", description: "ok" },+ ]),+ },+ }),+ ],+ });+ const adapter = fakeAdapter({ listSpans });++ const result = await deriveSnapshotFromAdapter(adapter, { serviceName: "svc" });++ expect(result?.tools).toEqual([+ { name: "valid_tool", description: "ok", schema: null },+ ]);+ });++ it("falls back to t.schema when parameters is absent on a tool definition", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [+ makeSpan({+ spanAttributes: {+ "gen_ai.tool.definitions": JSON.stringify([+ { name: "search", schema: { type: "string" } },+ ]),+ },+ }),+ ],+ });+ const adapter = fakeAdapter({ listSpans });++ const result = await deriveSnapshotFromAdapter(adapter, { serviceName: "svc" });++ expect(result?.tools[0].schema).toEqual({ type: "string" });+ });++ it("only parses gen_ai.tool.definitions from the first span that carries it (performance short-circuit)", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [+ makeSpan({+ spanAttributes: {+ "gen_ai.tool.definitions": JSON.stringify([{ name: "first_tool" }]),+ },+ }),+ makeSpan({+ spanAttributes: {+ "gen_ai.tool.definitions": JSON.stringify([{ name: "second_tool" }]),+ },+ }),+ ],+ });+ const adapter = fakeAdapter({ listSpans });++ const result = await deriveSnapshotFromAdapter(adapter, { serviceName: "svc" });++ expect(result?.tools.map((t) => t.name)).toEqual(["first_tool"]);+ });++ it("merges gen_ai.tool.name-only spans without duplicating a tool already parsed from definitions", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [+ makeSpan({+ spanAttributes: {+ "gen_ai.tool.definitions": JSON.stringify([+ { name: "search", description: "from-defs" },+ ]),+ "gen_ai.tool.name": "search",+ },+ }),+ ],+ });+ const adapter = fakeAdapter({ listSpans });++ const result = await deriveSnapshotFromAdapter(adapter, { serviceName: "svc" });++ expect(result?.tools).toEqual([+ { name: "search", description: "from-defs", schema: null },+ ]);+ });++ it("leaves runtime_config.provider empty when no providers were observed", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [makeSpan()],+ });+ const adapter = fakeAdapter({ listSpans });++ const result = await deriveSnapshotFromAdapter(adapter, { serviceName: "svc" });++ expect(result?.providers).toEqual([]);+ expect(result?.runtime_config.provider).toBeUndefined();+ });++ it("falls back to the current time for first_seen/last_seen when a span's timestamp is empty", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [makeSpan({ timestamp: "" })],+ });+ const adapter = fakeAdapter({ listSpans });++ const before = Date.now();+ const result = await deriveSnapshotFromAdapter(adapter, { serviceName: "svc" });+ const after = Date.now();++ expect(result?.first_seen).toBeDefined();+ expect(result?.last_seen).toBeDefined();+ const firstSeenMs = new Date(result!.first_seen).getTime();+ const lastSeenMs = new Date(result!.last_seen).getTime();+ expect(firstSeenMs).toBeGreaterThanOrEqual(before);+ expect(firstSeenMs).toBeLessThanOrEqual(after);+ expect(lastSeenMs).toBeGreaterThanOrEqual(before);+ expect(lastSeenMs).toBeLessThanOrEqual(after);+ });++ it("selects the alphabetically-first canonical provider when multiple are observed", async () => {+ const listSpans = jest.fn().mockResolvedValue({+ fields: [],+ rows: [+ makeSpan({ spanAttributes: { "gen_ai.system": "openai" } }),+ makeSpan({ spanAttributes: { "gen_ai.system": "gcp.gemini" } }),+ ],+ });+ const adapter = fakeAdapter({ listSpans });++ const result = await deriveSnapshotFromAdapter(adapter, { serviceName: "svc" });++ expect(result?.providers).toEqual(+ expect.arrayContaining(["openai", "gemini"])+ );+ // "gemini" < "openai" alphabetically.+ expect(result?.runtime_config.provider).toBe("gemini");+ });+});diff --git a/src/client/src/__tests__/lib/platform/agents/index.test.ts b/src/client/src/__tests__/lib/platform/agents/index.test.tsindex 732c4510..c5c17f37 100644--- a/src/client/src/__tests__/lib/platform/agents/index.test.ts+++ b/src/client/src/__tests__/lib/platform/agents/index.test.ts@@ -500,6 +500,141 @@ describe("listAgents", () => {expect(result.data).toHaveLength(1);expect(result.data[0].agent_key).toBe("coding-1");});++ it("triggers the coding overlay when only timeEnd (no timeStart) is provided", async () => {+ mockedDataCollector+ .mockResolvedValueOnce({+ data: [makeRow({ source: "coding", agent_key: "coding-end-only" })],+ })+ .mockResolvedValueOnce({ data: [] });++ await listAgents({+ filters: { source: ["coding"] },+ timeEnd: "2026-05-11 23:59:59",+ });+ // Two calls means the overlay branch executed (discoverCodingAgents+ // issues the second query) even though timeStart is absent.+ expect(mockedDataCollector).toHaveBeenCalledTimes(2);+ });++ it("skips rows the coding overlay has no match for and falls back to the existing last_seen when the live row's is blank", async () => {+ const cursorKey = computeAgentKey("coding", "default", "cursor");+ const codexKey = computeAgentKey("coding", "default", "codex");+ mockedDataCollector+ .mockResolvedValueOnce({+ data: [+ makeRow({+ agent_key: cursorKey,+ service_name: "cursor",+ source: "coding",+ cluster_id: "coding",+ environment: "default",+ last_seen: "2026-05-11 22:10:00",+ }),+ makeRow({+ agent_key: codexKey,+ service_name: "codex",+ source: "coding",+ cluster_id: "coding",+ environment: "default",+ last_seen: "2026-05-11 22:05:00",+ }),+ ],+ })+ // Only the "cursor" vendor is discovered live; "codex" has no+ // matching overlay row and must be left untouched. The+ // discovered row's last_seen is blank, so the original row's+ // last_seen must be preserved instead of overwritten.+ .mockResolvedValueOnce({+ data: [+ {+ vendor: "cursor",+ client_version: "1.0.0",+ first_seen: "2026-05-11 20:00:00",+ last_seen: "",+ session_count_24h: 4,+ cost_usd_24h: 0.5,+ active_users_24h: 2,+ lines_added_24h: 1,+ lines_removed_24h: 1,+ lines_accepted_24h: 1,+ lines_rejected_24h: 0,+ edit_accept_24h: 1,+ edit_reject_24h: 0,+ commit_count_24h: 0,+ pr_count_24h: 0,+ },+ ],+ });++ const result = await listAgents({+ filters: { source: ["coding"] },+ timeStart: "2026-05-11 00:00:00",+ timeEnd: "2026-05-11 23:59:59",+ });++ const cursorRow = result.data.find((r) => r.agent_key === cursorKey);+ const codexRow = result.data.find((r) => r.agent_key === codexKey);+ expect(cursorRow?.coding_session_count_24h).toBe(4);+ expect(cursorRow?.last_seen).toBe("2026-05-11 22:10:00");+ expect(codexRow?.coding_session_count_24h).toBe(0);+ expect(codexRow?.last_seen).toBe("2026-05-11 22:05:00");+ });++ it("defaults to an empty rows list when ClickHouse returns no data and no error", async () => {+ mockedDataCollector.mockResolvedValueOnce({});+ const result = await listAgents();+ expect(result.data).toEqual([]);+ expect(result.nextCursor).toBeNull();+ });++ it("applies rowToAgent defaults when optional summary fields are missing or non-array", async () => {+ mockedDataCollector.mockResolvedValueOnce({+ data: [+ {+ agent_key: "bare-key",+ service_name: "svc",+ controller_service_id: "",+ controller_instance_id: "",+ primary_model: "",+ models: undefined,+ providers: null,+ tool_names: "not-an-array",+ tool_count: 0,+ request_count_24h: 0,+ current_version_hash: "",+ current_version_number: 0,+ sdk_version: "",+ sdk_language: "",+ instrumentation_status: "",+ desired_instrumentation_status: "",+ agent_observability_status: "",+ desired_agent_status: "",+ pending_action: "",+ pending_action_status: "",+ first_seen: "2026-05-11 22:00:00",+ last_seen: "2026-05-11 22:10:00",+ updated_at: "2026-05-11 22:10:00",+ last_materialized_at: "",+ pods_total: 0,+ pods_pending: 0,+ pods_acknowledged: 0,+ },+ ],+ });+ const result = await listAgents();+ const row = result.data[0];+ expect(row.environment).toBe("default");+ expect(row.cluster_id).toBe("default");+ expect(row.source).toBe("sdk");+ expect(row.models).toEqual([]);+ expect(row.providers).toEqual([]);+ expect(row.tool_names).toEqual([]);+ expect(row.instrumentation_status).toBe("discovered");+ expect(row.desired_instrumentation_status).toBe("none");+ expect(row.desired_agent_status).toBe("none");+ expect(row.last_materialized_at).toBe("2026-05-11 22:10:00");+ });});describe("normalizeDeploymentEnvironment / deploymentEnvironmentSqlPredicate", () => {@@ -533,6 +668,11 @@ describe("getAgent", () => {expect(await getAgent({ agentKey: "key1" })).toBeNull();});+ it("returns null when ClickHouse returns no data and no error", async () => {+ mockedDataCollector.mockResolvedValueOnce({});+ expect(await getAgent({ agentKey: "missing-data" })).toBeNull();+ });+it("invalidates the detail cache key", () => {invalidateAgent("key1", "db-1");expect(invalidateCache).toHaveBeenCalledWith("agents:detail:db-1:key1");diff --git a/src/client/src/__tests__/lib/platform/agents/version-filter.test.ts b/src/client/src/__tests__/lib/platform/agents/version-filter.test.tsindex 73d1c377..af896d78 100644--- a/src/client/src/__tests__/lib/platform/agents/version-filter.test.ts+++ b/src/client/src/__tests__/lib/platform/agents/version-filter.test.ts@@ -38,6 +38,12 @@ jest.mock("@/lib/platform/agents/logger", () => ({},}));+const mockGetTelemetryAdapterForDbConfig = jest.fn();+jest.mock("@/lib/telemetry-source", () => ({+ getTelemetryAdapterForDbConfig: (...args: unknown[]) =>+ mockGetTelemetryAdapterForDbConfig(...args),+}));+import {buildVersionWhereClause,getVersionWindow,@@ -56,6 +62,7 @@ describe("getVersionWindow", () => {environment: "production",});mockDataCollector.mockResolvedValue({ err: null, data: [{ stamped: 1 }] });+ mockGetTelemetryAdapterForDbConfig.mockReset();});it("re-exports the pure version where builder", () => {@@ -116,6 +123,111 @@ describe("getVersionWindow", () => {);});+ it("falls through to the ClickHouse probe when the resolved adapter is built-in", async () => {+ mockGetTelemetryAdapterForDbConfig.mockResolvedValue({ isBuiltIn: true });++ await expect(getVersionWindow("agent-1", "v1", "db-1")).resolves.toMatchObject({+ hasAttributeSpans: true,+ });+ expect(mockDataCollector).toHaveBeenCalled();+ });++ it("uses a non-built-in telemetry adapter's listSpans instead of ClickHouse", async () => {+ const listSpans = jest.fn().mockResolvedValue({ rows: [{ id: "span-1" }] });+ mockGetTelemetryAdapterForDbConfig.mockResolvedValue({+ isBuiltIn: false,+ adapter: { listSpans },+ });++ await expect(getVersionWindow("agent-1", "v1", "db-1")).resolves.toMatchObject({+ hasAttributeSpans: true,+ });+ expect(listSpans).toHaveBeenCalledWith(+ expect.objectContaining({+ signal: "traces",+ aiSelector: true,+ limit: 1,+ })+ );+ expect(mockDataCollector).not.toHaveBeenCalled();+ });++ it("reports no attribute spans when a non-built-in adapter finds none", async () => {+ mockGetTelemetryAdapterForDbConfig.mockResolvedValue({+ isBuiltIn: false,+ adapter: { listSpans: jest.fn().mockResolvedValue({ rows: [] }) },+ });++ await expect(getVersionWindow("agent-1", "v1", "db-1")).resolves.toMatchObject({+ hasAttributeSpans: false,+ });+ expect(mockDataCollector).not.toHaveBeenCalled();+ });++ it("falls back to a 24h window when the version's first/last seen dates are invalid", async () => {+ mockGetVersion.mockResolvedValueOnce({+ version_hash: "v1",+ first_seen: "not-a-date",+ last_seen: "also-not-a-date",+ });+ const listSpans = jest.fn().mockResolvedValue({ rows: [] });+ mockGetTelemetryAdapterForDbConfig.mockResolvedValue({+ isBuiltIn: false,+ adapter: { listSpans },+ });++ await getVersionWindow("agent-1", "v1", "db-1");++ const call = listSpans.mock.calls[0][0];+ expect(call.timeRange.start).toBeInstanceOf(Date);+ expect(call.timeRange.end).toBeInstanceOf(Date);+ });++ it("falls back to the ClickHouse probe when resolving the telemetry adapter throws", async () => {+ mockGetTelemetryAdapterForDbConfig.mockRejectedValue(new Error("boom"));++ await expect(getVersionWindow("agent-1", "v1", "db-1")).resolves.toMatchObject({+ hasAttributeSpans: true,+ });+ expect(mockDataCollector).toHaveBeenCalled();+ });++ it("falls back to the current time in the ClickHouse probe when dates are unparsable", async () => {+ mockGetVersion.mockResolvedValueOnce({+ version_hash: "v1",+ first_seen: "not-a-date-at-all",+ last_seen: "also-garbage",+ });+ // No dbConfigId -> skips the telemetry-adapter branch and goes straight+ // to the ClickHouse probe, exercising toClickHouseDateTime's NaN fallback.+ await getVersionWindow("agent-1", "v1");++ const call = mockDataCollector.mock.calls[0][0];+ expect(call.query).toMatch(+ /parseDateTimeBestEffort\('\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'\)/+ );+ });++ it("reformats a parsable date-only string that doesn't match the fast-path regex", async () => {+ mockGetVersion.mockResolvedValueOnce({+ version_hash: "v1",+ first_seen: "2026-01-01", // valid Date, but no time component to match the regex+ last_seen: "2026-01-02T00:00:00.000Z",+ });+ await getVersionWindow("agent-1", "v1");++ const call = mockDataCollector.mock.calls[0][0];+ expect(call.query).toContain("2026-01-01 00:00:00");+ });++ it("treats a missing data array from a successful probe as no stamped spans", async () => {+ mockDataCollector.mockResolvedValueOnce({ err: null, data: undefined });++ await expect(getVersionWindow("agent-1", "v1")).resolves.toMatchObject({+ hasAttributeSpans: false,+ });+ });+it("uses the default environment predicate for default agents", async () => {mockGetAgent.mockResolvedValueOnce({service_name: "api",diff --git a/src/client/src/__tests__/lib/platform/chat/conversation.test.ts b/src/client/src/__tests__/lib/platform/chat/conversation.test.tsindex 169d69c5..3368a3b3 100644--- a/src/client/src/__tests__/lib/platform/chat/conversation.test.ts+++ b/src/client/src/__tests__/lib/platform/chat/conversation.test.ts@@ -57,6 +57,29 @@ describe('getConversations', () => {(dataCollector as jest.Mock).mockResolvedValue({ err: 'query failed' });await expect(getConversations()).resolves.toEqual({ err: 'query failed' });});++ it('defaults to an empty list when no data is returned', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: undefined, err: null });+ await expect(getConversations()).resolves.toEqual({ data: [] });+ });++ it('normalizes non-finite numeric fields and non-assistant roles', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({+ data: [+ {+ id: 'c1',+ title: 'Test',+ totalCost: NaN,+ totalPromptTokens: Infinity,+ totalCompletionTokens: 'not-a-number',+ },+ ],+ });+ const { data } = await getConversations();+ expect(data![0].totalCost).toBe(0);+ expect(data![0].totalPromptTokens).toBe(0);+ expect(data![0].totalCompletionTokens).toBe(0);+ });});describe('getConversationWithMessages', () => {@@ -141,6 +164,24 @@ describe('getConversationWithMessages', () => {err: 'messages failed',});});++ it('normalizes an assistant role and defaults to an empty message list when no data is returned', async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [{ id: 'c1' }] })+ .mockResolvedValueOnce({ data: undefined });++ const { data } = await getConversationWithMessages('c1');+ expect(data?.messages).toEqual([]);+ });++ it('normalizes an assistant role in returned messages', async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [{ id: 'c1' }] })+ .mockResolvedValueOnce({ data: [{ id: 'm1', role: 'assistant', content: 'Hi there' }] });++ const { data } = await getConversationWithMessages('c1');+ expect(data?.messages[0].role).toBe('assistant');+ });});describe('createConversation', () => {@@ -165,6 +206,20 @@ describe('createConversation', () => {await createConversation('Test', 'openai', 'gpt-4');expect(dataCollector).toHaveBeenCalledTimes(1);});++ it('defaults to an empty title when none is provided', async () => {+ (dataCollector as jest.Mock).mockResolvedValueOnce({ err: null, data: {} });+ await createConversation('', 'openai', 'gpt-4');+ expect((dataCollector as jest.Mock).mock.calls[0][0].values[0].title).toBe('');+ });++ it('serializes provided meta instead of defaulting to an empty object', async () => {+ (dataCollector as jest.Mock).mockResolvedValueOnce({ err: null, data: {} });+ await createConversation('Test', 'openai', 'gpt-4', { meta: { foo: 'bar' } });+ expect((dataCollector as jest.Mock).mock.calls[0][0].values[0].meta).toBe(+ JSON.stringify({ foo: 'bar' })+ );+ });});describe('deleteConversation', () => {@@ -260,6 +315,20 @@ describe('addMessage', () => {expect(result.err).toBe('insert failed');expect(result.data).toBeUndefined();});++ it('sanitizes provider and model when provided', async () => {+ (dataCollector as jest.Mock).mockResolvedValueOnce({ err: null, data: {} });+ await addMessage({+ conversationId: 'c1',+ role: 'assistant',+ content: 'Hello',+ provider: 'openai',+ model: 'gpt-4o',+ });+ const insertCall = (dataCollector as jest.Mock).mock.calls[0];+ expect(insertCall[0].values[0].provider).toBe('openai');+ expect(insertCall[0].values[0].model).toBe('gpt-4o');+ });});describe('updateMessage', () => {@@ -336,4 +405,9 @@ describe('getConversationMessages', () => {err: 'messages failed',});});++ it('defaults to an empty list when no data is returned', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: undefined, err: null });+ await expect(getConversationMessages('c1')).resolves.toEqual({ data: [] });+ });});diff --git a/src/client/src/__tests__/lib/platform/chat/stream.test.ts b/src/client/src/__tests__/lib/platform/chat/stream.test.tsindex 5bc79251..2a15c627 100644--- a/src/client/src/__tests__/lib/platform/chat/stream.test.ts+++ b/src/client/src/__tests__/lib/platform/chat/stream.test.ts@@ -63,10 +63,12 @@ jest.mock('@/lib/platform/chat/telemetry-sql-routing', () => ({}));import { streamText, generateText } from 'ai';+import { createOpenAI } from '@ai-sdk/openai';import { dataCollector } from '@/lib/platform/common';import { addMessage, getConversationMessages, updateConversation } from '@/lib/platform/chat/conversation';import { extractSQLFromResponse, validateSQL } from '@/lib/platform/chat/sql-validator';import { authorizeTelemetrySQLRouting } from '@/lib/platform/chat/telemetry-sql-routing';+import { isNativeSqlChatAvailable } from '@/lib/telemetry-source';async function* streamParts(parts: any[]) {for (const part of parts) {@@ -109,6 +111,18 @@ describe('getModelInstance', () => {expect(() => getModelInstance(p, 'key', 'model')).not.toThrow();}});++ it('throws when a provider factory returns a non-callable object instance', () => {+ (createOpenAI as jest.Mock).mockReturnValueOnce({ notAFunction: true });+ expect(() => getModelInstance('openai', 'key', 'model')).toThrow();+ });++ it('throws a descriptive error when a provider factory returns neither a function nor an object', () => {+ (createOpenAI as jest.Mock).mockReturnValueOnce(undefined);+ expect(() => getModelInstance('openai', 'key', 'model')).toThrow(+ 'Invalid provider instance for openai'+ );+ });});describe('formatStreamError', () => {@@ -608,6 +622,219 @@ describe('streamChatMessage', () => {});});+ it('falls back to a default tool label and marks errored tool results distinctly', async () => {+ const onStep = jest.fn();+ (streamText as jest.Mock).mockImplementation(({ onFinish }) => {+ onFinish({+ text: '',+ usage: { inputTokens: 0, outputTokens: 0 },+ steps: [],+ });+ return {+ fullStream: streamParts([+ { type: 'tool-call' },+ { type: 'tool-result', result: { success: false, error: 'boom' } },+ ]),+ };+ });++ await streamChatMessage({+ conversationId: 'c1',+ content: 'Hello',+ provider: 'openai',+ apiKey: 'sk-test',+ model: 'gpt-4o',+ userId: 'u1',+ dbConfigId: 'db1',+ onStep,+ });++ expect(onStep).toHaveBeenCalledWith('Using tool', 'active');+ expect(onStep).toHaveBeenCalledWith('Using tool', 'error');+ });++ it('skips empty text-delta parts without emitting a callback for them', async () => {+ const onDelta = jest.fn();+ (streamText as jest.Mock).mockImplementation(({ onFinish }) => {+ onFinish({+ text: 'Hello',+ usage: { inputTokens: 1, outputTokens: 1 },+ steps: [],+ });+ return {+ fullStream: streamParts([+ { type: 'text-delta' },+ { type: 'text-delta', text: 'Hello' },+ ]),+ };+ });++ const result = await streamChatMessage({+ conversationId: 'c1',+ content: 'Hi',+ provider: 'openai',+ apiKey: 'sk-test',+ model: 'gpt-4o',+ userId: 'u1',+ dbConfigId: 'db1',+ onDelta,+ });++ expect(onDelta).toHaveBeenCalledTimes(1);+ expect(onDelta).toHaveBeenCalledWith('Hello');+ expect(result.responseText).toBe('Hello');+ });++ it('emits the fallback delta when the response is built entirely from tool results', async () => {+ const onDelta = jest.fn();+ (streamText as jest.Mock).mockImplementation(({ onFinish }) => {+ onFinish({+ text: '',+ usage: { inputTokens: 0, outputTokens: 0 },+ steps: [],+ });+ return {+ fullStream: streamParts([+ {+ type: 'tool-result',+ toolName: 'get_secret',+ result: { success: true, message: 'Secret stored' },+ },+ ]),+ };+ });++ const result = await streamChatMessage({+ conversationId: 'c1',+ content: 'Store secret',+ provider: 'openai',+ apiKey: 'sk-test',+ model: 'gpt-4o',+ userId: 'u1',+ dbConfigId: 'db1',+ onDelta,+ });++ expect(onDelta).toHaveBeenCalledWith(expect.stringContaining('**Secret stored**'));+ expect(result.responseText).toContain('**Secret stored**');+ });++ it('emits the sanitized error text via onDelta when streaming fails before text arrives', async () => {+ const onDelta = jest.fn();+ (streamText as jest.Mock).mockImplementation(({ onError }) => {+ onError({ error: { statusCode: 401 } });+ return { fullStream: streamParts([]) };+ });++ const result = await streamChatMessage({+ conversationId: 'c1',+ content: 'Hello',+ provider: 'openai',+ apiKey: 'bad-key',+ model: 'gpt-4o',+ userId: 'u1',+ dbConfigId: 'db1',+ onDelta,+ });++ expect(onDelta).toHaveBeenCalledWith(expect.stringContaining('Invalid API key'));+ expect(result.responseText).toContain('Invalid API key');+ });++ it('emits the appended SQL query-result text via onDelta after enrichment', async () => {+ const onDelta = jest.fn();+ (extractSQLFromResponse as jest.Mock).mockReturnValue(['SELECT 1']);+ (validateSQL as jest.Mock).mockReturnValue({ valid: true, query: 'SELECT 1' });+ (dataCollector as jest.Mock).mockResolvedValue({ data: [{ one: 1 }], err: null });+ (streamText as jest.Mock).mockImplementation(({ onFinish }) => {+ onFinish({+ text: 'Run SELECT 1',+ usage: { inputTokens: 1, outputTokens: 1 },+ steps: [],+ });+ return {+ fullStream: streamParts([{ type: 'text-delta', text: 'Run SELECT 1' }]),+ };+ });++ const result = await streamChatMessage({+ conversationId: 'c1',+ content: 'Run SQL',+ provider: 'openai',+ apiKey: 'sk-test',+ model: 'gpt-4o',+ userId: 'u1',+ dbConfigId: 'db1',+ onDelta,+ });++ expect(result.responseText).toBe('Run SELECT 1\n\n```query-result\n[{"one":1}]\n```');+ expect(onDelta).toHaveBeenCalledWith('\n\n```query-result\n[{"one":1}]\n```');+ });++ it('falls back to the full content as the title when it is 50 characters or fewer and title generation fails', async () => {+ const shortPrompt = 'Explain traces';+ (getConversationMessages as jest.Mock).mockResolvedValue({+ data: [{ role: 'user', content: shortPrompt }],+ });+ (generateText as jest.Mock).mockRejectedValue(new Error('title failed'));+ (streamText as jest.Mock).mockImplementation(({ onFinish }) => {+ onFinish({+ text: 'Trace analysis',+ usage: { inputTokens: 1, outputTokens: 1 },+ steps: [],+ });+ return {+ fullStream: streamParts([{ type: 'text-delta', text: 'Trace analysis' }]),+ };+ });++ await streamChatMessage({+ conversationId: 'c1',+ content: shortPrompt,+ provider: 'openai',+ apiKey: 'sk-test',+ model: 'gpt-4o',+ userId: 'u1',+ dbConfigId: 'db1',+ });++ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(updateConversation).toHaveBeenCalledWith('c1', {+ title: shortPrompt,+ });+ });++ it('skips SQL execution when native SQL chat is unavailable for the environment', async () => {+ (extractSQLFromResponse as jest.Mock).mockReturnValue(['SELECT 1']);+ (validateSQL as jest.Mock).mockReturnValue({ valid: true, query: 'SELECT 1' });+ (isNativeSqlChatAvailable as jest.Mock).mockResolvedValueOnce({ available: false });+ (streamText as jest.Mock).mockImplementation(({ onFinish }) => {+ onFinish({+ text: '```sql\nSELECT 1\n```',+ usage: { inputTokens: 1, outputTokens: 1 },+ steps: [],+ });+ return {+ fullStream: streamParts([{ type: 'text-delta', text: '```sql\nSELECT 1\n```' }]),+ };+ });++ const result = await streamChatMessage({+ conversationId: 'c1',+ content: 'Run SQL',+ provider: 'openai',+ apiKey: 'sk-test',+ model: 'gpt-4o',+ userId: 'u1',+ dbConfigId: 'db1',+ });++ expect(dataCollector).not.toHaveBeenCalled();+ expect(result.responseText).toBe('```sql\nSELECT 1\n```');+ });+it('appends query results when a SQL block cannot be replaced exactly', async () => {(extractSQLFromResponse as jest.Mock).mockReturnValue(['SELECT 1']);(validateSQL as jest.Mock).mockReturnValue({ valid: true, query: 'SELECT 1' });diff --git a/src/client/src/__tests__/lib/platform/common.test.ts b/src/client/src/__tests__/lib/platform/common.test.tsindex 126d7ae2..847b6f4f 100644--- a/src/client/src/__tests__/lib/platform/common.test.ts+++ b/src/client/src/__tests__/lib/platform/common.test.ts@@ -116,6 +116,32 @@ describe('dataCollector', () => {});});+ describe('client acquisition failures (native ClickHouse path)', () => {+ it('returns the error when clickhousePool.acquire() fails', async () => {+ const mockPool = { acquire: jest.fn(), release: jest.fn() };+ (createClickhousePool as jest.Mock).mockReturnValue(mockPool);+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, mockDbConfig])+ .mockResolvedValueOnce(['acquire failed', null]);++ const result = await dataCollector({ table: 'test_table', values: [{ col: 1 }] }, 'insert');+ expect(result.err).toBe('acquire failed');+ expect(result.data).toEqual([]);+ });++ it('returns an unavailable-client error when acquire resolves without a client', async () => {+ const mockPool = { acquire: jest.fn(), release: jest.fn() };+ (createClickhousePool as jest.Mock).mockReturnValue(mockPool);+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, mockDbConfig])+ .mockResolvedValueOnce([null, null]);++ const result = await dataCollector({ table: 'test_table', values: [{ col: 1 }] }, 'insert');+ expect(result.err).toBe('Clickhouse client is not available!');+ expect(result.data).toEqual([]);+ });+ });+describe('insert mode', () => {it('returns error when no table provided', async () => {const mockClient = makeClient();@@ -310,4 +336,51 @@ describe('intelligenceDataCollector', () => {expect(executeOpenPlaitRead).not.toHaveBeenCalled();expect(mockPool.release).toHaveBeenCalledWith(mockClient);});++ it('returns an error when no query is provided (native query mode does not early-return through OpenPlait)', async () => {+ const mockClient = makeClient();+ const mockPool = { acquire: jest.fn(), release: jest.fn() };+ (createClickhousePool as jest.Mock).mockReturnValue(mockPool);+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, mockDbConfig])+ .mockResolvedValueOnce([null, mockClient]);++ const result = await intelligenceDataCollector({}, 'query');++ expect(result.err).toBe('No query specified!');+ expect(executeOpenPlaitRead).not.toHaveBeenCalled();+ });++ it('applies readonly clickhouse_settings on the native query when enable_readonly is true', async () => {+ const mockClient = makeClient();+ const mockPool = { acquire: jest.fn(), release: jest.fn() };+ (createClickhousePool as jest.Mock).mockReturnValue(mockPool);+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, mockDbConfig])+ .mockResolvedValueOnce([null, mockClient])+ .mockResolvedValueOnce([null, { json: jest.fn().mockResolvedValue([{ total: 2 }]) }])+ .mockResolvedValueOnce([null, [{ total: 2 }]]);++ await intelligenceDataCollector({ query: 'SELECT 1', enable_readonly: true });++ const callArg = mockClient.query.mock.calls[0][0];+ expect(callArg.clickhouse_settings).toEqual({ readonly: '1' });+ });++ it('defaults to an empty data array when the native query resolves without rows', async () => {+ const mockClient = makeClient({+ query: jest.fn().mockResolvedValue({ json: jest.fn().mockResolvedValue(null) }),+ });+ const mockPool = { acquire: jest.fn(), release: jest.fn() };+ (createClickhousePool as jest.Mock).mockReturnValue(mockPool);+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, mockDbConfig])+ .mockResolvedValueOnce([null, mockClient])+ .mockResolvedValueOnce([null, { json: jest.fn().mockResolvedValue(null) }])+ .mockResolvedValueOnce([null, null]);++ const result = await intelligenceDataCollector({ query: 'SELECT 1' });++ expect(result).toEqual({ err: null, data: [] });+ });});diff --git a/src/client/src/__tests__/lib/platform/connectors/bootstrap.test.ts b/src/client/src/__tests__/lib/platform/connectors/bootstrap.test.tsnew file mode 100644index 00000000..e604afae--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/bootstrap.test.ts@@ -0,0 +1,33 @@+const mockEnsureAdaptersRegistered = jest.fn();+const mockEnsureMemoryAdaptersRegistered = jest.fn();++jest.mock("@/lib/platform/connectors/datasource/bootstrap", () => ({+ ensureAdaptersRegistered: (...a: unknown[]) => mockEnsureAdaptersRegistered(...a),+}));++jest.mock("@/lib/platform/connectors/memory/bootstrap", () => ({+ ensureMemoryAdaptersRegistered: (...a: unknown[]) => mockEnsureMemoryAdaptersRegistered(...a),+}));++import { ensureConnectorsRegistered } from "@/lib/platform/connectors/bootstrap";++beforeEach(() => {+ jest.clearAllMocks();+});++describe("ensureConnectorsRegistered", () => {+ it("registers both datasource and memory connector categories", () => {+ ensureConnectorsRegistered();++ expect(mockEnsureAdaptersRegistered).toHaveBeenCalledTimes(1);+ expect(mockEnsureMemoryAdaptersRegistered).toHaveBeenCalledTimes(1);+ });++ it("calls both registries again on every invocation", () => {+ ensureConnectorsRegistered();+ ensureConnectorsRegistered();++ expect(mockEnsureAdaptersRegistered).toHaveBeenCalledTimes(2);+ expect(mockEnsureMemoryAdaptersRegistered).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/client/src/__tests__/lib/platform/connectors/catalog.test.ts b/src/client/src/__tests__/lib/platform/connectors/catalog.test.tsnew file mode 100644index 00000000..2cd180da--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/catalog.test.ts@@ -0,0 +1,100 @@+const mockEnsureConnectorsRegistered = jest.fn();+const mockAvailableSourceTypeDescriptors = jest.fn();+const mockAvailableMemoryTypeDescriptors = jest.fn();+const mockIsVisibleConnectorType = jest.fn();+const mockConnectorIconPath = jest.fn();++jest.mock("@/lib/platform/connectors/bootstrap", () => ({+ ensureConnectorsRegistered: (...a: unknown[]) => mockEnsureConnectorsRegistered(...a),+}));++jest.mock("@/lib/telemetry-source-crud", () => ({+ availableSourceTypeDescriptors: (...a: unknown[]) => mockAvailableSourceTypeDescriptors(...a),+}));++jest.mock("@/lib/platform/connectors/memory/crud", () => ({+ availableMemoryTypeDescriptors: (...a: unknown[]) => mockAvailableMemoryTypeDescriptors(...a),+}));++jest.mock("@/lib/platform/connectors/visible-types", () => ({+ isVisibleConnectorType: (...a: unknown[]) => mockIsVisibleConnectorType(...a),+}));++jest.mock("@/lib/platform/connectors/icons", () => ({+ connectorIconPath: (...a: unknown[]) => mockConnectorIconPath(...a),+}));++import { availableConnectorTypeDescriptors } from "@/lib/platform/connectors/catalog";++beforeEach(() => {+ jest.clearAllMocks();+ mockAvailableSourceTypeDescriptors.mockReturnValue([]);+ mockAvailableMemoryTypeDescriptors.mockReturnValue([]);+ mockIsVisibleConnectorType.mockReturnValue(true);+});++describe("availableConnectorTypeDescriptors", () => {+ it("registers connectors before building the catalog", () => {+ availableConnectorTypeDescriptors();+ expect(mockEnsureConnectorsRegistered).toHaveBeenCalledTimes(1);+ });++ it("merges category/scope onto datasource descriptors and keeps an existing icon", () => {+ mockAvailableSourceTypeDescriptors.mockReturnValue([+ { type: "tempo", displayName: "Tempo", icon: "/icons/tempo.svg" },+ ]);++ const result = availableConnectorTypeDescriptors();++ expect(result).toEqual([+ expect.objectContaining({+ type: "tempo",+ icon: "/icons/tempo.svg",+ category: "datasource",+ scope: "project",+ }),+ ]);+ expect(mockConnectorIconPath).not.toHaveBeenCalled();+ });++ it("falls back to connectorIconPath when a datasource descriptor has no icon", () => {+ mockAvailableSourceTypeDescriptors.mockReturnValue([+ { type: "loki", displayName: "Loki" },+ ]);+ mockConnectorIconPath.mockReturnValue("/icons/loki.svg");++ const result = availableConnectorTypeDescriptors();++ expect(mockConnectorIconPath).toHaveBeenCalledWith("loki");+ expect(result).toEqual([+ expect.objectContaining({ type: "loki", icon: "/icons/loki.svg" }),+ ]);+ });++ it("passes memory descriptors through unchanged", () => {+ mockAvailableMemoryTypeDescriptors.mockReturnValue([+ { type: "mem0", displayName: "Mem0", category: "memory", scope: "project" },+ ]);++ const result = availableConnectorTypeDescriptors();++ expect(result).toEqual([+ { type: "mem0", displayName: "Mem0", category: "memory", scope: "project" },+ ]);+ });++ it("filters out hidden connector types", () => {+ mockAvailableSourceTypeDescriptors.mockReturnValue([+ { type: "tempo", displayName: "Tempo", icon: "/icons/tempo.svg" },+ { type: "datadog", displayName: "Datadog", icon: "/icons/datadog.svg" },+ ]);+ mockAvailableMemoryTypeDescriptors.mockReturnValue([+ { type: "mem0", displayName: "Mem0" },+ ]);+ mockIsVisibleConnectorType.mockImplementation((type: unknown) => type !== "datadog");++ const result = availableConnectorTypeDescriptors();++ expect(result.map((descriptor) => descriptor.type)).toEqual(["tempo", "mem0"]);+ });+});diff --git a/src/client/src/__tests__/lib/platform/connectors/datasource-index.test.ts b/src/client/src/__tests__/lib/platform/connectors/datasource-index.test.tsnew file mode 100644index 00000000..70d96187--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/datasource-index.test.ts@@ -0,0 +1,201 @@+const mockListSourceTypeDescriptors = jest.fn();+const mockCreateAdapter = jest.fn();+const mockRegisterConnectorType = jest.fn();+const mockConnectorIconPath = jest.fn((..._a: unknown[]) => "/icons/mock.svg");+const mockConnectorDescription = jest.fn((..._a: unknown[]) => "Mock description");++jest.mock("@/lib/platform/connectors/datasource/registry", () => ({+ listSourceTypeDescriptors: (...a: unknown[]) => mockListSourceTypeDescriptors(...a),+ createAdapter: (...a: unknown[]) => mockCreateAdapter(...a),+}));++jest.mock("@/lib/platform/connectors/registry", () => ({+ registerConnectorType: (...a: unknown[]) => mockRegisterConnectorType(...a),+}));++jest.mock("@/lib/platform/connectors/icons", () => ({+ connectorIconPath: (...a: unknown[]) => mockConnectorIconPath(...a),+}));++jest.mock("@/lib/platform/connectors/descriptions", () => ({+ connectorDescription: (...a: unknown[]) => mockConnectorDescription(...a),+}));++import { registerDatasourceConnectorTypes } from "@/lib/platform/connectors/datasource/index";++function fieldDescriptor(kind: string) {+ return {+ type: "tempo",+ displayName: "Tempo",+ declaredSignals: ["traces"],+ capabilities: {},+ correlation: {},+ configFields: [+ { key: "endpoint", label: "Endpoint", kind, group: "connection" },+ ],+ };+}++beforeEach(() => {+ jest.clearAllMocks();+});++describe("registerDatasourceConnectorTypes", () => {+ it("does nothing when there are no source type descriptors", () => {+ mockListSourceTypeDescriptors.mockReturnValue([]);+ registerDatasourceConnectorTypes();+ expect(mockRegisterConnectorType).not.toHaveBeenCalled();+ });++ it.each([+ ["switch", "boolean"],+ ["password", "password"],+ ["url", "url"],+ ["select", "select"],+ ["text", "text"],+ ["unknown-kind", "text"],+ ])("maps configField kind %s to connector field kind %s", (kind, expected) => {+ mockListSourceTypeDescriptors.mockReturnValue([fieldDescriptor(kind)]);+ registerDatasourceConnectorTypes();++ const registration = mockRegisterConnectorType.mock.calls[0][0];+ expect(registration.descriptor.configFields[0].kind).toBe(expected);+ });++ it("registers one connector type per source descriptor with the mapped metadata", () => {+ mockListSourceTypeDescriptors.mockReturnValue([+ {+ type: "tempo",+ displayName: "Tempo",+ declaredSignals: ["traces"],+ capabilities: { readSpans: true },+ correlation: {},+ internal: false,+ configFields: [+ {+ key: "endpoint",+ label: "Endpoint",+ kind: "url",+ group: "connection",+ defaultValue: "http://localhost",+ options: undefined,+ },+ ],+ },+ ]);+ registerDatasourceConnectorTypes();++ expect(mockRegisterConnectorType).toHaveBeenCalledTimes(1);+ const registration = mockRegisterConnectorType.mock.calls[0][0];+ expect(registration.descriptor).toMatchObject({+ type: "tempo",+ category: "datasource",+ displayName: "Tempo",+ description: "Mock description",+ icon: "/icons/mock.svg",+ scope: "project",+ capabilities: { readSpans: true },+ internal: false,+ });+ expect(mockConnectorDescription).toHaveBeenCalledWith("tempo", "Tempo");+ expect(mockConnectorIconPath).toHaveBeenCalledWith("tempo");+ });++ it("marks clickhouse instances as built-in and defaults a missing projectId to null", () => {+ mockListSourceTypeDescriptors.mockReturnValue([+ {+ type: "clickhouse",+ displayName: "ClickHouse",+ declaredSignals: ["traces"],+ capabilities: {},+ correlation: {},+ configFields: [],+ },+ ]);+ registerDatasourceConnectorTypes();+ const { create } = mockRegisterConnectorType.mock.calls[0][0];++ const adapter = { healthCheck: jest.fn() };+ mockCreateAdapter.mockReturnValue(adapter);+ const result = create({+ id: "inst-1",+ type: "clickhouse",+ category: "datasource",+ name: "Primary",+ settings: { foo: "bar" },+ secretRef: "secret-1",+ });++ expect(result).toBe(adapter);+ const source = mockCreateAdapter.mock.calls[0][0];+ expect(source).toMatchObject({+ type: "clickhouse",+ id: "inst-1",+ isBuiltIn: true,+ settings: { foo: "bar" },+ secretRef: "secret-1",+ signals: ["traces"],+ projectId: null,+ name: "Primary",+ });+ });++ it("marks non-clickhouse instances as not built-in and preserves an explicit projectId", () => {+ mockListSourceTypeDescriptors.mockReturnValue([+ {+ type: "tempo",+ displayName: "Tempo",+ declaredSignals: ["traces"],+ capabilities: {},+ correlation: {},+ configFields: [],+ },+ ]);+ registerDatasourceConnectorTypes();+ const { create } = mockRegisterConnectorType.mock.calls[0][0];++ mockCreateAdapter.mockReturnValue({ healthCheck: jest.fn() });+ create({+ id: "inst-2",+ type: "tempo",+ category: "datasource",+ name: "Secondary",+ settings: {},+ projectId: "proj-9",+ environment: "production",+ });++ const source = mockCreateAdapter.mock.calls[0][0];+ expect(source).toMatchObject({+ isBuiltIn: false,+ projectId: "proj-9",+ environment: "production",+ });+ });++ it("throws when the adapter factory returns no adapter", () => {+ mockListSourceTypeDescriptors.mockReturnValue([+ {+ type: "tempo",+ displayName: "Tempo",+ declaredSignals: ["traces"],+ capabilities: {},+ correlation: {},+ configFields: [],+ },+ ]);+ registerDatasourceConnectorTypes();+ const { create } = mockRegisterConnectorType.mock.calls[0][0];++ mockCreateAdapter.mockReturnValue(undefined);+ expect(() =>+ create({+ id: "inst-3",+ type: "tempo",+ category: "datasource",+ name: "Missing",+ settings: {},+ })+ ).toThrow("Connector adapter unavailable: tempo");+ });+});diff --git a/src/client/src/__tests__/lib/platform/connectors/instances.test.ts b/src/client/src/__tests__/lib/platform/connectors/instances.test.tsnew file mode 100644index 00000000..f7130e80--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/instances.test.ts@@ -0,0 +1,326 @@+jest.mock("@/lib/prisma", () => ({+ __esModule: true,+ default: {+ connectorInstance: {+ upsert: jest.fn(),+ deleteMany: jest.fn(),+ findMany: jest.fn(),+ },+ databaseConfig: {+ findMany: jest.fn(),+ },+ telemetrySource: {+ findMany: jest.fn(),+ },+ },+}));++import prisma from "@/lib/prisma";+import {+ syncDatabaseConfigConnector,+ syncTelemetrySourceConnector,+ removeLegacyConnector,+ listProjectConnectorInstances,+} from "@/lib/platform/connectors/instances";+import type { DatabaseConfig, TelemetrySource } from "@prisma/client";++beforeEach(() => {+ jest.clearAllMocks();+});++const baseDatabaseConfig = {+ id: "db-1",+ username: "user",+ host: "localhost",+ port: 8123,+ database: "default",+ query: "",+ name: "My DB",+ environment: "production",+ projectId: "project-1",+} as unknown as DatabaseConfig;++const baseTelemetrySource = {+ id: "ts-1",+ type: "grafana",+ name: "My Source",+ environment: "production",+ projectId: "project-1",+ settings: '{"url":"http://x"}',+ secretRef: null,+ signals: "traces,logs",+ isDefault: false,+} as unknown as TelemetrySource;++describe("syncDatabaseConfigConnector", () => {+ it("upserts a connector using the database: prefix and default settings", async () => {+ (prisma.connectorInstance.upsert as jest.Mock).mockResolvedValue({});++ await syncDatabaseConfigConnector(baseDatabaseConfig);++ expect(prisma.connectorInstance.upsert).toHaveBeenCalledWith(+ expect.objectContaining({+ where: { id: "database:db-1" },+ create: expect.objectContaining({+ id: "database:db-1",+ category: "datasource",+ type: "clickhouse",+ name: "My DB",+ environment: "production",+ projectId: "project-1",+ status: "active",+ }),+ update: expect.objectContaining({+ name: "My DB",+ environment: "production",+ projectId: "project-1",+ status: "active",+ }),+ })+ );+ const call = (prisma.connectorInstance.upsert as jest.Mock).mock.calls[0][0];+ const settings = JSON.parse(call.create.settings);+ expect(settings).toEqual({+ username: "user",+ host: "localhost",+ port: 8123,+ database: "default",+ query: "",+ });+ });++ it("defaults environment to production when missing", async () => {+ (prisma.connectorInstance.upsert as jest.Mock).mockResolvedValue({});+ await syncDatabaseConfigConnector({+ ...baseDatabaseConfig,+ environment: "" as any,+ });+ const call = (prisma.connectorInstance.upsert as jest.Mock).mock.calls[0][0];+ expect(call.create.environment).toBe("production");+ expect(call.update.environment).toBe("production");+ });++ it("defaults query to an empty string when not set", async () => {+ (prisma.connectorInstance.upsert as jest.Mock).mockResolvedValue({});+ await syncDatabaseConfigConnector({+ ...baseDatabaseConfig,+ query: null as any,+ });+ const call = (prisma.connectorInstance.upsert as jest.Mock).mock.calls[0][0];+ const settings = JSON.parse(call.create.settings);+ expect(settings.query).toBe("");+ });+});++describe("syncTelemetrySourceConnector", () => {+ it("upserts a connector using the telemetry: prefix", async () => {+ (prisma.connectorInstance.upsert as jest.Mock).mockResolvedValue({});++ await syncTelemetrySourceConnector(baseTelemetrySource);++ expect(prisma.connectorInstance.upsert).toHaveBeenCalledWith(+ expect.objectContaining({+ where: { id: "telemetry:ts-1" },+ create: expect.objectContaining({+ id: "telemetry:ts-1",+ category: "datasource",+ type: "grafana",+ name: "My Source",+ environment: "production",+ projectId: "project-1",+ settings: '{"url":"http://x"}',+ secretRef: null,+ status: "active",+ }),+ update: expect.objectContaining({+ type: "grafana",+ name: "My Source",+ settings: '{"url":"http://x"}',+ }),+ })+ );+ });++ it("defaults environment to production and settings to {} when missing", async () => {+ (prisma.connectorInstance.upsert as jest.Mock).mockResolvedValue({});+ await syncTelemetrySourceConnector({+ ...baseTelemetrySource,+ environment: "" as any,+ settings: "" as any,+ });+ const call = (prisma.connectorInstance.upsert as jest.Mock).mock.calls[0][0];+ expect(call.create.environment).toBe("production");+ expect(call.create.settings).toBe("{}");+ expect(call.update.environment).toBe("production");+ expect(call.update.settings).toBe("{}");+ });++ it("embeds signals and isDefault flags in metadata", async () => {+ (prisma.connectorInstance.upsert as jest.Mock).mockResolvedValue({});+ await syncTelemetrySourceConnector({+ ...baseTelemetrySource,+ signals: "metrics",+ isDefault: true,+ });+ const call = (prisma.connectorInstance.upsert as jest.Mock).mock.calls[0][0];+ const metadata = JSON.parse(call.create.metadata);+ expect(metadata).toEqual(+ expect.objectContaining({+ legacyKind: "telemetry-source",+ legacyId: "ts-1",+ signals: "metrics",+ isDefault: true,+ })+ );+ });+});++describe("removeLegacyConnector", () => {+ it("deletes using the database: prefix for database-config kind", async () => {+ (prisma.connectorInstance.deleteMany as jest.Mock).mockResolvedValue({});+ await removeLegacyConnector("database-config", "db-1");+ expect(prisma.connectorInstance.deleteMany).toHaveBeenCalledWith({+ where: { id: "database:db-1" },+ });+ });++ it("deletes using the telemetry: prefix for telemetry-source kind", async () => {+ (prisma.connectorInstance.deleteMany as jest.Mock).mockResolvedValue({});+ await removeLegacyConnector("telemetry-source", "ts-1");+ expect(prisma.connectorInstance.deleteMany).toHaveBeenCalledWith({+ where: { id: "telemetry:ts-1" },+ });+ });+});++describe("listProjectConnectorInstances", () => {+ beforeEach(() => {+ (prisma.databaseConfig.findMany as jest.Mock).mockResolvedValue([]);+ (prisma.telemetrySource.findMany as jest.Mock).mockResolvedValue([]);+ (prisma.connectorInstance.upsert as jest.Mock).mockResolvedValue({});+ });++ it("backfills connectors from database configs and telemetry sources before reading", async () => {+ (prisma.databaseConfig.findMany as jest.Mock).mockResolvedValue([baseDatabaseConfig]);+ (prisma.telemetrySource.findMany as jest.Mock).mockResolvedValue([baseTelemetrySource]);+ (prisma.connectorInstance.findMany as jest.Mock).mockResolvedValue([]);++ await listProjectConnectorInstances("project-1");++ expect(prisma.connectorInstance.upsert).toHaveBeenCalledTimes(2);+ expect(prisma.connectorInstance.findMany).toHaveBeenCalledWith(+ expect.objectContaining({ where: { projectId: "project-1" } })+ );+ });++ it("gives clickhouse datasource connectors the fixed signal set", async () => {+ (prisma.connectorInstance.findMany as jest.Mock).mockResolvedValue([+ {+ id: "database:db-1",+ category: "datasource",+ type: "clickhouse",+ metadata: JSON.stringify({ legacyKind: "database-config" }),+ secretRef: null,+ },+ ]);++ const result = await listProjectConnectorInstances("project-1");+ expect(result[0].signals).toBe("traces,logs,metrics,intelligence");+ expect(result[0].isDefault).toBe(false);+ expect(result[0].hasSecret).toBe(false);+ });++ it("falls back to metadata.signals for non-clickhouse datasource connectors", async () => {+ (prisma.connectorInstance.findMany as jest.Mock).mockResolvedValue([+ {+ id: "telemetry:ts-1",+ category: "datasource",+ type: "grafana",+ metadata: JSON.stringify({ signals: "metrics", isDefault: true }),+ secretRef: "secret-1",+ },+ ]);++ const result = await listProjectConnectorInstances("project-1");+ expect(result[0].signals).toBe("metrics");+ expect(result[0].isDefault).toBe(true);+ expect(result[0].hasSecret).toBe(true);+ });++ it("defaults to traces,logs,metrics when metadata has no signals for non-clickhouse connectors", async () => {+ (prisma.connectorInstance.findMany as jest.Mock).mockResolvedValue([+ {+ id: "telemetry:ts-2",+ category: "datasource",+ type: "loki",+ metadata: "{}",+ secretRef: null,+ },+ ]);++ const result = await listProjectConnectorInstances("project-1");+ expect(result[0].signals).toBe("traces,logs,metrics");+ });++ it("gives non-datasource connectors an empty signals string and no default flag", async () => {+ (prisma.connectorInstance.findMany as jest.Mock).mockResolvedValue([+ {+ id: "connector-1",+ category: "memory",+ type: "custom-memory",+ metadata: JSON.stringify({ isDefault: true }),+ secretRef: null,+ },+ ]);++ const result = await listProjectConnectorInstances("project-1");+ expect(result[0].signals).toBe("");+ expect(result[0].isDefault).toBe(false);+ });++ it("tolerates malformed metadata JSON and keeps sensible defaults", async () => {+ (prisma.connectorInstance.findMany as jest.Mock).mockResolvedValue([+ {+ id: "connector-1",+ category: "datasource",+ type: "grafana",+ metadata: "{not-json",+ secretRef: null,+ },+ ]);++ const result = await listProjectConnectorInstances("project-1");+ expect(result[0].signals).toBe("traces,logs,metrics");+ expect(result[0].isDefault).toBe(false);+ });++ it("treats metadata that parses to null (JSON \"null\") as an empty object", async () => {+ (prisma.connectorInstance.findMany as jest.Mock).mockResolvedValue([+ {+ id: "connector-1",+ category: "datasource",+ type: "grafana",+ metadata: "null",+ secretRef: null,+ },+ ]);++ const result = await listProjectConnectorInstances("project-1");+ expect(result[0].signals).toBe("traces,logs,metrics");+ });++ it("treats a null metadata field as an empty object", async () => {+ (prisma.connectorInstance.findMany as jest.Mock).mockResolvedValue([+ {+ id: "connector-1",+ category: "datasource",+ type: "grafana",+ metadata: null,+ secretRef: null,+ },+ ]);++ const result = await listProjectConnectorInstances("project-1");+ expect(result[0].signals).toBe("traces,logs,metrics");+ });+});diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-adapters.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-adapters.test.tsindex 4a8723e5..3ad1b21e 100644--- a/src/client/src/__tests__/lib/platform/connectors/memory-adapters.test.ts+++ b/src/client/src/__tests__/lib/platform/connectors/memory-adapters.test.ts@@ -28,6 +28,7 @@ import { ClaudeAdapter, claudeAdapterFactory } from "@/lib/platform/connectors/mimport { Mem0Adapter, mem0AdapterFactory } from "@/lib/platform/connectors/memory/mem0/adapter";import { ZepAdapter, zepAdapterFactory } from "@/lib/platform/connectors/memory/zep/adapter";import { SourceResponseError } from "@/lib/platform/connectors/datasource/http/safe-fetch";+import { resolveSourceSecret } from "@/lib/platform/connectors/datasource/http/secret";import type { MemorySourceDescriptor } from "@/lib/platform/connectors/memory/types";function defaultUrl(type: "claude" | "mem0" | "zep"): string {@@ -338,559 +339,2093 @@ describe("Mem0 adapter", () => {}));});-});-describe("Zep adapter", () => {- it("describes graph get and session add capabilities", () => {- const described = zepAdapterFactory.describe();- expect(described.type).toBe("zep");- expect(described.capabilities.get).toBe(true);- expect(described.capabilities.feedback).toBe(false);- expect(described.capabilities.update).toBe(false);- expect(described.configFields.map((field) => field.key)).toEqual(- expect.arrayContaining(["url", "apiKey"])- );- expect(described.filterFields?.map((field) => field.key)).toEqual([- "userId",- "sessionId",- ]);- expect(described.filterFields?.[0]).toMatchObject({- key: "userId",- required: true,- allowCustom: true,- });- expect(described.filterFields?.[1]).toMatchObject({- key: "sessionId",- writeRequired: true,- allowCustom: true,+ it("exposes capabilities directly on the adapter instance", () => {+ const adapter = new Mem0Adapter(descriptor("mem0"));+ expect(adapter.capabilities()).toEqual({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: true,});});- it("health-checks users with Api-Key auth", async () => {- mockSafeFetch.mockResolvedValue({ users: [] });- const adapter = new ZepAdapter(descriptor("zep"));+ it("reports an unhealthy connection when the entities call fails", async () => {+ mockSafeFetch.mockRejectedValue(new Error("boom"));+ const adapter = new Mem0Adapter(descriptor("mem0"));await expect(adapter.healthCheck()).resolves.toEqual(- expect.objectContaining({ ok: true })+ expect.objectContaining({ ok: false, message: expect.stringContaining("boom") }));- const [url, options] = mockSafeFetch.mock.calls[0];- expect(String(url)).toContain("https://api.getzep.com/api/v2/users-ordered");- expect(options.headers.Authorization).toBe("Api-Key secret-key");});- it("adds session memory and requires a session id", async () => {- const adapter = new ZepAdapter(descriptor("zep"));- await expect(adapter.add({ content: "hello" })).rejects.toThrow(/session id/i);+ it("rejects adding a memory with no content or messages", async () => {+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.add({})).rejects.toThrow(/content/i);+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("adds a memory from an explicit messages array", async () => {mockSafeFetch.mockResolvedValue({- facts: [{ uuid: "f1", fact: "User likes tea" }],- messages: [{ uuid: "m1", content: "hello", role: "user", session_id: "s1" }],+ results: [{ id: "mem-2", memory: "hi there" }],});- const records = await adapter.add({ content: "hello", sessionId: "s1" });- expect(records[0]).toEqual(+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await adapter.add({+ messages: [{ role: "user", content: "hi there" }],+ userId: "u1",+ });+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(JSON.parse(options.body)).toEqual(expect.objectContaining({- id: "f1",- content: "User likes tea",- sessionId: "s1",- input: [{ role: "user", content: "hello" }],+ messages: [{ role: "user", content: "hi there" }],}));- expect(String(mockSafeFetch.mock.calls[0][0])).toContain(- "/api/v2/threads/s1/messages"+ });++ it("normalizes a bare array response and a single-object response", async () => {+ mockSafeFetch.mockResolvedValue([{ id: "mem-1", memory: "tea" }]);+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.search({ query: "tea" })).resolves.toEqual([+ expect.objectContaining({ id: "mem-1", content: "tea" }),+ ]);++ mockSafeFetch.mockResolvedValue({ id: "mem-1", memory: "tea", user_id: "u1" });+ await expect(adapter.search({ query: "tea" })).resolves.toEqual([+ expect.objectContaining({ id: "mem-1", content: "tea", userId: "u1" }),+ ]);+ });++ it("falls back to the text field and nested data when memory is missing", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) return [];+ return { data: { id: "mem-9", text: "nested content" } };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-9")).resolves.toEqual(+ expect.objectContaining({ id: "mem-9", content: "nested content" }));});- it("does not list until a user or session is provided", async () => {- const adapter = new ZepAdapter(descriptor("zep"));- await expect(adapter.list({})).rejects.toThrow(/user, agent, or session/i);- expect(mockSafeFetch).not.toHaveBeenCalled();+ it("reads history wrapped in a results or history envelope", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) {+ return { results: [{ id: "h1", event: "ADD", new_memory: "hi" }] };+ }+ return { id: "mem-1", memory: "hi" };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-1")).resolves.toEqual(+ expect.objectContaining({+ history: [expect.objectContaining({ id: "h1", event: "ADD" })],+ })+ );++ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) {+ return { history: [{ id: "h2", event: "UPDATE", new_memory: "hi2" }] };+ }+ return { id: "mem-1", memory: "hi2" };+ });+ await expect(adapter.get("mem-1")).resolves.toEqual(+ expect.objectContaining({+ history: [expect.objectContaining({ id: "h2", event: "UPDATE" })],+ })+ );});- it("lists user graph facts from a raw edge array", async () => {+ it("lists entities from a bare array response", async () => {mockSafeFetch.mockResolvedValue([- {- uuid: "e1",- fact: "Ada prefers TypeScript",- name: "PREFERS",- created_at: "2026-08-16T00:00:00Z",- },+ { id: "e1", name: "ada", type: "user", email: "[email protected]" },]);- const adapter = new ZepAdapter(descriptor("zep"));- await expect(adapter.list({ userId: "ada" })).resolves.toEqual([+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [{ id: "ada", label: "[email protected]" }],+ sessions: [],+ agents: [],+ });+ });++ it("lists entities keyed by owner and falls back to an entities array", async () => {+ mockSafeFetch.mockResolvedValue({+ entities: [+ { owner: "agent", run_id: "run-9" },+ { id: "no-name-user" },+ ],+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [{ id: "no-name-user", label: "no-name-user" }],+ sessions: [],+ agents: [{ id: "run-9", label: "run-9" }],+ });+ });++ it("returns empty filters when listing entities fails", async () => {+ mockSafeFetch.mockRejectedValue(new Error("entities unavailable"));+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [],+ sessions: [],+ agents: [],+ });+ });++ it("updates a memory and normalizes the response", async () => {+ mockSafeFetch.mockResolvedValue({ id: "mem-1", memory: "Prefers spaces" });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(+ adapter.update("mem-1", { content: "Prefers spaces" })+ ).resolves.toEqual(expect.objectContaining({ id: "mem-1", content: "Prefers spaces" }));+ const [url, options] = mockSafeFetch.mock.calls[0];+ expect(String(url)).toBe("https://api.mem0.ai/v1/memories/mem-1/");+ expect(options.method).toBe("PUT");+ });++ it("falls back to the input payload when an update response cannot be normalized", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(+ adapter.update("mem-1", { content: "Prefers spaces" })+ ).resolves.toEqual({ id: "mem-1", content: "Prefers spaces", metadata: undefined });+ });++ it("deletes a memory through the slash-aware request helper", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await adapter.delete("mem-1");+ expect(String(mockSafeFetch.mock.calls[0][0])).toBe(+ "https://api.mem0.ai/v1/memories/mem-1/"+ );+ expect(mockSafeFetch.mock.calls[0][1].method).toBe("DELETE");+ });++ it("builds fallback feedback when the vendor response omits it", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(+ adapter.feedback("mem-1", { rating: "positive" })+ ).resolves.toEqual({ rating: "positive" });+ await expect(+ adapter.feedback("mem-1", { rating: null, reason: "Outdated" })+ ).resolves.toEqual({ reason: "Outdated" });+ });++ it("rejects an empty search query", async () => {+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.search({ query: " " })).rejects.toThrow(/query/i);+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("rejects feedback for a blank memory id", async () => {+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.feedback(" ", { rating: "positive" })).rejects.toThrow();+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("normalizes messages using the text field, defaults the role, and skips blank items", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) return [];+ return {+ id: "mem-1",+ memory: "hello",+ messages: [{}, { text: "fallback text" }],+ };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-1")).resolves.toEqual(expect.objectContaining({- id: "e1",- content: "Ada prefers TypeScript",- userId: "ada",- }),- ]);+ input: [{ role: "user", content: "fallback text" }],+ })+ );});- it("maps edge endpoints and keeps entity nodes off the memory list", async () => {+ it("normalizes history rows using action/newMemory aliases, history_id, and default event", async () => {mockSafeFetch.mockImplementation(async (url: string) => {- if (String(url).includes("/graph/edge/user/")) {+ if (String(url).includes("/history")) {return [- {- uuid: "e1",- fact: "Sarah lives in Austin",- name: "LIVES_IN",- source_node_uuid: "n-user",- target_node_uuid: "n-loc",- source_node_name: "Sarah Smith",- target_node_name: "Austin",- source_node_labels: ["User"],- target_node_labels: ["Location"],- },+ {},+ { history_id: "h1", action: "restored", newMemory: "hi again" },];}- if (String(url).includes("/graph/node/user/")) {+ return { id: "mem-1", memory: "hi again" };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-1")).resolves.toEqual(+ expect.objectContaining({+ history: [+ expect.objectContaining({+ id: "h1",+ event: "restored",+ newMemory: "hi again",+ }),+ ],+ })+ );+ });++ it("resolves input from history when the record has no direct input", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) {return [{- uuid: "n-topic",- name: "Observability",- summary: "Talks about tracing",- labels: ["Topic"],+ event: "ADD",+ input: [{ role: "user", content: "from history" }],},];}- throw new Error(`unexpected ${url}`);+ return { memory: "hello there" };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-1")).resolves.toEqual(+ expect.objectContaining({+ id: "hello there",+ input: [{ role: "user", content: "from history" }],+ })+ );+ });++ it("returns an empty list when a search result cannot be normalized", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.search({ query: "tea" })).resolves.toEqual([]);+ });++ it("deduplicates entity choices and skips the app entity type", async () => {+ mockSafeFetch.mockResolvedValue({+ results: [+ { id: "e1", name: "ada", type: "user", email: "[email protected]" },+ { id: "e1", name: "ada", type: "user", email: "[email protected]" },+ { name: "billing-app", type: "app" },+ {},+ ],+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [{ id: "ada", label: "[email protected]" }],+ sessions: [],+ agents: [],+ });+ });++ it("returns empty entity rows when the response has no recognizable shape", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [],+ sessions: [],+ agents: [],+ });+ });++ it("defaults the list page size when no limit is provided", async () => {+ mockSafeFetch.mockResolvedValue({ results: [] });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await adapter.list({ userId: "u1" });+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain("page_size=25");+ });++ it("scopes requests to an org and project when configured", async () => {+ mockSafeFetch.mockResolvedValue({ results: [] });+ const adapter = new Mem0Adapter(+ descriptor("mem0", { orgId: "org-1", projectId: "proj-1" })+ );+ await adapter.listFilters();+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain("org_id=org-1");+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain("project_id=proj-1");++ await adapter.search({ query: "tea" });+ expect(JSON.parse(mockSafeFetch.mock.calls[1][1].body)).toEqual(+ expect.objectContaining({ org_id: "org-1", project_id: "proj-1" })+ );+ });++ it("rejects adding a memory when content is only whitespace", async () => {+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.add({ content: " " })).rejects.toThrow(/content/i);+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("falls back to content for the id when the vendor id is only whitespace", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) return [];+ return { id: " ", memory: "hello" };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-1")).resolves.toEqual(+ expect.objectContaining({ id: "hello", content: "hello" })+ );+ });++ it("captures a boolean synthesized flag on the record", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) return [];+ return { id: "mem-1", memory: "hello", synthesized: true };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-1")).resolves.toEqual(+ expect.objectContaining({ synthesized: true })+ );+ });++ it("captures feedback with only a rating, and separately with only a reason", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) return [];+ return { id: "mem-1", memory: "hello", feedback: "POSITIVE" };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-1")).resolves.toEqual(+ expect.objectContaining({ feedback: { rating: "positive" } })+ );++ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) return [];+ return { id: "mem-2", memory: "hello again", feedback_reason: "Just because" };+ });+ await expect(adapter.get("mem-2")).resolves.toEqual(+ expect.objectContaining({ feedback: { reason: "Just because" } })+ );+ });++ it("defaults history events to UPDATE when the row lacks an explicit event", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) {+ return [{ new_memory: "no event field" }];+ }+ return { id: "mem-1", memory: "hello" };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-1")).resolves.toEqual(+ expect.objectContaining({+ history: [+ expect.objectContaining({ event: "UPDATE", newMemory: "no event field" }),+ ],+ })+ );+ });++ it("retries without a trailing slash when the redirect error is not an Error instance", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ const href = String(url);+ if (href.endsWith("/mem-1/")) {+ throw "exceeded the maximum number of redirects";+ }+ return { id: "mem-1", memory: "hello" };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(+ adapter.update("mem-1", { content: "hello" })+ ).resolves.toEqual(expect.objectContaining({ id: "mem-1", content: "hello" }));+ expect(String(mockSafeFetch.mock.calls[1][0])).toBe(+ "https://api.mem0.ai/v1/memories/mem-1"+ );+ });++ it("falls back to secret.raw for the Authorization header when credentials lack an apiKey", async () => {+ (resolveSourceSecret as jest.Mock).mockResolvedValueOnce({+ raw: "raw-secret",+ credentials: {},+ });+ mockSafeFetch.mockResolvedValue({ results: [] });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await adapter.healthCheck();+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(options.headers.Authorization).toBe("Token raw-secret");+ });++ it("omits the Authorization header when the secret has no usable value", async () => {+ (resolveSourceSecret as jest.Mock).mockResolvedValueOnce({+ raw: "",+ credentials: {},+ });+ mockSafeFetch.mockResolvedValue({ results: [] });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await adapter.healthCheck();+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(options.headers.Authorization).toBeUndefined();+ });++ it("uses the raw rejection value as the message when it has no .message property", async () => {+ mockSafeFetch.mockRejectedValue("entities down");+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.healthCheck()).resolves.toEqual(+ expect.objectContaining({ ok: false, message: "entities down" })+ );+ });+});++describe("Zep adapter", () => {+ it("describes graph get and session add capabilities", () => {+ const described = zepAdapterFactory.describe();+ expect(described.type).toBe("zep");+ expect(described.capabilities.get).toBe(true);+ expect(described.capabilities.feedback).toBe(false);+ expect(described.capabilities.update).toBe(false);+ expect(described.configFields.map((field) => field.key)).toEqual(+ expect.arrayContaining(["url", "apiKey"])+ );+ expect(described.filterFields?.map((field) => field.key)).toEqual([+ "userId",+ "sessionId",+ ]);+ expect(described.filterFields?.[0]).toMatchObject({+ key: "userId",+ required: true,+ allowCustom: true,+ });+ expect(described.filterFields?.[1]).toMatchObject({+ key: "sessionId",+ writeRequired: true,+ allowCustom: true,+ });+ });++ it("health-checks users with Api-Key auth", async () => {+ mockSafeFetch.mockResolvedValue({ users: [] });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.healthCheck()).resolves.toEqual(+ expect.objectContaining({ ok: true })+ );+ const [url, options] = mockSafeFetch.mock.calls[0];+ expect(String(url)).toContain("https://api.getzep.com/api/v2/users-ordered");+ expect(options.headers.Authorization).toBe("Api-Key secret-key");+ });++ it("adds session memory and requires a session id", async () => {+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.add({ content: "hello" })).rejects.toThrow(/session id/i);+ mockSafeFetch.mockResolvedValue({+ facts: [{ uuid: "f1", fact: "User likes tea" }],+ messages: [{ uuid: "m1", content: "hello", role: "user", session_id: "s1" }],+ });+ const records = await adapter.add({ content: "hello", sessionId: "s1" });+ expect(records[0]).toEqual(+ expect.objectContaining({+ id: "f1",+ content: "User likes tea",+ sessionId: "s1",+ input: [{ role: "user", content: "hello" }],+ })+ );+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain(+ "/api/v2/threads/s1/messages"+ );+ });++ it("does not list until a user or session is provided", async () => {+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.list({})).rejects.toThrow(/user, agent, or session/i);+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("lists user graph facts from a raw edge array", async () => {+ mockSafeFetch.mockResolvedValue([+ {+ uuid: "e1",+ fact: "Ada prefers TypeScript",+ name: "PREFERS",+ created_at: "2026-08-16T00:00:00Z",+ },+ ]);+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.list({ userId: "ada" })).resolves.toEqual([+ expect.objectContaining({+ id: "e1",+ content: "Ada prefers TypeScript",+ userId: "ada",+ }),+ ]);+ });++ it("maps edge endpoints and keeps entity nodes off the memory list", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/user/")) {+ return [+ {+ uuid: "e1",+ fact: "Sarah lives in Austin",+ name: "LIVES_IN",+ source_node_uuid: "n-user",+ target_node_uuid: "n-loc",+ source_node_name: "Sarah Smith",+ target_node_name: "Austin",+ source_node_labels: ["User"],+ target_node_labels: ["Location"],+ },+ ];+ }+ if (String(url).includes("/graph/node/user/")) {+ return [+ {+ uuid: "n-topic",+ name: "Observability",+ summary: "Talks about tracing",+ labels: ["Topic"],+ },+ ];+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ userId: "ada" });+ expect(records).toEqual([+ expect.objectContaining({+ id: "e1",+ relation: {+ source: {+ id: "n-user",+ label: "Sarah Smith",+ types: ["User"],+ },+ target: {+ id: "n-loc",+ label: "Austin",+ types: ["Location"],+ },+ name: "LIVES_IN",+ },+ }),+ expect.objectContaining({+ id: "n-topic",+ graphOnly: true,+ categories: ["Topic"],+ }),+ ]);+ });++ it("falls back to /users and /sessions when ordered/thread endpoints are missing", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/users-ordered") || String(url).includes("/threads")) {+ throw new Error("not found");+ }+ if (String(url).includes("/users")) {+ return { users: [{ user_id: "ada", email: "[email protected]" }] };+ }+ return { sessions: [{ session_id: "s1", user_id: "ada" }] };+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [{ id: "ada", label: "[email protected]" }],+ sessions: [{ id: "s1", label: "s1", userId: "ada" }],+ agents: [],+ });+ });++ it("lists user graph facts and falls back to nodes", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/user/")) {+ return {+ edges: [+ {+ uuid: "e1",+ fact: "Ada prefers TypeScript",+ name: "PREFERS",+ created_at: "2026-08-16T00:00:00Z",+ },+ ],+ };+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.list({ userId: "ada" })).resolves.toEqual([+ expect.objectContaining({+ id: "e1",+ content: "Ada prefers TypeScript",+ userId: "ada",+ categories: ["PREFERS"],+ }),+ ]);+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain(+ "/api/v2/graph/edge/user/ada"+ );+ });++ it("lists the user graph even when a session is selected", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/user/ada")) {+ return [{ uuid: "e1", fact: "Ada prefers TypeScript", created_at: "2026-08-16T00:00:00Z" }];+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ sessionId: "s1", userId: "ada" });+ expect(records).toEqual([+ expect.objectContaining({+ id: "e1",+ content: "Ada prefers TypeScript",+ userId: "ada",+ }),+ ]);+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain(+ "/api/v2/graph/edge/user/ada"+ );+ });++ it("resolves the thread user then lists that user's graph", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/threads/s1/messages")) {+ return { messages: [], user_id: "ada" };+ }+ if (String(url).includes("/graph/edge/user/ada")) {+ return [{ uuid: "e1", fact: "Ada prefers TypeScript" }];+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ sessionId: "s1" });+ expect(records).toEqual([+ expect.objectContaining({ id: "e1", userId: "ada" }),+ ]);+ });++ it("gets a fact by graph edge uuid and falls back to nodes", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/")) {+ throw new Error("not found");+ }+ if (String(url).includes("/graph/node/")) {+ return {+ uuid: "n1",+ name: "Ada",+ summary: "Engineer who drinks tea",+ labels: ["user"],+ attributes: { role: "engineer" },+ };+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.get("n1")).resolves.toEqual(+ expect.objectContaining({+ id: "n1",+ content: "Engineer who drinks tea",+ categories: ["user"],+ structuredAttributes: { role: "engineer" },+ })+ );+ });++ it("attaches changelog and source episodes when getting an edge", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/e1") && !String(url).includes("/user/")) {+ return {+ uuid: "e1",+ fact: "The Enterprise Sandbox Tier 3 plan is Active.",+ name: "HAS_PLAN",+ created_at: "2026-08-17T00:00:00Z",+ valid_at: "2026-08-17T01:00:00Z",+ episodes: ["ep-1"],+ };+ }+ if (String(url).includes("/graph/episodes/ep-1")) {+ return { uuid: "ep-1", content: "Our plan is active", role: "user" };+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.get("e1")).resolves.toEqual(+ expect.objectContaining({+ id: "e1",+ input: [{ role: "user", content: "Our plan is active" }],+ history: [+ expect.objectContaining({+ event: "ADD",+ createdAt: "2026-08-17T00:00:00Z",+ }),+ expect.objectContaining({+ event: "UPDATE",+ createdAt: "2026-08-17T01:00:00Z",+ }),+ ],+ })+ );+ });++ it("gets thread context when the id is not a graph uuid", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/") || String(url).includes("/graph/node/")) {+ throw new Error("not found");+ }+ if (String(url).includes("/threads/s1/context")) {+ return { context: "Ada likes tea.", messages: [{ role: "user", content: "I like tea" }] };+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.get("s1")).resolves.toEqual(+ expect.objectContaining({+ id: "s1",+ content: "Ada likes tea.",+ input: [{ role: "user", content: "I like tea" }],+ })+ );+ });++ it("pages user graph edges with uuid_cursor", async () => {+ mockSafeFetch.mockImplementation(async (url: string, options?: { body?: string }) => {+ if (!String(url).includes("/graph/edge/user/ada")) {+ throw new Error(`unexpected ${url}`);+ }+ const body = JSON.parse(String(options?.body || "{}")) as { uuid_cursor?: string };+ if (!body.uuid_cursor) {+ return Array.from({ length: 50 }, (_, index) => ({+ uuid: `e${index}`,+ fact: `Fact ${index}`,+ }));+ }+ return [{ uuid: "e50", fact: "Fact 50" }];+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ userId: "ada", limit: 51 });+ expect(records).toHaveLength(51);+ expect(records[50]?.id).toBe("e50");+ expect(JSON.parse(String(mockSafeFetch.mock.calls[1][1].body)).uuid_cursor).toBe("e49");+ });++ it("deletes a graph edge instead of the whole session", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new ZepAdapter(descriptor("zep"));+ await adapter.delete("e1");+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain("/api/v2/graph/edge/e1");+ expect(mockSafeFetch.mock.calls[0][1].method).toBe("DELETE");+ });++ it("lists users and threads for filter dropdowns", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/users-ordered") || String(url).includes("/users")) {+ return { users: [{ user_id: "ada", email: "[email protected]" }] };+ }+ if (String(url).includes("/threads")) {+ return { threads: [{ thread_id: "s1", user_id: "ada" }] };+ }+ return { sessions: [{ session_id: "s1", user_id: "ada" }] };+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [{ id: "ada", label: "[email protected]" }],+ sessions: [{ id: "s1", label: "s1", userId: "ada" }],+ agents: [],+ });+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain("/api/v2/users-ordered");+ expect(String(mockSafeFetch.mock.calls[1][0])).toContain("/api/v2/threads");+ });++ it("exposes capabilities directly on the adapter instance", () => {+ const adapter = new ZepAdapter(descriptor("zep"));+ expect(adapter.capabilities()).toEqual({+ add: true,+ search: true,+ get: true,+ list: true,+ update: false,+ delete: true,+ feedback: false,+ });+ });++ it("reports an unhealthy connection when both user endpoints fail", async () => {+ mockSafeFetch.mockRejectedValue(new Error("network down"));+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.healthCheck()).resolves.toEqual(+ expect.objectContaining({ ok: false, message: expect.stringContaining("network down") })+ );+ });++ it("adds session memory from an explicit messages array", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new ZepAdapter(descriptor("zep"));+ await adapter.add({+ sessionId: "s1",+ messages: [{ role: "assistant", content: "hi there" }],+ });+ expect(JSON.parse(mockSafeFetch.mock.calls[0][1].body)).toEqual(+ expect.objectContaining({+ messages: [{ role: "assistant", content: "hi there" }],+ })+ );+ });++ it("requires content or messages when adding session memory", async () => {+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.add({ sessionId: "s1" })).rejects.toThrow(/content/i);+ });++ it("falls back to a synthesized record when the add response has no facts", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.add({ content: "hello there", sessionId: "s1" });+ expect(records).toEqual([+ expect.objectContaining({+ id: "s1",+ content: "hello there",+ sessionId: "s1",+ }),+ ]);+ });++ it("searches session memory and falls through to graph search on failure without a user", async () => {+ mockSafeFetch.mockResolvedValue({+ facts: [{ uuid: "f1", fact: "Ada prefers tea" }],+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(+ adapter.search({ query: "tea", sessionId: "s1" })+ ).resolves.toEqual([expect.objectContaining({ id: "f1" })]);+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain("/sessions/s1/search");+ });++ it("rejects an empty search query", async () => {+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.search({ query: " ", userId: "ada" })).rejects.toThrow(+ /query/i+ );+ });++ it("rethrows the session search error when no user id is available to fall back on", async () => {+ mockSafeFetch.mockRejectedValue(new Error("session search failed"));+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(+ adapter.search({ query: "tea", sessionId: "s1" })+ ).rejects.toThrow("session search failed");+ });++ it("falls back to graph search when session search fails but a user id is present", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/sessions/")) throw new Error("no session memory");+ if (String(url).includes("/graph/search")) {+ return { facts: [{ uuid: "f2", fact: "Ada prefers coffee" }] };+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(+ adapter.search({ query: "coffee", sessionId: "s1", userId: "ada" })+ ).resolves.toEqual([expect.objectContaining({ id: "f2" })]);+ });++ it("searches the user graph directly when no session id is given", async () => {+ mockSafeFetch.mockResolvedValue({+ facts: [{ uuid: "f3", fact: "Ada prefers dark mode" }],+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(+ adapter.search({ query: "dark mode", userId: "ada" })+ ).resolves.toEqual([expect.objectContaining({ id: "f3" })]);+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain("/graph/search");+ });++ it("treats string labels and single relevance scores as valid record fields", async () => {+ mockSafeFetch.mockResolvedValue([+ {+ uuid: "e1",+ fact: "Ada prefers TypeScript",+ labels: "Preference",+ relevance: 0.42,+ },+ ]);+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ userId: "ada" });+ expect(records[0]).toEqual(+ expect.objectContaining({+ id: "e1",+ categories: ["Preference"],+ score: 0.42,+ })+ );+ });++ it("labels relation endpoints with their raw id when no name is present", async () => {+ mockSafeFetch.mockResolvedValue([+ {+ uuid: "e1",+ fact: "Sarah lives in Austin",+ source_node_uuid: "n-user",+ target_node_uuid: "n-loc",+ },+ ]);+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ userId: "ada" });+ expect(records[0].relation).toEqual(+ expect.objectContaining({+ source: expect.objectContaining({ id: "n-user", label: "n-user" }),+ target: expect.objectContaining({ id: "n-loc", label: "n-loc" }),+ })+ );+ });++ it("falls back to raw session messages when there are no facts or context", async () => {+ mockSafeFetch.mockResolvedValue({+ messages: [{ uuid: "m1", role: "user", content: "hello there" }],+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ sessionId: "s1" });+ expect(records).toEqual([+ expect.objectContaining({+ id: "s1:0",+ content: "hello there",+ sessionId: "s1",+ metadata: { role: "user", memory_type: "temporal" },+ }),+ ]);+ });++ it("normalizes session listFilters ids from a bare uuid", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/users")) return { users: [] };+ return { sessions: [{ uuid: "s9" }] };+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.listFilters()).resolves.toEqual(+ expect.objectContaining({ sessions: [{ id: "s9", label: "s9" }] })+ );+ });++ it("marks a graph edge deleted via invalid_at and falls back to expired_at", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/e1") && !String(url).includes("/user/")) {+ return {+ uuid: "e1",+ fact: "The plan lapsed",+ created_at: "2026-08-17T00:00:00Z",+ invalid_at: "2026-08-18T00:00:00Z",+ };+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.get("e1")).resolves.toEqual(+ expect.objectContaining({+ history: expect.arrayContaining([+ expect.objectContaining({ event: "DELETE", createdAt: "2026-08-18T00:00:00Z" }),+ ]),+ })+ );++ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/e2") && !String(url).includes("/user/")) {+ return {+ uuid: "e2",+ fact: "The plan expired",+ created_at: "2026-08-17T00:00:00Z",+ expired_at: "2026-08-19T00:00:00Z",+ };+ }+ throw new Error(`unexpected ${url}`);+ });+ await expect(adapter.get("e2")).resolves.toEqual(+ expect.objectContaining({+ history: expect.arrayContaining([+ expect.objectContaining({ event: "DELETE", createdAt: "2026-08-19T00:00:00Z" }),+ ]),+ })+ );+ });++ it("breaks user-graph pagination when a later page request fails", async () => {+ mockSafeFetch.mockImplementation(async (url: string, options?: { body?: string }) => {+ if (!String(url).includes("/graph/edge/user/ada")) {+ throw new Error(`unexpected ${url}`);+ }+ const body = JSON.parse(String(options?.body || "{}")) as { uuid_cursor?: string };+ if (!body.uuid_cursor) {+ return Array.from({ length: 50 }, (_, index) => ({+ uuid: `e${index}`,+ fact: `Fact ${index}`,+ }));+ }+ throw new Error("page failed");+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ userId: "ada", limit: 100 });+ expect(records).toHaveLength(50);+ });++ it("falls back to pure node listing when no user graph edges are collected", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/user/ada")) {+ throw new Error("edges unavailable");+ }+ if (String(url).includes("/graph/node/user/ada")) {+ return [{ uuid: "n1", name: "Topic", summary: "About tea" }];+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ userId: "ada" });+ expect(records).toEqual([expect.objectContaining({ id: "n1" })]);+ });++ it("returns just the facts when node enrichment fails after collecting edges", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/user/ada")) {+ return [{ uuid: "e1", fact: "Ada prefers tea" }];+ }+ if (String(url).includes("/graph/node/user/ada")) {+ throw new Error("nodes unavailable");+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ userId: "ada" });+ expect(records).toEqual([expect.objectContaining({ id: "e1" })]);+ });++ it("resolves the thread user from a nested session field", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/threads/s1/messages")) {+ return { session: { user_id: "ada" } };+ }+ if (String(url).includes("/graph/edge/user/ada")) {+ return [{ uuid: "e1", fact: "Ada prefers TypeScript" }];+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.list({ sessionId: "s1" })).resolves.toEqual([+ expect.objectContaining({ id: "e1", userId: "ada" }),+ ]);+ });++ it("lists a session's raw thread context when the thread's user cannot be resolved", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/threads/s1/messages")) throw new Error("no user");+ if (String(url).includes("/sessions/s1")) throw new Error("no user");+ if (String(url).includes("/threads/s1/context")) {+ return { context: "Ada likes tea." };+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.list({ sessionId: "s1" })).resolves.toEqual([+ expect.objectContaining({ id: "s1", content: "Ada likes tea." }),+ ]);+ });++ it("uses an explicit numeric score when the vendor provides one", async () => {+ mockSafeFetch.mockResolvedValue([+ { uuid: "e1", fact: "Ada prefers TypeScript", score: 0.87 },+ ]);+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ userId: "ada" });+ expect(records[0].score).toBe(0.87);+ });++ it("returns no filter choices when the vendor response has no recognizable rows", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [],+ sessions: [],+ agents: [],+ });+ });++ it("returns null when neither the graph nor the session memory can be fetched", async () => {+ mockSafeFetch.mockRejectedValue(new Error("unavailable"));+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.get("s1")).resolves.toBeNull();+ });++ it("clears user and session filters independently when both listings fail", async () => {+ mockSafeFetch.mockRejectedValue(new Error("vendor down"));+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [],+ sessions: [],+ agents: [],+ });+ });++ it("falls back to deleting the graph node when deleting the edge fails", async () => {+ mockSafeFetch.mockImplementation(async (url: string, options?: { method?: string }) => {+ if (String(url).includes("/graph/edge/e1") && options?.method === "DELETE") {+ throw new Error("edge not found");+ }+ return {};+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await adapter.delete("e1");+ expect(String(mockSafeFetch.mock.calls[1][0])).toContain("/api/v2/graph/node/e1");+ expect(mockSafeFetch.mock.calls[1][1].method).toBe("DELETE");+ });++ it("passes user id and metadata through when adding session memory", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new ZepAdapter(descriptor("zep"));+ await adapter.add({+ content: "hello",+ sessionId: "s1",+ userId: "ada",+ metadata: { source: "otter" },+ });+ expect(JSON.parse(mockSafeFetch.mock.calls[0][1].body)).toEqual(+ expect.objectContaining({+ user_id: "ada",+ metadata: { source: "otter" },+ })+ );+ });++ it("normalizes user and session filter rows with fallback id and label fields", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/users")) {+ return { users: [{ uuid: "u1", first_name: "Ada", last_name: "Lovelace" }] };+ }+ return { sessions: [{ session_id: "s1" }] };+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [{ id: "u1", label: "Ada Lovelace" }],+ sessions: [{ id: "s1", label: "s1", userId: undefined }],+ agents: [],+ });+ });++ it("normalizes session messages using the text field, defaults role, and skips blanks", async () => {+ mockSafeFetch.mockResolvedValue({+ context: "Ada likes tea.",+ messages: [{ uuid: "m0" }, { uuid: "m1", text: "fallback text" }],+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.add({ content: "hello", sessionId: "s1" });+ expect(records[0].input).toEqual([{ role: "user", content: "fallback text" }]);+ });++ it("captures the scope field on temporal facts", async () => {+ mockSafeFetch.mockResolvedValue([+ { uuid: "e1", fact: "Ada prefers tea", scope: "project" },+ ]);+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ userId: "ada" });+ expect(records[0].metadata).toEqual(+ expect.objectContaining({ scope: "project" })+ );+ });++ it("falls back to content as the id and leaves metadata empty for a bare node", async () => {+ mockSafeFetch.mockResolvedValue([{ uuid_: "", text: "raw text with no labels" }]);+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ userId: "ada" });+ expect(records[0]).toEqual(+ expect.objectContaining({ id: "raw text with no labels", metadata: undefined })+ );+ });++ it("deduplicates graph records that share the same id across groups", async () => {+ mockSafeFetch.mockResolvedValue({+ edges: [{ uuid: "e1", fact: "Ada prefers tea" }],+ facts: [{ uuid: "e1", fact: "Ada prefers tea" }],+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ userId: "ada" });+ expect(records).toHaveLength(1);+ });++ it("defaults empty ids/labels for users and sessions with no recognizable fields", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/users")) return { users: [{}] };+ return { sessions: [{}] };+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [],+ sessions: [],+ agents: [],+ });+ });++ it("returns null when getting a blank id", async () => {+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.get(" ")).resolves.toBeNull();+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("returns null when the session lookup succeeds but has no content", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/") || String(url).includes("/graph/node/")) {+ throw new Error("not found");+ }+ return {};+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.get("s1")).resolves.toBeNull();+ });++ it("returns no records when the first edge page is already empty", async () => {+ mockSafeFetch.mockResolvedValue([]);+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.list({ userId: "ada" })).resolves.toEqual([]);+ });++ it("returns null when deleting a blank id", async () => {+ const adapter = new ZepAdapter(descriptor("zep"));+ await adapter.delete(" ");+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("skips enriching a graph record that already carries input", async () => {+ mockSafeFetch.mockResolvedValue({+ uuid: "e1",+ fact: "Ada prefers tea",+ messages: [{ role: "user", content: "already here" }],+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.get("e1")).resolves.toEqual(+ expect.objectContaining({+ input: [{ role: "user", content: "already here" }],+ })+ );+ });++ it("leaves the record unchanged when every episode fetch fails", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/e1") && !String(url).includes("/user/")) {+ return { uuid: "e1", fact: "The plan is active", episodes: ["ep-1"] };+ }+ if (String(url).includes("/graph/episodes/")) throw new Error("gone");+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.get("e1")).resolves.toEqual(+ expect.objectContaining({ id: "e1", input: undefined })+ );+ });++ it("skips episodes with no content and falls back to role_type", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/e1") && !String(url).includes("/user/")) {+ return {+ uuid: "e1",+ fact: "The plan is active",+ episodes: ["ep-empty", "ep-role-type"],+ };+ }+ if (String(url).includes("/graph/episodes/ep-empty")) return { uuid: "ep-empty" };+ if (String(url).includes("/graph/episodes/ep-role-type")) {+ return { uuid: "ep-role-type", content: "renewed", role_type: "assistant" };+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.get("e1")).resolves.toEqual(+ expect.objectContaining({+ input: [{ role: "assistant", content: "renewed" }],+ })+ );+ });++ it("skips episodes that fail to load while enriching a graph record", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/e1") && !String(url).includes("/user/")) {+ return {+ uuid: "e1",+ fact: "The plan is active",+ episodes: ["ep-bad", "ep-good"],+ };+ }+ if (String(url).includes("/graph/episodes/ep-bad")) {+ throw new Error("episode missing");+ }+ if (String(url).includes("/graph/episodes/ep-good")) {+ return { uuid: "ep-good", content: "Plan renewed", role: "user" };+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.get("e1")).resolves.toEqual(+ expect.objectContaining({+ input: [{ role: "user", content: "Plan renewed" }],+ })+ );+ });++ it("coerces a numeric uuid to a string id", async () => {+ mockSafeFetch.mockResolvedValue([{ uuid: 501, fact: "Numeric id fact" }]);+ const adapter = new ZepAdapter(descriptor("zep"));+ const records = await adapter.list({ userId: "ada" });+ expect(records[0]).toEqual(expect.objectContaining({ id: "501" }));+ });++ it("reads a bare array response when listing users", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/users-ordered")) {+ return [{ user_id: "ada", email: "[email protected]" }];+ }+ return { sessions: [] };+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.listFilters()).resolves.toEqual(+ expect.objectContaining({ users: [{ id: "ada", label: "[email protected]" }] })+ );+ });++ it("falls back to secret.raw for the Api-Key header when credentials lack an apiKey", async () => {+ (resolveSourceSecret as jest.Mock).mockResolvedValueOnce({+ raw: "raw-secret",+ credentials: {},+ });+ mockSafeFetch.mockResolvedValue({ users: [] });+ const adapter = new ZepAdapter(descriptor("zep"));+ await adapter.healthCheck();+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(options.headers.Authorization).toBe("Api-Key raw-secret");+ });++ it("omits the Authorization header when the secret has no usable value", async () => {+ (resolveSourceSecret as jest.Mock).mockResolvedValueOnce({+ raw: "",+ credentials: {},+ });+ mockSafeFetch.mockResolvedValue({ users: [] });+ const adapter = new ZepAdapter(descriptor("zep"));+ await adapter.healthCheck();+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(options.headers.Authorization).toBeUndefined();+ });++ it("wraps a non-Error rejection into an Error when every health-check attempt fails", async () => {+ mockSafeFetch.mockImplementation(async () => {+ throw "vendor exploded";+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.healthCheck()).resolves.toEqual(+ expect.objectContaining({ ok: false, message: expect.stringContaining("vendor exploded") })+ );+ });++ it("uses the raw error value as the message when the wrapped error has no message text", async () => {+ mockSafeFetch.mockRejectedValue(new Error(""));+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.healthCheck()).resolves.toEqual(+ expect.objectContaining({ ok: false, message: "Error" })+ );+ });++ it("defaults an episode's role to user when role and role_type are both missing", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/graph/edge/e1") && !String(url).includes("/user/")) {+ return { uuid: "e1", fact: "The plan is active", episodes: ["ep-1"] };+ }+ if (String(url).includes("/graph/episodes/ep-1")) {+ return { uuid: "ep-1", content: "Plan details" };+ }+ throw new Error(`unexpected ${url}`);+ });+ const adapter = new ZepAdapter(descriptor("zep"));+ await expect(adapter.get("e1")).resolves.toEqual(+ expect.objectContaining({+ input: [{ role: "user", content: "Plan details" }],+ })+ );+ });+});++describe("Claude adapter", () => {+ it("describes memory-store config", () => {+ const described = claudeAdapterFactory.describe();+ expect(described.type).toBe("claude");+ expect(described.capabilities).toEqual({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: false,+ });+ expect(described.configFields.map((field) => field.key)).toEqual(+ expect.arrayContaining(["url", "apiKey"])+ );+ expect(described.configFields.map((field) => field.key)).not.toContain("storeId");+ expect(described.configFields.find((field) => field.key === "apiKey")?.group).toBe(+ "credentials"+ );+ expect(described.filterFields?.map((field) => field.key)).toEqual([+ "sessionId",+ ]);+ expect(described.filterFields?.[0]).toMatchObject({+ key: "sessionId",+ required: true,+ });+ });++ it("health-checks stores with Anthropic memory headers", async () => {+ mockSafeFetch.mockResolvedValue({ data: [] });+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.healthCheck()).resolves.toEqual(+ expect.objectContaining({ ok: true })+ );+ const [url, options] = mockSafeFetch.mock.calls[0];+ expect(String(url)).toContain("https://api.anthropic.com/v1/memory_stores");+ expect(options.headers["x-api-key"]).toBe("secret-key");+ expect(options.headers["anthropic-version"]).toBe("2023-06-01");+ expect(options.headers["anthropic-beta"]).toBe("agent-memory-2026-07-22");+ });++ it("lists memory stores as session filters", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ {+ id: "memstore_1",+ name: "User Preferences",+ metadata: { user_id: "ada" },+ },+ ],+ });+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [],+ sessions: [{ id: "memstore_1", label: "User Preferences" }],+ agents: [],+ });+ });++ it("lists memories from a store with view=full", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ {+ id: "mem_1",+ type: "memory",+ path: "/projects/foo/notes.md",+ content: "Prefers TypeScript",+ memory_store_id: "memstore_1",+ created_at: "2026-08-01T00:00:00Z",+ },+ { type: "memory_prefix", path: "/archive/" },+ ],+ });+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.list({ sessionId: "memstore_1" })).resolves.toEqual([+ expect.objectContaining({+ id: "memstore_1:mem_1",+ content: "Prefers TypeScript",+ sessionId: "memstore_1",+ categories: ["projects", "foo", "notes.md"],+ }),+ ]);+ const [url] = mockSafeFetch.mock.calls[0];+ expect(String(url)).toContain(+ "https://api.anthropic.com/v1/memory_stores/memstore_1/memories?"+ );+ expect(String(url)).toContain("view=full");+ });++ it("requires a store when more than one exists", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ { id: "memstore_1", name: "One" },+ { id: "memstore_2", name: "Two" },+ ],+ });+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.list({})).rejects.toThrow(/user, agent, or session/i);+ });++ it("gets a memory by composite id and attaches changelog", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/memory_versions")) {+ return {+ data: [+ {+ id: "memver_2",+ operation: "modified",+ content: "Prefers bun",+ created_by: { type: "api_actor", api_key_id: "key_1" },+ },+ {+ id: "memver_1",+ operation: "created",+ content: "Prefers TypeScript",+ },+ ],+ };+ }+ return {+ id: "mem_1",+ type: "memory",+ path: "/notes.md",+ content: "Prefers bun",+ memory_store_id: "memstore_1",+ };+ });+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.get("memstore_1:mem_1")).resolves.toEqual(+ expect.objectContaining({+ id: "memstore_1:mem_1",+ content: "Prefers bun",+ history: [+ expect.objectContaining({+ id: "memver_2",+ event: "UPDATE",+ newMemory: "Prefers bun",+ actorId: "key_1",+ }),+ expect.objectContaining({ id: "memver_1", event: "ADD" }),+ ],+ })+ );+ });++ it("searches listed memories locally", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ {+ id: "mem_1",+ type: "memory",+ path: "/a.md",+ content: "Prefers TypeScript",+ memory_store_id: "memstore_1",+ },+ {+ id: "mem_2",+ type: "memory",+ path: "/b.md",+ content: "Uses bun",+ memory_store_id: "memstore_1",+ },+ ],+ });+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" })+ );+ const records = await adapter.search({ query: "typescript" });+ expect(records).toEqual([+ expect.objectContaining({ content: "Prefers TypeScript" }),+ ]);+ });++ it("creates a memory under /openlit when no path is given", async () => {+ mockSafeFetch.mockResolvedValue({+ id: "mem_9",+ type: "memory",+ path: "/openlit/prefers-tabs.md",+ content: "Prefers tabs",+ memory_store_id: "memstore_1",+ });+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" })+ );+ await expect(adapter.add({ content: "Prefers tabs" })).resolves.toEqual([+ expect.objectContaining({ id: "memstore_1:mem_9", content: "Prefers tabs" }),+ ]);+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(options.method).toBe("POST");+ expect(JSON.parse(options.body)).toEqual({+ path: "/openlit/prefers-tabs.md",+ content: "Prefers tabs",+ });+ });++ it("exposes capabilities directly on the adapter instance", () => {+ const adapter = new ClaudeAdapter(descriptor("claude"));+ expect(adapter.capabilities()).toEqual({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: false,+ });+ });++ it("health-checks a specific store when storeId is configured", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" })+ );+ await expect(adapter.healthCheck()).resolves.toEqual(+ expect.objectContaining({ ok: true })+ );+ expect(String(mockSafeFetch.mock.calls[0][0])).toBe(+ "https://api.anthropic.com/v1/memory_stores/memstore_1"+ );+ });++ it("reports an unhealthy connection when the store request fails", async () => {+ mockSafeFetch.mockRejectedValue(new Error("store unreachable"));+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.healthCheck()).resolves.toEqual(+ expect.objectContaining({ ok: false, message: expect.stringContaining("store unreachable") })+ );+ });++ it("rejects adding a memory with no content or messages", async () => {+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" })+ );+ await expect(adapter.add({})).rejects.toThrow(/content/i);+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("includes content_size_bytes in metadata when the vendor reports it", async () => {+ mockSafeFetch.mockResolvedValue({+ id: "mem_1",+ path: "/a.md",+ content: "Prefers TypeScript",+ memory_store_id: "memstore_1",+ content_size_bytes: 42,});- const adapter = new ZepAdapter(descriptor("zep"));- const records = await adapter.list({ userId: "ada" });- expect(records).toEqual([- expect.objectContaining({- id: "e1",- relation: {- source: {- id: "n-user",- label: "Sarah Smith",- types: ["User"],- },- target: {- id: "n-loc",- label: "Austin",- types: ["Location"],- },- name: "LIVES_IN",- },- }),+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" })+ );+ await expect(adapter.add({ content: "Prefers TypeScript" })).resolves.toEqual([expect.objectContaining({- id: "n-topic",- graphOnly: true,- categories: ["Topic"],+ metadata: expect.objectContaining({ content_size_bytes: 42 }),}),]);});- it("falls back to /users and /sessions when ordered/thread endpoints are missing", async () => {+ it("paginates memory store listings using next_page", async () => {mockSafeFetch.mockImplementation(async (url: string) => {- if (String(url).includes("/users-ordered") || String(url).includes("/threads")) {- throw new Error("not found");- }- if (String(url).includes("/users")) {- return { users: [{ user_id: "ada", email: "[email protected]" }] };+ if (String(url).includes("page=p2")) {+ return { data: [{ id: "memstore_2", name: "Two" }] };}- return { sessions: [{ session_id: "s1", user_id: "ada" }] };+ return { data: [{ id: "memstore_1", name: "One" }], next_page: "p2" };});- const adapter = new ZepAdapter(descriptor("zep"));+ const adapter = new ClaudeAdapter(descriptor("claude"));await expect(adapter.listFilters()).resolves.toEqual({- users: [{ id: "ada", label: "[email protected]" }],- sessions: [{ id: "s1", label: "s1", userId: "ada" }],+ users: [],+ sessions: [+ { id: "memstore_1", label: "One" },+ { id: "memstore_2", label: "Two" },+ ],agents: [],});});- it("lists user graph facts and falls back to nodes", async () => {- mockSafeFetch.mockImplementation(async (url: string) => {- if (String(url).includes("/graph/edge/user/")) {- return {- edges: [- {- uuid: "e1",- fact: "Ada prefers TypeScript",- name: "PREFERS",- created_at: "2026-08-16T00:00:00Z",- },- ],- };- }- throw new Error(`unexpected ${url}`);+ it("returns empty filters when listing stores fails", async () => {+ mockSafeFetch.mockRejectedValue(new Error("stores unavailable"));+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [],+ sessions: [],+ agents: [],});- const adapter = new ZepAdapter(descriptor("zep"));- await expect(adapter.list({ userId: "ada" })).resolves.toEqual([- expect.objectContaining({- id: "e1",- content: "Ada prefers TypeScript",- userId: "ada",- categories: ["PREFERS"],- }),- ]);- expect(String(mockSafeFetch.mock.calls[0][0])).toContain(- "/api/v2/graph/edge/user/ada"- );});- it("lists the user graph even when a session is selected", async () => {+ it("resolves a bare memory id using the configured store", async () => {mockSafeFetch.mockImplementation(async (url: string) => {- if (String(url).includes("/graph/edge/user/ada")) {- return [{ uuid: "e1", fact: "Ada prefers TypeScript", created_at: "2026-08-16T00:00:00Z" }];- }- throw new Error(`unexpected ${url}`);+ if (String(url).includes("/memory_versions")) return { data: [] };+ return {+ id: "mem_1",+ path: "/a.md",+ content: "Prefers TypeScript",+ memory_store_id: "memstore_1",+ };});- const adapter = new ZepAdapter(descriptor("zep"));- const records = await adapter.list({ sessionId: "s1", userId: "ada" });- expect(records).toEqual([- expect.objectContaining({- id: "e1",- content: "Ada prefers TypeScript",- userId: "ada",- }),- ]);- expect(String(mockSafeFetch.mock.calls[0][0])).toContain(- "/api/v2/graph/edge/user/ada"+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" })+ );+ await expect(adapter.get("mem_1")).resolves.toEqual(+ expect.objectContaining({ id: "memstore_1:mem_1" }));});- it("resolves the thread user then lists that user's graph", async () => {- mockSafeFetch.mockImplementation(async (url: string) => {- if (String(url).includes("/threads/s1/messages")) {- return { messages: [], user_id: "ada" };- }- if (String(url).includes("/graph/edge/user/ada")) {- return [{ uuid: "e1", fact: "Ada prefers TypeScript" }];- }- throw new Error(`unexpected ${url}`);- });- const adapter = new ZepAdapter(descriptor("zep"));- const records = await adapter.list({ sessionId: "s1" });- expect(records).toEqual([- expect.objectContaining({ id: "e1", userId: "ada" }),- ]);+ it("returns null when a memory id cannot be resolved to a store", async () => {+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.get("mem_1")).resolves.toBeNull();+ expect(mockSafeFetch).not.toHaveBeenCalled();});- it("gets a fact by graph edge uuid and falls back to nodes", async () => {+ it("still returns the memory when the version history request fails", async () => {mockSafeFetch.mockImplementation(async (url: string) => {- if (String(url).includes("/graph/edge/")) {- throw new Error("not found");- }- if (String(url).includes("/graph/node/")) {- return {- uuid: "n1",- name: "Ada",- summary: "Engineer who drinks tea",- labels: ["user"],- attributes: { role: "engineer" },- };- }- throw new Error(`unexpected ${url}`);+ if (String(url).includes("/memory_versions")) throw new Error("no history");+ return {+ id: "mem_1",+ path: "/a.md",+ content: "Prefers TypeScript",+ memory_store_id: "memstore_1",+ };});- const adapter = new ZepAdapter(descriptor("zep"));- await expect(adapter.get("n1")).resolves.toEqual(- expect.objectContaining({- id: "n1",- content: "Engineer who drinks tea",- categories: ["user"],- structuredAttributes: { role: "engineer" },- })+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.get("memstore_1:mem_1")).resolves.toEqual(+ expect.objectContaining({ id: "memstore_1:mem_1", history: [] }));});- it("attaches changelog and source episodes when getting an edge", async () => {+ it("reads a memory_versions response that is a raw array", async () => {mockSafeFetch.mockImplementation(async (url: string) => {- if (String(url).includes("/graph/edge/e1") && !String(url).includes("/user/")) {- return {- uuid: "e1",- fact: "The Enterprise Sandbox Tier 3 plan is Active.",- name: "HAS_PLAN",- created_at: "2026-08-17T00:00:00Z",- valid_at: "2026-08-17T01:00:00Z",- episodes: ["ep-1"],- };- }- if (String(url).includes("/graph/episodes/ep-1")) {- return { uuid: "ep-1", content: "Our plan is active", role: "user" };+ if (String(url).includes("/memory_versions")) {+ return [{ id: "memver_1", operation: "created", content: "Prefers bun" }];}- throw new Error(`unexpected ${url}`);+ return {+ id: "mem_1",+ path: "/a.md",+ content: "Prefers bun",+ memory_store_id: "memstore_1",+ };});- const adapter = new ZepAdapter(descriptor("zep"));- await expect(adapter.get("e1")).resolves.toEqual(+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.get("memstore_1:mem_1")).resolves.toEqual(expect.objectContaining({- id: "e1",- input: [{ role: "user", content: "Our plan is active" }],- history: [- expect.objectContaining({- event: "ADD",- createdAt: "2026-08-17T00:00:00Z",- }),- expect.objectContaining({- event: "UPDATE",- createdAt: "2026-08-17T01:00:00Z",- }),- ],+ history: [expect.objectContaining({ id: "memver_1", event: "ADD" })],}));});- it("gets thread context when the id is not a graph uuid", async () => {- mockSafeFetch.mockImplementation(async (url: string) => {- if (String(url).includes("/graph/edge/") || String(url).includes("/graph/node/")) {- throw new Error("not found");- }- if (String(url).includes("/threads/s1/context")) {- return { context: "Ada likes tea.", messages: [{ role: "user", content: "I like tea" }] };- }- throw new Error(`unexpected ${url}`);+ it("updates a memory and merges a normalized path", async () => {+ mockSafeFetch.mockResolvedValue({+ id: "mem_1",+ path: "/renamed.md",+ content: "Prefers bun",+ memory_store_id: "memstore_1",});- const adapter = new ZepAdapter(descriptor("zep"));- await expect(adapter.get("s1")).resolves.toEqual(- expect.objectContaining({- id: "s1",- content: "Ada likes tea.",- input: [{ role: "user", content: "I like tea" }],+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(+ adapter.update("memstore_1:mem_1", {+ content: "Prefers bun",+ metadata: { path: "renamed.md" },})+ ).resolves.toEqual(+ expect.objectContaining({ id: "memstore_1:mem_1", content: "Prefers bun" }));+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(JSON.parse(options.body)).toEqual({+ content: "Prefers bun",+ path: "/renamed.md",+ });});- it("pages user graph edges with uuid_cursor", async () => {- mockSafeFetch.mockImplementation(async (url: string, options?: { body?: string }) => {- if (!String(url).includes("/graph/edge/user/ada")) {- throw new Error(`unexpected ${url}`);- }- const body = JSON.parse(String(options?.body || "{}")) as { uuid_cursor?: string };- if (!body.uuid_cursor) {- return Array.from({ length: 50 }, (_, index) => ({- uuid: `e${index}`,- fact: `Fact ${index}`,- }));- }- return [{ uuid: "e50", fact: "Fact 50" }];+ it("falls back to the input payload when an update response cannot be normalized", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(+ adapter.update("memstore_1:mem_1", { content: "Prefers bun" })+ ).resolves.toEqual({+ id: "memstore_1:mem_1",+ content: "Prefers bun",+ sessionId: "memstore_1",+ metadata: undefined,});- const adapter = new ZepAdapter(descriptor("zep"));- const records = await adapter.list({ userId: "ada", limit: 51 });- expect(records).toHaveLength(51);- expect(records[50]?.id).toBe("e50");- expect(JSON.parse(String(mockSafeFetch.mock.calls[1][1].body)).uuid_cursor).toBe("e49");});- it("deletes a graph edge instead of the whole session", async () => {- mockSafeFetch.mockResolvedValue({});- const adapter = new ZepAdapter(descriptor("zep"));- await adapter.delete("e1");- expect(String(mockSafeFetch.mock.calls[0][0])).toContain("/api/v2/graph/edge/e1");- expect(mockSafeFetch.mock.calls[0][1].method).toBe("DELETE");+ it("rejects updating or deleting a memory whose id cannot be resolved", async () => {+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(+ adapter.update("mem_1", { content: "hello" })+ ).rejects.toThrow(/could not be found/i);+ await expect(adapter.delete("mem_1")).rejects.toThrow(/could not be found/i);+ expect(mockSafeFetch).not.toHaveBeenCalled();});- it("lists users and threads for filter dropdowns", async () => {- mockSafeFetch.mockImplementation(async (url: string) => {- if (String(url).includes("/users-ordered") || String(url).includes("/users")) {- return { users: [{ user_id: "ada", email: "[email protected]" }] };- }- if (String(url).includes("/threads")) {- return { threads: [{ thread_id: "s1", user_id: "ada" }] };- }- return { sessions: [{ session_id: "s1", user_id: "ada" }] };- });- const adapter = new ZepAdapter(descriptor("zep"));- await expect(adapter.listFilters()).resolves.toEqual({- users: [{ id: "ada", label: "[email protected]" }],- sessions: [{ id: "s1", label: "s1", userId: "ada" }],- agents: [],- });- expect(String(mockSafeFetch.mock.calls[0][0])).toContain("/api/v2/users-ordered");- expect(String(mockSafeFetch.mock.calls[1][0])).toContain("/api/v2/threads");+ it("deletes a memory by composite id", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await adapter.delete("memstore_1:mem_1");+ const [url, options] = mockSafeFetch.mock.calls[0];+ expect(String(url)).toBe(+ "https://api.anthropic.com/v1/memory_stores/memstore_1/memories/mem_1"+ );+ expect(options.method).toBe("DELETE");});-});-describe("Claude adapter", () => {- it("describes memory-store config", () => {- const described = claudeAdapterFactory.describe();- expect(described.type).toBe("claude");- expect(described.capabilities).toEqual({- add: true,- search: true,- get: true,- list: true,- update: true,- delete: true,- feedback: false,- });- expect(described.configFields.map((field) => field.key)).toEqual(- expect.arrayContaining(["url", "apiKey"])+ it("returns null when getting a blank memory id", async () => {+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" }));- expect(described.configFields.map((field) => field.key)).not.toContain("storeId");- expect(described.configFields.find((field) => field.key === "apiKey")?.group).toBe(- "credentials"+ await expect(adapter.get(" ")).resolves.toBeNull();+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("rejects an empty search query", async () => {+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" }));- expect(described.filterFields?.map((field) => field.key)).toEqual([- "sessionId",- ]);- expect(described.filterFields?.[0]).toMatchObject({- key: "sessionId",- required: true,- });+ await expect(adapter.search({ query: " " })).rejects.toThrow(/query/i);});- it("health-checks stores with Anthropic memory headers", async () => {- mockSafeFetch.mockResolvedValue({ data: [] });+ it("resolves a single store automatically when none is specified", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/memory_stores?")) {+ return { data: [{ id: "memstore_only", name: "Only" }] };+ }+ return { data: [] };+ });const adapter = new ClaudeAdapter(descriptor("claude"));- await expect(adapter.healthCheck()).resolves.toEqual(- expect.objectContaining({ ok: true })- );- const [url, options] = mockSafeFetch.mock.calls[0];- expect(String(url)).toContain("https://api.anthropic.com/v1/memory_stores");- expect(options.headers["x-api-key"]).toBe("secret-key");- expect(options.headers["anthropic-version"]).toBe("2023-06-01");- expect(options.headers["anthropic-beta"]).toBe("agent-memory-2026-07-22");+ await expect(adapter.list({})).resolves.toEqual([]);});- it("lists memory stores as session filters", async () => {+ it("falls back to memory when a store row has no name and skips rows with no id", async () => {mockSafeFetch.mockResolvedValue({- data: [- {- id: "memstore_1",- name: "User Preferences",- metadata: { user_id: "ada" },- },- ],+ data: [{ id: "memstore_1" }, { name: "no id" }],});const adapter = new ClaudeAdapter(descriptor("claude"));await expect(adapter.listFilters()).resolves.toEqual({users: [],- sessions: [{ id: "memstore_1", label: "User Preferences" }],+ sessions: [{ id: "memstore_1", label: "memstore_1" }],agents: [],});});- it("lists memories from a store with view=full", async () => {+ it("paginates a store's memory listing using next_page", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("&page=p2")) {+ return {+ data: [+ { id: "mem_2", content: "Second page", memory_store_id: "memstore_1" },+ ],+ };+ }+ return {+ data: [+ { id: "mem_1", content: "First page", memory_store_id: "memstore_1" },+ ],+ next_page: "p2",+ };+ });+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" })+ );+ const records = await adapter.list({});+ expect(records.map((record) => record.id)).toEqual([+ "memstore_1:mem_1",+ "memstore_1:mem_2",+ ]);+ });++ it("normalizes memories missing a path or content, and captures version/sha metadata", async () => {mockSafeFetch.mockResolvedValue({- data: [- {- id: "mem_1",- type: "memory",- path: "/projects/foo/notes.md",- content: "Prefers TypeScript",- memory_store_id: "memstore_1",- created_at: "2026-08-01T00:00:00Z",- },- { type: "memory_prefix", path: "/archive/" },- ],+ id: "mem_1",+ memory_store_id: "memstore_1",+ memory_version_id: "v2",+ content_sha256: "abc123",});- const adapter = new ClaudeAdapter(descriptor("claude"));- await expect(adapter.list({ sessionId: "memstore_1" })).resolves.toEqual([+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" })+ );+ await expect(adapter.add({ content: "irrelevant, path defaults" })).resolves.toEqual([expect.objectContaining({id: "memstore_1:mem_1",- content: "Prefers TypeScript",- sessionId: "memstore_1",- categories: ["projects", "foo", "notes.md"],+ content: "",+ categories: undefined,+ metadata: expect.objectContaining({+ memory_version_id: "v2",+ content_sha256: "abc123",+ }),}),]);- const [url] = mockSafeFetch.mock.calls[0];- expect(String(url)).toContain(- "https://api.anthropic.com/v1/memory_stores/memstore_1/memories?"+ });++ it("returns an empty list when the created memory cannot be normalized", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" }));- expect(String(url)).toContain("view=full");+ await expect(adapter.add({ content: "hello" })).resolves.toEqual([]);});- it("requires a store when more than one exists", async () => {+ it("keeps an absolute metadata path unchanged when updating", async () => {mockSafeFetch.mockResolvedValue({- data: [- { id: "memstore_1", name: "One" },- { id: "memstore_2", name: "Two" },- ],+ id: "mem_1",+ path: "/already/slash.md",+ content: "hello",+ memory_store_id: "memstore_1",});const adapter = new ClaudeAdapter(descriptor("claude"));- await expect(adapter.list({})).rejects.toThrow(/user, agent, or session/i);+ await adapter.update("memstore_1:mem_1", {+ content: "hello",+ metadata: { path: "/already/slash.md" },+ });+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(JSON.parse(options.body)).toEqual({+ content: "hello",+ path: "/already/slash.md",+ });});- it("gets a memory by composite id and attaches changelog", async () => {+ it("reads history rows with no operation and unmapped operations", async () => {mockSafeFetch.mockImplementation(async (url: string) => {if (String(url).includes("/memory_versions")) {return {data: [- {- id: "memver_2",- operation: "modified",- content: "Prefers bun",- created_by: { type: "api_actor", api_key_id: "key_1" },- },- {- id: "memver_1",- operation: "created",- content: "Prefers TypeScript",- },+ { id: "v1", content: "no-op row" },+ { id: "v2", operation: "archived", content: "unmapped op" },],};}return {id: "mem_1",- type: "memory",- path: "/notes.md",- content: "Prefers bun",+ content: "hello",memory_store_id: "memstore_1",};});const adapter = new ClaudeAdapter(descriptor("claude"));await expect(adapter.get("memstore_1:mem_1")).resolves.toEqual(expect.objectContaining({- id: "memstore_1:mem_1",- content: "Prefers bun",history: [- expect.objectContaining({- id: "memver_2",- event: "UPDATE",- newMemory: "Prefers bun",- actorId: "key_1",- }),- expect.objectContaining({ id: "memver_1", event: "ADD" }),+ expect.objectContaining({ id: "v1", event: "UPDATE" }),+ expect.objectContaining({ id: "v2", event: "ARCHIVED" }),],}));});- it("searches listed memories locally", async () => {+ it("rejects adding a memory when content is only whitespace", async () => {+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" })+ );+ await expect(adapter.add({ content: " " })).rejects.toThrow(/content/i);+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("falls back to a generic slug when the content has no alphanumeric characters", async () => {+ mockSafeFetch.mockResolvedValue({+ id: "mem_1",+ path: "/openlit/memory.md",+ content: "!!!",+ memory_store_id: "memstore_1",+ });+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" })+ );+ await adapter.add({ content: "!!!" });+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(JSON.parse(options.body)).toEqual({+ path: "/openlit/memory.md",+ content: "!!!",+ });+ });++ it("uses a metadata path when adding a memory, adding a leading slash if missing", async () => {+ mockSafeFetch.mockResolvedValue({+ id: "mem_1",+ path: "/notes/today.md",+ content: "Standup notes",+ memory_store_id: "memstore_1",+ });+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" })+ );+ await adapter.add({+ content: "Standup notes",+ metadata: { path: "notes/today.md" },+ });+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(JSON.parse(options.body)).toEqual({+ path: "/notes/today.md",+ content: "Standup notes",+ });+ });++ it("keeps an already-absolute metadata path unchanged when adding a memory", async () => {+ mockSafeFetch.mockResolvedValue({+ id: "mem_1",+ path: "/notes/today.md",+ content: "Standup notes",+ memory_store_id: "memstore_1",+ });+ const adapter = new ClaudeAdapter(+ descriptor("claude", { storeId: "memstore_1" })+ );+ await adapter.add({+ content: "Standup notes",+ metadata: { path: "/notes/today.md" },+ });+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(JSON.parse(options.body)).toEqual({+ path: "/notes/today.md",+ content: "Standup notes",+ });+ });++ it("returns an empty page when a store listing is neither wrapped nor a bare array", async () => {+ mockSafeFetch.mockResolvedValue({});+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [],+ sessions: [],+ agents: [],+ });+ });++ it("treats a root-only path as having no categories", async () => {mockSafeFetch.mockResolvedValue({data: [- {- id: "mem_1",- type: "memory",- path: "/a.md",- content: "Prefers TypeScript",- memory_store_id: "memstore_1",- },- {- id: "mem_2",- type: "memory",- path: "/b.md",- content: "Uses bun",- memory_store_id: "memstore_1",- },+ { id: "mem_1", path: "/", content: "root memory", memory_store_id: "memstore_1" },],});const adapter = new ClaudeAdapter(descriptor("claude", { storeId: "memstore_1" }));- const records = await adapter.search({ query: "typescript" });- expect(records).toEqual([- expect.objectContaining({ content: "Prefers TypeScript" }),- ]);+ const records = await adapter.list({});+ expect(records[0]).toEqual(+ expect.objectContaining({ id: "memstore_1:mem_1", categories: undefined })+ );});- it("creates a memory under /openlit when no path is given", async () => {+ it("matches search queries against a memory that has no categories", async () => {mockSafeFetch.mockResolvedValue({- id: "mem_9",- type: "memory",- path: "/openlit/prefers-tabs.md",- content: "Prefers tabs",- memory_store_id: "memstore_1",+ data: [+ { id: "mem_1", content: "Uses vim keybindings", memory_store_id: "memstore_1" },+ ],});const adapter = new ClaudeAdapter(descriptor("claude", { storeId: "memstore_1" }));- await expect(adapter.add({ content: "Prefers tabs" })).resolves.toEqual([- expect.objectContaining({ id: "memstore_1:mem_9", content: "Prefers tabs" }),+ const records = await adapter.search({ query: "vim" });+ expect(records).toEqual([+ expect.objectContaining({ id: "memstore_1:mem_1", categories: undefined }),]);+ });++ it("treats a version-history response with no data array as empty", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/memory_versions")) return {};+ return {+ id: "mem_1",+ path: "/a.md",+ content: "hello",+ memory_store_id: "memstore_1",+ };+ });+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.get("memstore_1:mem_1")).resolves.toEqual(+ expect.objectContaining({ history: [] })+ );+ });++ it("reads a bare array response when listing memory stores", async () => {+ mockSafeFetch.mockResolvedValue([{ id: "memstore_1", name: "Only" }]);+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [],+ sessions: [{ id: "memstore_1", label: "Only" }],+ agents: [],+ });+ });++ it("falls back to secret.raw for the x-api-key header when credentials lack an apiKey", async () => {+ (resolveSourceSecret as jest.Mock).mockResolvedValueOnce({+ raw: "raw-secret",+ credentials: {},+ });+ mockSafeFetch.mockResolvedValue({ data: [] });+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await adapter.healthCheck();const [, options] = mockSafeFetch.mock.calls[0];- expect(options.method).toBe("POST");- expect(JSON.parse(options.body)).toEqual({- path: "/openlit/prefers-tabs.md",- content: "Prefers tabs",+ expect(options.headers["x-api-key"]).toBe("raw-secret");+ });++ it("omits the x-api-key header when the secret has no usable value", async () => {+ (resolveSourceSecret as jest.Mock).mockResolvedValueOnce({+ raw: "",+ credentials: {},});+ mockSafeFetch.mockResolvedValue({ data: [] });+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await adapter.healthCheck();+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(options.headers["x-api-key"]).toBeUndefined();+ });++ it("uses the raw rejection value as the message when it has no .message property", async () => {+ mockSafeFetch.mockRejectedValue("store down");+ const adapter = new ClaudeAdapter(descriptor("claude"));+ await expect(adapter.healthCheck()).resolves.toEqual(+ expect.objectContaining({ ok: false, message: "store down" })+ );});});diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-ask.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-ask.test.tsindex 8d9f8b93..3434991f 100644--- a/src/client/src/__tests__/lib/platform/connectors/memory-ask.test.ts+++ b/src/client/src/__tests__/lib/platform/connectors/memory-ask.test.ts@@ -1,4 +1,8 @@-import { buildMemoryAskPrompt, memoryAskSelectedSummary } from "@/lib/platform/connectors/memory/ask";+import {+ buildMemoryAskPrompt,+ memoryAskExcerpt,+ memoryAskSelectedSummary,+} from "@/lib/platform/connectors/memory/ask";import {MEMORY_ASK_FALLBACK_PROMPT,MEMORY_ASK_OTTER_PROMPT,@@ -6,6 +10,31 @@ import {MEMORY_ASK_TOOLS_PROMPT,} from "@/constants/messages/en";+describe("memoryAskExcerpt", () => {+ it("returns an empty string for missing or whitespace-only values", () => {+ expect(memoryAskExcerpt(undefined)).toBe("");+ expect(memoryAskExcerpt(" \n ")).toBe("");+ });++ it("truncates text longer than the max length with an ellipsis", () => {+ const long = "a".repeat(150);+ const excerpt = memoryAskExcerpt(long);+ expect(excerpt).toHaveLength(121);+ expect(excerpt.endsWith("…")).toBe(true);+ });+});++describe("memoryAskSelectedSummary", () => {+ it("falls back to the memory id when there is no content to summarize", () => {+ expect(memoryAskSelectedSummary({ memoryId: "mem-1" })).toBe("mem-1");+ });++ it("returns undefined when there is neither content nor a memory id", () => {+ expect(memoryAskSelectedSummary({})).toBeUndefined();+ expect(memoryAskSelectedSummary()).toBeUndefined();+ });+});+describe("buildMemoryAskPrompt", () => {it("stays compact and only passes filters the connector declares", () => {const prompt = buildMemoryAskPrompt("What does Ada prefer?", {@@ -59,6 +88,20 @@ describe("buildMemoryAskPrompt", () => {).toBe("User visited New York");});+ it("allows every filter key when the connector declares no filterKeys", () => {+ const prompt = buildMemoryAskPrompt("who talked to Ada?", {+ connectorId: "memory:1",+ userId: "ada",+ agentId: "bot",+ sessionId: "run-1",+ canList: true,+ canSearch: true,+ });+ expect(prompt).toContain("user_id=ada");+ expect(prompt).toContain("agent_id=bot");+ expect(prompt).toContain("session_id=run-1");+ });+it("falls back when the connector has no list/search API", () => {const prompt = buildMemoryAskPrompt("who are my users?", {connectorId: "memory:1",diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-copy.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-copy.test.tsindex 2934be0b..2e5b6e9c 100644--- a/src/client/src/__tests__/lib/platform/connectors/memory-copy.test.ts+++ b/src/client/src/__tests__/lib/platform/connectors/memory-copy.test.ts@@ -25,6 +25,7 @@ import {MEMORY_ADD_UNSUPPORTED,MEMORY_COPY_EMPTY,MEMORY_COPY_SAME_CONNECTOR,+ MEMORY_COPY_TOO_MANY,} from "@/constants/messages/en";const source = { id: "memory:src", name: "Mem0", type: "mem0" };@@ -61,6 +62,22 @@ describe("copyProjectMemories", () => {).rejects.toThrow(MEMORY_ADD_UNSUPPORTED);});+ it("rejects a destination whose type is no longer registered", async () => {+ mockGetMemoryTypeDescriptor.mockReturnValue(undefined);+ await expect(+ copyProjectMemories({+ sourceConnectorId: "memory:src",+ targetConnectorId: "memory:dst",+ })+ ).rejects.toThrow(MEMORY_ADD_UNSUPPORTED);+ });++ // Note: `!sourceId.startsWith("memory:") || !targetId.startsWith("memory:")`+ // (port.ts lines 77-79) is defensive/unreachable in practice: both the real+ // and mocked `memoryConnectorId` always return a "memory:"-prefixed string,+ // so this guard can never observe an unprefixed id. Left intentionally+ // uncovered rather than forcing an artificial test around it.+it("copies selected memories with a stored source link", async () => {mockQueryProjectMemories.mockResolvedValue({memories: [@@ -164,4 +181,118 @@ describe("copyProjectMemories", () => {})).rejects.toThrow(MEMORY_COPY_EMPTY);});++ it("ignores blank entries in the requested memoryIds list", async () => {+ mockQueryProjectMemories.mockResolvedValue({+ memories: [+ { id: "m1", content: "Prefers tabs", userId: "ada", kind: "profile" },+ { id: "m2", content: "Skip me", userId: "ada", kind: "summary" },+ ],+ });+ mockAddProjectMemories.mockResolvedValue({+ memories: [{ id: "z1", content: "Prefers tabs", userId: "ada", kind: "profile" }],+ });++ const result = await copyProjectMemories({+ sourceConnectorId: "src",+ targetConnectorId: "dst",+ memoryIds: ["", " ", "m1"],+ });++ expect(result.copied).toBe(1);+ expect(mockAddProjectMemories).toHaveBeenCalledTimes(1);+ });++ it("rejects when more than the max number of memories would be copied", async () => {+ const memories = Array.from({ length: 51 }, (_, i) => ({+ id: `m${i}`,+ content: `content ${i}`,+ userId: "ada",+ kind: "profile",+ }));+ mockQueryProjectMemories.mockResolvedValue({ memories });+ await expect(+ copyProjectMemories({+ sourceConnectorId: "memory:src",+ targetConnectorId: "memory:dst",+ })+ ).rejects.toThrow(MEMORY_COPY_TOO_MANY);+ });++ it("treats a source-only port link (no origin recorded yet) as the origin on re-copy", async () => {+ mockQueryProjectMemories.mockResolvedValue({+ memories: [+ {+ id: "z1",+ content: "Prefers tabs",+ userId: "ada",+ kind: "profile",+ metadata: {+ openlit: {+ port: {+ sourceConnectorId: "memory:src",+ sourceMemoryId: "m1",+ },+ },+ },+ },+ ],+ });+ mockAddProjectMemories.mockResolvedValue({+ memories: [{ id: "c1", content: "Prefers tabs", userId: "ada", kind: "profile" }],+ });++ const result = await copyProjectMemories({+ sourceConnectorId: "memory:dst",+ targetConnectorId: "memory:src",+ memoryIds: ["z1"],+ });++ expect(result.memories[0].port).toEqual(+ expect.objectContaining({+ originConnectorId: "memory:src",+ originMemoryId: "m1",+ })+ );+ });++ it("records per-memory failures, including from a non-Error rejection", async () => {+ mockQueryProjectMemories.mockResolvedValue({+ memories: [+ { id: "m1", content: "First", userId: "ada", kind: "profile" },+ { id: "m2", content: "Second", userId: "ada", kind: "profile" },+ ],+ });+ mockAddProjectMemories+ .mockRejectedValueOnce(new Error("boom"))+ .mockRejectedValueOnce("plain string failure");++ const result = await copyProjectMemories({+ sourceConnectorId: "memory:src",+ targetConnectorId: "memory:dst",+ });++ expect(result.copied).toBe(0);+ expect(result.failed).toEqual([+ { id: "m1", message: "boom" },+ { id: "m2", message: "plain string failure" },+ ]);+ expect(mockRecordMemoryPortLinks).not.toHaveBeenCalled();+ });++ it("records a failure when the destination adapter reports no created memory", async () => {+ mockQueryProjectMemories.mockResolvedValue({+ memories: [{ id: "m1", content: "First", userId: "ada", kind: "profile" }],+ });+ mockAddProjectMemories.mockResolvedValue({ memories: [] });++ const result = await copyProjectMemories({+ sourceConnectorId: "memory:src",+ targetConnectorId: "memory:dst",+ });++ expect(result.copied).toBe(0);+ expect(result.failed).toHaveLength(1);+ expect(result.failed[0].id).toBe("m1");+ });});diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-crud.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-crud.test.tsindex af6d7628..15c6d242 100644--- a/src/client/src/__tests__/lib/platform/connectors/memory-crud.test.ts+++ b/src/client/src/__tests__/lib/platform/connectors/memory-crud.test.ts@@ -63,13 +63,22 @@ jest.mock("@/lib/platform/connectors/datasource/http/secret", () => ({invalidateSourceSecretCache: jest.fn(),}));+import { headers } from "next/headers";+import { listMemoryTypeDescriptors } from "@/lib/platform/connectors/memory/registry";import {+ availableMemoryTypeDescriptors,createMemoryConnector,deleteMemoryConnector,+ emptyRememberedMemoryFilters,+ getMemoryRuntime,healthCheckMemoryConnector,isMemoryConnectorId,+ isMemoryConnectorType,listMemoryConnectors,+ memoryConnectorId,+ readMemoryPortLinks,readRememberedMemoryFilters,+ recordMemoryPortLinks,rememberMemoryFilters,updateMemoryConnector,} from "@/lib/platform/connectors/memory/crud";@@ -106,6 +115,28 @@ describe("memory connector CRUD", () => {expect(isMemoryConnectorId("telemetry:abc")).toBe(false);});+ it("prefixes a bare id and leaves an already-prefixed id untouched", () => {+ expect(memoryConnectorId("abc")).toBe("memory:abc");+ expect(memoryConnectorId("memory:abc")).toBe("memory:abc");+ expect(memoryConnectorId("")).toBe("memory:");+ });++ it("denies when there is no current organisation at all", async () => {+ mockGetCurrentOrganisation.mockResolvedValue(null);+ await expect(+ createMemoryConnector({ name: "X", type: "mem0" })+ ).rejects.toThrow(/no current project/i);+ expect(mockCreate).not.toHaveBeenCalled();+ });++ it("denies when the user has no current project for the organisation", async () => {+ mockGetCurrentProjectForOrganisation.mockResolvedValue(null);+ await expect(+ createMemoryConnector({ name: "X", type: "mem0" })+ ).rejects.toThrow(/no current project/i);+ expect(mockCreate).not.toHaveBeenCalled();+ });+it("creates a project-scoped memory connector and encrypts credentials without ClickHouse vault", async () => {mockCreate.mockResolvedValue(row({ secretRef: 'enc:v1:{"apiKey":"m0-key"}' }));const created = await createMemoryConnector({@@ -160,6 +191,13 @@ describe("memory connector CRUD", () => {).rejects.toThrow(/unknown memory connector/i);});+ it("rejects a blank type", async () => {+ await expect(+ createMemoryConnector({ name: "X", type: "" })+ ).rejects.toThrow(/unknown memory connector/i);+ expect(mockCreate).not.toHaveBeenCalled();+ });+it("rejects a duplicate name in the same environment", async () => {mockFindFirst.mockResolvedValue({ id: "memory:existing" });await expect(@@ -284,4 +322,535 @@ describe("memory connector CRUD", () => {const listed = await listMemoryConnectors();expect(listed.map((item) => item.id)).toEqual(["memory:abc"]);});++ it("rejects an environment name with invalid characters", async () => {+ await expect(+ createMemoryConnector({+ name: "Prod Mem0",+ type: "mem0",+ environment: "Prod!!",+ })+ ).rejects.toThrow(/letters, numbers, dots, hyphens, or underscores/i);+ expect(mockCreate).not.toHaveBeenCalled();+ });++ it("resolves the environment from the request header when none is given explicitly", async () => {+ (headers as jest.Mock).mockResolvedValueOnce({+ get: (key: string) =>+ key === "x-openlit-environment" ? "staging" : null,+ });+ mockFindMany.mockResolvedValue([row({ environment: "staging" })]);+ await listMemoryConnectors();+ expect(mockFindMany).toHaveBeenCalledWith(+ expect.objectContaining({+ where: expect.objectContaining({ environment: "staging" }),+ })+ );+ });++ it("falls back to production when reading headers throws outside a request", async () => {+ (headers as jest.Mock).mockRejectedValueOnce(new Error("no request context"));+ mockFindMany.mockResolvedValue([row()]);+ await listMemoryConnectors();+ expect(mockFindMany).toHaveBeenCalledWith(+ expect.objectContaining({+ where: expect.objectContaining({ environment: "production" }),+ })+ );+ });++ it("rejects settings that are not valid JSON", async () => {+ await expect(+ createMemoryConnector({+ name: "Prod Mem0",+ type: "mem0",+ settings: "{not json",+ })+ ).rejects.toThrow(/must be a json object/i);+ });++ it("rejects settings that parse to a non-object", async () => {+ await expect(+ createMemoryConnector({+ name: "Prod Mem0",+ type: "mem0",+ settings: "[1,2,3]",+ })+ ).rejects.toThrow(/must be a json object/i);+ await expect(+ createMemoryConnector({+ name: "Prod Mem0",+ type: "mem0",+ settings: 42,+ })+ ).rejects.toThrow(/must be a json object/i);+ });++ it("accepts settings passed as a JSON string and normalizes the endpoint url", async () => {+ mockCreate.mockResolvedValue(row());+ await createMemoryConnector({+ name: "Prod Mem0",+ type: "mem0",+ settings: '{"url":"https://api.mem0.ai/"}',+ });+ expect(JSON.parse(mockCreate.mock.calls[0][0].data.settings)).toEqual(+ expect.objectContaining({ url: "https://api.mem0.ai" })+ );+ });++ it("checks whether a type is a known memory connector type", () => {+ expect(isMemoryConnectorType("mem0")).toBe(true);+ mockHasMemoryAdapterFactory.mockReturnValueOnce(false);+ expect(isMemoryConnectorType("unknown")).toBe(false);+ });++ it("treats a blank/missing type as not a known memory connector type", () => {+ mockHasMemoryAdapterFactory.mockImplementation((type: unknown) => !!type);+ expect(isMemoryConnectorType("")).toBe(false);+ expect(isMemoryConnectorType(undefined)).toBe(false);+ });++ it("lists available memory type descriptors with category and scope metadata", () => {+ (listMemoryTypeDescriptors as jest.Mock).mockReturnValue([+ { type: "mem0", displayName: "Mem0", description: "", icon: "" },+ ]);+ const descriptors = availableMemoryTypeDescriptors();+ expect(descriptors).toEqual([+ expect.objectContaining({+ type: "mem0",+ category: "memory",+ scope: "project",+ declaredSignals: [],+ }),+ ]);+ });++ it("keeps a descriptor's own description and icon instead of the generated defaults", () => {+ (listMemoryTypeDescriptors as jest.Mock).mockReturnValue([+ {+ type: "mem0",+ displayName: "Mem0",+ description: "Already described",+ icon: "/already.svg",+ },+ ]);+ const descriptors = availableMemoryTypeDescriptors();+ expect(descriptors[0]).toMatchObject({+ description: "Already described",+ icon: "/already.svg",+ });+ });++ it("reads and records port links on a memory connector", async () => {+ mockFindFirst.mockResolvedValue(+ row({+ metadata: JSON.stringify({+ category: "memory",+ memoryPorts: [+ {+ sourceConnectorId: "memory:src",+ sourceMemoryId: "m1",+ copiedAt: "2026-08-18T00:00:00.000Z",+ contentFingerprint: "fp1",+ },+ { sourceConnectorId: "", sourceMemoryId: "" },+ "not-an-object",+ ],+ }),+ })+ );+ await expect(readMemoryPortLinks("abc")).resolves.toEqual([+ expect.objectContaining({ sourceConnectorId: "memory:src", sourceMemoryId: "m1" }),+ ]);++ // A required-fields-only entry: optional fields fall back to "" or+ // undefined instead of throwing.+ mockFindFirst.mockResolvedValue(+ row({+ metadata: JSON.stringify({+ memoryPorts: [+ { sourceConnectorId: "memory:src", sourceMemoryId: "m2" },+ ],+ }),+ })+ );+ await expect(readMemoryPortLinks("abc")).resolves.toEqual([+ expect.objectContaining({+ sourceConnectorId: "memory:src",+ sourceMemoryId: "m2",+ sourceConnectorType: undefined,+ sourceConnectorName: undefined,+ originConnectorId: undefined,+ originMemoryId: undefined,+ destMemoryId: undefined,+ copiedAt: "",+ contentFingerprint: "",+ }),+ ]);++ mockUpdate.mockResolvedValue(row());+ await recordMemoryPortLinks("abc", [+ {+ sourceConnectorId: "memory:src2",+ sourceMemoryId: "m2",+ copiedAt: "2026-08-19T00:00:00.000Z",+ contentFingerprint: "fp2",+ },+ ]);+ const stored = JSON.parse(mockUpdate.mock.calls[0][0].data.metadata).memoryPorts;+ expect(stored).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ sourceConnectorId: "memory:src2", sourceMemoryId: "m2" }),+ ])+ );+ });++ it("does nothing when recording an empty list of port links", async () => {+ await recordMemoryPortLinks("abc", []);+ expect(mockFindFirst).not.toHaveBeenCalled();+ expect(mockUpdate).not.toHaveBeenCalled();+ });++ it("throws when recording port links on a missing connector", async () => {+ mockFindFirst.mockResolvedValue(null);+ await expect(+ recordMemoryPortLinks("missing", [+ {+ sourceConnectorId: "memory:src",+ sourceMemoryId: "m1",+ copiedAt: "2026-08-18T00:00:00.000Z",+ contentFingerprint: "fp1",+ },+ ])+ ).rejects.toThrow(/not found/i);+ });++ it("does not persist remembered filters that are already known", async () => {+ mockFindFirst.mockResolvedValue(+ row({+ metadata: JSON.stringify({+ category: "memory",+ memoryFilters: { users: ["ada"], sessions: [], agents: [] },+ }),+ })+ );+ await rememberMemoryFilters("abc", { users: ["ada"] });+ expect(mockUpdate).not.toHaveBeenCalled();+ });++ it("does nothing when remembering an empty filter patch", async () => {+ await rememberMemoryFilters("abc", {});+ expect(mockFindFirst).not.toHaveBeenCalled();+ });++ it("throws when remembering filters on a missing connector", async () => {+ mockFindFirst.mockResolvedValue(null);+ await expect(rememberMemoryFilters("missing", { users: ["ada"] })).rejects.toThrow(+ /not found/i+ );+ });++ it("updates the connector environment and detects a name/environment clash", async () => {+ mockFindFirst.mockImplementation(async (args: { where: Record<string, unknown> }) => {+ if (args.where && "NOT" in args.where) return { id: "memory:other" };+ return row();+ });+ await expect(+ updateMemoryConnector("abc", {+ name: "New Name",+ environment: "development",+ })+ ).rejects.toThrow(/already exists/i);+ });++ it("updates credentials and invalidates the previous secret cache", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockUpdate.mockResolvedValue(row());+ const updated = await updateMemoryConnector("abc", {+ credentials: { apiKey: "new-key" },+ });+ expect(mockUpdate.mock.calls[0][0].data.secretRef).toContain("new-key");+ expect(updated.hasSecret).toBe(true);+ });++ it("rejects updating with an inline unencrypted secretRef", async () => {+ mockFindFirst.mockResolvedValue(row());+ await expect(+ updateMemoryConnector("abc", { secretRef: "plain-vault-id" })+ ).rejects.toThrow(/store its API key on the connector/i);+ });++ it("rejects updating a connector that no longer exists", async () => {+ mockFindFirst.mockResolvedValue(null);+ await expect(+ updateMemoryConnector("missing", { name: "New Name" })+ ).rejects.toThrow(/not found/i);+ });++ it("rejects clearing the connector name on update", async () => {+ mockFindFirst.mockResolvedValue(row());+ await expect(updateMemoryConnector("abc", { name: " " })).rejects.toThrow(+ /name is required/i+ );+ });++ it("rejects an explicitly blank (but defined) connector name on update", async () => {+ mockFindFirst.mockResolvedValue(row());+ await expect(updateMemoryConnector("abc", { name: "" })).rejects.toThrow(+ /name is required/i+ );+ });++ it("validates a null secretRef when neither credentials nor secretRef change", async () => {+ mockFindFirst.mockResolvedValue(row({ secretRef: null }));+ mockUpdate.mockResolvedValue(row({ secretRef: null }));+ const updated = await updateMemoryConnector("abc", { settings: { url: "https://x" } });+ expect(updated.hasSecret).toBe(false);+ });++ it("invalidates the secret cache with undefined when the prior secretRef was empty", async () => {+ mockFindFirst.mockResolvedValue(row({ secretRef: null }));+ mockUpdate.mockResolvedValue(row({ secretRef: 'enc:v1:{"apiKey":"new-key"}' }));+ const updated = await updateMemoryConnector("abc", {+ credentials: { apiKey: "new-key" },+ });+ expect(updated.hasSecret).toBe(true);+ });++ it("gets the runtime for a specific connector id", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockCreateMemoryAdapter.mockReturnValue({ healthCheck: async () => ({ ok: true }) });+ const runtime = await getMemoryRuntime("abc");+ expect(runtime.connector.id).toBe("memory:abc");+ expect(runtime.adapter).toBeDefined();+ });++ it("gets the runtime for the first connector when no id is given", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockCreateMemoryAdapter.mockReturnValue({ healthCheck: async () => ({ ok: true }) });+ await getMemoryRuntime();+ expect(mockFindFirst).toHaveBeenCalledWith(+ expect.objectContaining({ orderBy: [{ createdAt: "asc" }] })+ );+ });++ it("throws when no memory connector exists for the runtime lookup", async () => {+ mockFindFirst.mockResolvedValue(null);+ await expect(getMemoryRuntime("missing")).rejects.toThrow(/not found/i);+ });++ it("throws when the runtime adapter type is no longer registered", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockCreateMemoryAdapter.mockReturnValue(undefined);+ await expect(getMemoryRuntime("abc")).rejects.toThrow(/unknown memory connector/i);+ });++ it("throws healthCheckMemoryConnector when the adapter type is no longer registered", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockCreateMemoryAdapter.mockReturnValue(undefined);+ await expect(healthCheckMemoryConnector("abc")).rejects.toThrow(+ /unknown memory connector/i+ );+ });++ it("returns an empty remembered-filters shape by default", () => {+ expect(emptyRememberedMemoryFilters()).toEqual({+ users: [],+ sessions: [],+ agents: [],+ });+ });++ it("dedupes remembered filter ids given as objects with an id field", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockUpdate.mockResolvedValue(row());+ await rememberMemoryFilters("abc", {+ users: [{ id: "ada" } as unknown as string, { id: "ada" } as unknown as string, { id: "" } as unknown as string],+ });+ expect(JSON.parse(mockUpdate.mock.calls[0][0].data.metadata).memoryFilters).toEqual({+ users: ["ada"],+ sessions: [],+ agents: [],+ });+ });++ it("ignores filter entries that are neither strings nor plain id objects", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockUpdate.mockResolvedValue(row());+ await rememberMemoryFilters("abc", {+ users: [+ 42 as unknown as string,+ null as unknown as string,+ ["nested"] as unknown as string,+ "ada",+ ],+ });+ expect(JSON.parse(mockUpdate.mock.calls[0][0].data.metadata).memoryFilters).toEqual({+ users: ["ada"],+ sessions: [],+ agents: [],+ });+ });++ it("treats non-object remembered filter metadata as empty", async () => {+ mockFindFirst.mockResolvedValue(+ row({+ metadata: JSON.stringify({ category: "memory", memoryFilters: "not-an-object" }),+ })+ );+ await expect(readRememberedMemoryFilters("abc")).resolves.toEqual({+ users: [],+ sessions: [],+ agents: [],+ });+ });++ it("treats malformed metadata JSON as empty when reading port links", async () => {+ mockFindFirst.mockResolvedValue(row({ metadata: "{not json" }));+ await expect(readMemoryPortLinks("abc")).resolves.toEqual([]);+ });++ it("treats a missing metadata string as empty when reading port links", async () => {+ mockFindFirst.mockResolvedValue(row({ metadata: "" }));+ await expect(readMemoryPortLinks("abc")).resolves.toEqual([]);+ });++ it("treats a missing metadata string as an empty object when recording port links", async () => {+ mockFindFirst.mockResolvedValue(row({ metadata: "" }));+ mockUpdate.mockResolvedValue(row());+ await recordMemoryPortLinks("abc", [+ {+ sourceConnectorId: "memory:src",+ sourceMemoryId: "m1",+ copiedAt: "2026-08-18T00:00:00.000Z",+ contentFingerprint: "fp1",+ },+ ]);+ const metadata = JSON.parse(mockUpdate.mock.calls[0][0].data.metadata);+ expect(metadata.memoryPorts).toHaveLength(1);+ });++ it("treats a missing metadata string as empty when reading remembered filters", async () => {+ mockFindFirst.mockResolvedValue(row({ metadata: "" }));+ await expect(readRememberedMemoryFilters("abc")).resolves.toEqual({+ users: [],+ sessions: [],+ agents: [],+ });+ });++ it("treats a missing existing metadata string as empty when remembering filters", async () => {+ mockFindFirst.mockResolvedValue(row({ metadata: "" }));+ mockUpdate.mockResolvedValue(row());+ await rememberMemoryFilters("abc", { users: ["ada"] });+ expect(JSON.parse(mockUpdate.mock.calls[0][0].data.metadata).memoryFilters).toEqual({+ users: ["ada"],+ sessions: [],+ agents: [],+ });+ });++ it("treats malformed settings JSON as an empty object in the runtime descriptor", async () => {+ mockFindFirst.mockResolvedValue(row({ settings: "{not json" }));+ mockCreateMemoryAdapter.mockReturnValue({ healthCheck: async () => ({ ok: true }) });+ await getMemoryRuntime("abc");+ expect(mockCreateMemoryAdapter.mock.calls[0][0].settings).toEqual({});+ });++ it("treats settings that parse to a JSON array as an empty object in the runtime descriptor", async () => {+ mockFindFirst.mockResolvedValue(row({ settings: "[1,2,3]" }));+ mockCreateMemoryAdapter.mockReturnValue({ healthCheck: async () => ({ ok: true }) });+ await getMemoryRuntime("abc");+ expect(mockCreateMemoryAdapter.mock.calls[0][0].settings).toEqual({});+ });++ it("treats settings that parse to a non-object primitive as an empty object in the runtime descriptor", async () => {+ mockFindFirst.mockResolvedValue(row({ settings: "42" }));+ mockCreateMemoryAdapter.mockReturnValue({ healthCheck: async () => ({ ok: true }) });+ await getMemoryRuntime("abc");+ expect(mockCreateMemoryAdapter.mock.calls[0][0].settings).toEqual({});+ });++ it("treats metadata that parses to a non-object primitive as empty when reading port links", async () => {+ mockFindFirst.mockResolvedValue(row({ metadata: "42" }));+ await expect(readMemoryPortLinks("abc")).resolves.toEqual([]);+ });++ it("skips a malformed entry already stored in metadata when recording new port links", async () => {+ mockFindFirst.mockResolvedValue(+ row({+ metadata: JSON.stringify({+ memoryPorts: [{ sourceConnectorId: "", sourceMemoryId: "" }],+ }),+ })+ );+ mockUpdate.mockResolvedValue(row());+ await recordMemoryPortLinks("abc", [+ {+ sourceConnectorId: "memory:src",+ sourceMemoryId: "m1",+ copiedAt: "2026-08-18T00:00:00.000Z",+ contentFingerprint: "fp1",+ },+ ]);+ const stored = JSON.parse(mockUpdate.mock.calls[0][0].data.metadata).memoryPorts;+ expect(stored).toHaveLength(1);+ });++ it("defaults sanitized metadata to an empty object when the stored row has none", async () => {+ mockCreate.mockResolvedValue(row({ metadata: null as unknown as string }));+ const created = await createMemoryConnector({ name: "Prod Mem0", type: "mem0" });+ expect(JSON.parse(created.metadata)).toEqual({});+ });++ it("rejects a type marked internal by its descriptor", async () => {+ mockGetMemoryTypeDescriptor.mockReturnValue({ type: "internal-only", internal: true });+ await expect(+ createMemoryConnector({ name: "X", type: "internal-only" })+ ).rejects.toThrow(/unknown memory connector/i);+ expect(mockCreate).not.toHaveBeenCalled();+ });++ it("ignores credentials whose values are all blank or non-string", async () => {+ mockCreate.mockResolvedValue(row({ secretRef: null }));+ await createMemoryConnector({+ name: "Prod Mem0",+ type: "mem0",+ credentials: { apiKey: " ", count: 5 },+ });+ expect(mockCreate.mock.calls[0][0].data.secretRef).toBeNull();+ });++ it("leaves environment/organisationId nullish when the stored row has none", async () => {+ mockFindFirst.mockResolvedValue(+ row({ organisationId: null, environment: "", secretRef: null })+ );+ mockCreateMemoryAdapter.mockReturnValue({ healthCheck: async () => ({ ok: true }) });+ const runtime = await getMemoryRuntime("abc");+ expect(runtime.connector.organisationId).toBeNull();+ expect(runtime.connector.hasSecret).toBe(false);+ expect(mockCreateMemoryAdapter.mock.calls[0][0].environment).toBeUndefined();+ });++ it("skips invalidating the secret cache when deleting a connector without a secretRef", async () => {+ mockFindFirst.mockResolvedValue(row({ secretRef: null }));+ mockDelete.mockResolvedValue({});+ await deleteMemoryConnector("abc");+ expect(mockDelete).toHaveBeenCalled();+ });++ it("rejects deleting a connector that no longer exists", async () => {+ mockFindFirst.mockResolvedValue(null);+ await expect(deleteMemoryConnector("missing")).rejects.toThrow(/not found/i);+ expect(mockDelete).not.toHaveBeenCalled();+ });++ it("throws when reading port links for a missing connector", async () => {+ mockFindFirst.mockResolvedValue(null);+ await expect(readMemoryPortLinks("missing")).rejects.toThrow(/not found/i);+ });++ it("resolves an empty id to just the memory connector prefix", () => {+ expect(isMemoryConnectorId("")).toBe(false);+ });});diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-graph.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-graph.test.tsindex 828806e0..a0198d2d 100644--- a/src/client/src/__tests__/lib/platform/connectors/memory-graph.test.ts+++ b/src/client/src/__tests__/lib/platform/connectors/memory-graph.test.ts@@ -1,9 +1,13 @@import {buildMemoryGraph,+ classifyEntityType,classifyMemoryKind,layoutMemoryGraph,+ radialEdgePoints,summarizeMemoryStats,+ type MemoryGraphModel,} from "@/lib/platform/connectors/memory/graph";+import { MEMORY_UNKNOWN_USER } from "@/constants/messages/en";import type { MemoryRecord } from "@/lib/platform/connectors/memory/types";function record(over: Partial<MemoryRecord> = {}): MemoryRecord {@@ -31,6 +35,16 @@ describe("memory graph helpers", () => {expect(classifyMemoryKind(record())).toBe("summary");});+ it("classifies summary from metadata and temporal from content when metadata is silent", () => {+ expect(+ classifyMemoryKind(record({ metadata: { category: "semantic" } }))+ ).toBe("summary");+ expect(classifyMemoryKind(record({ content: "" }))).toBe("summary");+ expect(+ classifyMemoryKind(record({ content: "We met yesterday for coffee" }))+ ).toBe("temporal");+ });+it("summarizes counts and unique connections", () => {const stats = summarizeMemoryStats([record({@@ -60,6 +74,16 @@ describe("memory graph helpers", () => {);});+ it("keys connections with a placeholder when only one side of the pair is known", () => {+ const stats = summarizeMemoryStats([+ record({ id: "1", userId: "ada" }),+ record({ id: "2", sessionId: "s1" }),+ ]);+ expect(stats.connections).toBe(2);+ expect(stats.users).toBe(1);+ expect(stats.sessions).toBe(1);+ });+it("builds user → session → memory edges", () => {const graph = buildMemoryGraph([record({ id: "mem-1", userId: "ada", sessionId: "run-9" }),@@ -75,6 +99,46 @@ describe("memory graph helpers", () => {]);});+ it("falls back to the record id as the memory label when content has no first line", () => {+ const graph = buildMemoryGraph([record({ id: "mem-empty", content: "" })]);+ const memoryNode = graph.nodes.find((node) => node.type === "memory");+ expect(memoryNode?.label).toBe("mem-empty");+ });++ it("truncates long memory titles to 48 characters with an ellipsis", () => {+ const longLine =+ "This first line of the memory content is deliberately long enough to be truncated";+ const graph = buildMemoryGraph([record({ id: "mem-long", content: longLine })]);+ const memoryNode = graph.nodes.find((node) => node.type === "memory");+ expect(memoryNode?.label).toHaveLength(46);+ expect(memoryNode?.label?.endsWith("…")).toBe(true);+ });++ it("groups memories under an unknown-user placeholder when userId is missing", () => {+ const graph = buildMemoryGraph([record({ id: "mem-1" })]);+ expect(graph.nodes).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ id: "user:unknown", label: MEMORY_UNKNOWN_USER }),+ ])+ );+ expect(graph.edges).toEqual(+ expect.arrayContaining([{ from: "user:unknown", to: "memory:mem-1", memoryId: "mem-1" }])+ );+ });++ it("respects a custom maxMemories option", () => {+ const graph = buildMemoryGraph(+ [+ record({ id: "a", userId: "u1" }),+ record({ id: "b", userId: "u1" }),+ record({ id: "c", userId: "u1" }),+ ],+ { maxMemories: 1 }+ );+ const memoryNodes = graph.nodes.filter((node) => node.type === "memory");+ expect(memoryNodes).toHaveLength(1);+ });+it("lays out nodes with coordinates", () => {const laid = layoutMemoryGraph(buildMemoryGraph([@@ -111,6 +175,77 @@ describe("memory graph helpers", () => {).toBe(true);});+ it("classifies unknown or missing entity type labels as a generic entity", () => {+ expect(classifyEntityType(undefined)).toBe("entity");+ expect(classifyEntityType(["mystery-type", "Node"])).toBe("entity");+ });++ it("skips relation facts missing a source or target id", () => {+ const graph = buildMemoryGraph([+ record({+ id: "broken",+ relation: {+ source: { id: "", label: "No id" },+ target: { id: "n-loc", label: "Austin" },+ },+ }),+ record({+ id: "ok",+ relation: {+ source: { id: "n-user", label: "Sarah", types: ["User"] },+ target: { id: "n-loc-2", label: "Berlin", types: ["Location"] },+ },+ }),+ ]);+ expect(graph.kind).toBe("knowledge");+ expect(graph.nodes.some((node) => node.id === "n-loc")).toBe(false);+ expect(graph.edges).toEqual([+ { from: "n-user", to: "n-loc-2", memoryId: "ok", label: undefined },+ ]);+ });++ it("dedupes relation endpoints shared across facts and falls back to the id for blank labels", () => {+ const graph = buildMemoryGraph([+ record({+ id: "e1",+ relation: {+ source: { id: "n-user", label: " ", types: ["User"] },+ target: { id: "n-topic", label: "Tracing", types: ["Topic"] },+ },+ }),+ record({+ id: "e2",+ relation: {+ source: { id: "n-user", label: "Sarah", types: ["User"] },+ target: { id: "n-loc", label: "Austin", types: ["Location"] },+ },+ }),+ ]);+ const userNodes = graph.nodes.filter((node) => node.id === "n-user");+ expect(userNodes).toHaveLength(1);+ expect(userNodes[0].label).toBe("n-user");+ });++ it("falls back to titleFromContent for graph-only nodes without a string metadata name", () => {+ const graph = buildMemoryGraph([+ record({+ id: "e1",+ relation: {+ source: { id: "n-user", label: "Sarah", types: ["User"] },+ target: { id: "n-loc", label: "Austin", types: ["Location"] },+ },+ }),+ record({+ id: "n-extra",+ content: "Observability platform notes",+ graphOnly: true,+ metadata: { name: 42 },+ }),+ ]);+ const extraNode = graph.nodes.find((node) => node.id === "n-extra");+ expect(extraNode?.label).toBe("Observability platform notes");+ });+it("builds an entity knowledge graph from relation endpoints", () => {const graph = buildMemoryGraph([record({@@ -174,4 +309,122 @@ describe("memory graph helpers", () => {true);});++ it("returns an empty layout for an empty knowledge graph", () => {+ expect(layoutMemoryGraph({ nodes: [], edges: [], kind: "knowledge" })).toEqual([]);+ });++ it("returns an empty layout for an empty session-tree graph", () => {+ expect(layoutMemoryGraph({ nodes: [], edges: [] })).toEqual([]);+ });++ it("skips knowledge-graph edges that reference a node outside the model", () => {+ const model: MemoryGraphModel = {+ kind: "knowledge",+ nodes: [+ { id: "n-a", type: "entity", entityType: "topic", label: "A" },+ { id: "n-b", type: "entity", entityType: "topic", label: "B" },+ ],+ edges: [{ from: "n-a", to: "missing-node" }],+ };+ const laid = layoutMemoryGraph(model);+ expect(laid).toHaveLength(2);+ expect(laid.every((node) => Number.isFinite(node.x) && Number.isFinite(node.y))).toBe(+ true+ );+ });++ it("keeps a stable layout when nodes coincide and Math.hypot reports zero distance", () => {+ const hypotSpy = jest.spyOn(Math, "hypot").mockReturnValue(0);+ try {+ const model: MemoryGraphModel = {+ kind: "knowledge",+ nodes: [+ { id: "n-a", type: "entity", entityType: "topic", label: "A" },+ { id: "n-b", type: "entity", entityType: "topic", label: "B" },+ ],+ edges: [{ from: "n-a", to: "n-b" }],+ };+ const laid = layoutMemoryGraph(model);+ expect(laid).toHaveLength(2);+ expect(+ laid.every((node) => Number.isFinite(node.x) && Number.isFinite(node.y))+ ).toBe(true);+ } finally {+ hypotSpy.mockRestore();+ }+ });++ it("falls back to root nodes for tree layout when no user node exists", () => {+ const model: MemoryGraphModel = {+ nodes: [+ { id: "memory:only", type: "memory", label: "Standalone note" },+ ],+ edges: [],+ };+ const laid = layoutMemoryGraph(model);+ expect(laid).toHaveLength(1);+ expect(laid[0].id).toBe("memory:only");+ });++ it("places orphan nodes that are not reachable from any root", () => {+ const model: MemoryGraphModel = {+ nodes: [+ { id: "user:ada", type: "user", label: "ada" },+ { id: "memory:m1", type: "memory", label: "one", memoryId: "m1" },+ { id: "memory:orphan", type: "memory", label: "orphan", memoryId: "orphan" },+ ],+ edges: [{ from: "user:ada", to: "memory:m1", memoryId: "m1" }],+ };+ const laid = layoutMemoryGraph(model);+ expect(laid).toHaveLength(3);+ const orphan = laid.find((node) => node.id === "memory:orphan");+ expect(orphan).toBeDefined();+ expect(Number.isFinite(orphan?.x)).toBe(true);+ expect(Number.isFinite(orphan?.y)).toBe(true);+ });+});++describe("radialEdgePoints", () => {+ const origin = { x: 0, y: 0 };++ it("interpolates points along an arc between two radii", () => {+ const points = radialEdgePoints({ x: 100, y: 0 }, { x: 0, y: 100 }, origin);+ expect(points).toHaveLength(9);+ expect(points[0].x).toBeCloseTo(100);+ expect(points[0].y).toBeCloseTo(0);+ expect(points[points.length - 1].x).toBeCloseTo(0);+ expect(points[points.length - 1].y).toBeCloseTo(100);+ });++ it("uses the target angle when the origin point sits on the origin", () => {+ const points = radialEdgePoints(origin, { x: 0, y: 100 }, origin);+ expect(points[0].x).toBeCloseTo(0);+ expect(points[0].y).toBeCloseTo(0);+ expect(points[points.length - 1].y).toBeCloseTo(100);+ });++ it("wraps a large positive angular delta into the shortest path", () => {+ const angleFrom = -3;+ const angleTo = 3;+ const from = { x: 100 * Math.cos(angleFrom), y: 100 * Math.sin(angleFrom) };+ const to = { x: 100 * Math.cos(angleTo), y: 100 * Math.sin(angleTo) };+ const points = radialEdgePoints(from, to, origin, 4);+ expect(points).toHaveLength(5);+ expect(points.every((point) => Number.isFinite(point.x) && Number.isFinite(point.y))).toBe(+ true+ );+ });++ it("wraps a large negative angular delta into the shortest path", () => {+ const angleFrom = 3;+ const angleTo = -3;+ const from = { x: 100 * Math.cos(angleFrom), y: 100 * Math.sin(angleFrom) };+ const to = { x: 100 * Math.cos(angleTo), y: 100 * Math.sin(angleTo) };+ const points = radialEdgePoints(from, to, origin, 4);+ expect(points).toHaveLength(5);+ expect(points.every((point) => Number.isFinite(point.x) && Number.isFinite(point.y))).toBe(+ true+ );+ });});diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-port.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-port.test.tsindex fa8b5c0d..eafbc5f5 100644--- a/src/client/src/__tests__/lib/platform/connectors/memory-port.test.ts+++ b/src/client/src/__tests__/lib/platform/connectors/memory-port.test.ts@@ -34,6 +34,51 @@ describe("memory port links", () => {expect(parseMemoryPortLink({ memory_type: "temporal" })).toBeUndefined();});+ it("defaults copiedAt and contentFingerprint to empty strings when absent", () => {+ const link = parseMemoryPortLink({+ openlit: {+ port: {+ sourceConnectorId: "memory:src",+ sourceMemoryId: "mem-1",+ sourceConnectorType: " ",+ },+ },+ });+ expect(link).toEqual(+ expect.objectContaining({+ sourceConnectorId: "memory:src",+ sourceMemoryId: "mem-1",+ sourceConnectorType: undefined,+ copiedAt: "",+ contentFingerprint: "",+ })+ );+ });++ it("hashes content without a userId", () => {+ const withUser = memoryContentFingerprint("Prefers dark mode", "ada");+ const withoutUser = memoryContentFingerprint("Prefers dark mode");+ expect(withoutUser).toEqual(expect.any(String));+ expect(withoutUser).not.toBe(withUser);+ });++ it("builds port metadata without merging into any existing metadata", () => {+ const link = {+ sourceConnectorId: "memory:src",+ sourceMemoryId: "mem-1",+ copiedAt: "2026-08-18T12:00:00.000Z",+ contentFingerprint: "abc123",+ };+ const metadata = memoryPortMetadata(link);+ expect(metadata).toEqual(+ expect.objectContaining({+ openlit: expect.objectContaining({+ port: expect.objectContaining({ sourceMemoryId: "mem-1" }),+ }),+ })+ );+ });+it("matches stored links by destination id or content fingerprint", () => {const fingerprint = memoryContentFingerprint("Prefers tabs", "ada");const attached = attachMemoryPorts<MemoryRecord>(diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-read.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-read.test.tsindex a0efe635..f2e8c9a3 100644--- a/src/client/src/__tests__/lib/platform/connectors/memory-read.test.ts+++ b/src/client/src/__tests__/lib/platform/connectors/memory-read.test.ts@@ -1,5 +1,10 @@const mockListMemoryConnectors = jest.fn();const mockGetMemoryRuntime = jest.fn();+const mockGetMemoryTypeDescriptor = jest.fn();++jest.mock("@/lib/platform/connectors/memory/registry", () => ({+ getMemoryTypeDescriptor: (...a: unknown[]) => mockGetMemoryTypeDescriptor(...a),+}));jest.mock("@/lib/platform/connectors/memory/crud", () => ({listMemoryConnectors: (...a: unknown[]) => mockListMemoryConnectors(...a),@@ -16,13 +21,25 @@ jest.mock("@/lib/platform/connectors/memory/crud", () => ({String(id).startsWith("memory:") ? id : `memory:${id}`,}));-import { getProjectMemory, queryProjectMemories, submitProjectMemoryFeedback } from "@/lib/platform/connectors/memory/read";+import {+ getProjectMemory,+ queryProjectMemories,+ resolveProjectMemoryAdapter,+ submitProjectMemoryFeedback,+} from "@/lib/platform/connectors/memory/read";import { readRememberedMemoryFilters } from "@/lib/platform/connectors/memory/crud";+import { UnsupportedMemoryCapabilityError } from "@/lib/platform/connectors/memory/types";+import { getMemoryTypeDescriptor } from "@/lib/platform/connectors/memory/registry";+import { SourceResponseError } from "@/lib/platform/connectors/datasource/http/safe-fetch";import {MEMORY_CONNECTOR_FILTER_REQUIRED,+ MEMORY_CONNECTOR_NOT_FOUND,+ MEMORY_CONNECTOR_QUERY_REQUIRED,MEMORY_CONNECTOR_SESSION_REQUIRED,MEMORY_DETAIL_FEEDBACK_UNSUPPORTED,MEMORY_DETAIL_NOT_FOUND,+ MEMORY_FEEDBACK_INVALID,+ MEMORY_FEEDBACK_REASON_TOO_LONG,} from "@/constants/messages/en";const connector = {@@ -36,6 +53,7 @@ const connector = {describe("queryProjectMemories", () => {beforeEach(() => {jest.clearAllMocks();+ mockGetMemoryTypeDescriptor.mockReturnValue(undefined);});it("returns an empty payload when the project has no memory connectors", async () => {@@ -295,6 +313,388 @@ describe("queryProjectMemories", () => {expect(result.hint).toBe("unavailable");expect(result.memories).toEqual([]);});++ it("uses the descriptor's own filter fields instead of the fallback when provided", async () => {+ mockGetMemoryTypeDescriptor.mockReturnValue({+ filterFields: [{ key: "custom", label: "Custom", allowCustom: false }],+ capabilities: { add: true },+ });+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list: async () => [],+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories();+ expect(result.filterFields).toEqual([+ { key: "custom", label: "Custom", allowCustom: false },+ ]);+ expect(result.connector?.capabilities).toEqual({ add: true });+ });++ it("clamps a non-numeric limit down to the default", async () => {+ const list = jest.fn().mockResolvedValue([]);+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list,+ search: jest.fn(),+ },+ });++ await queryProjectMemories({ limit: Number.NaN });+ expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 50 }));+ });++ it("keys remembered sessions to their owning user when both are known", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list: async () => [],+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories({ userId: "ada", sessionId: "run-1" });+ expect(result.filters.sessions).toEqual([+ { id: "run-1", label: "run-1", userId: "ada" },+ ]);+ });++ it("derives session filter choices from returned memory records", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list: async () => [+ { id: "m1", content: "hi", userId: "ada", sessionId: "run-2" },+ ],+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories();+ expect(result.filters.sessions).toEqual([+ expect.objectContaining({ id: "run-2", userId: "ada" }),+ ]);+ });++ it("falls back to empty filters when listFilters throws", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ listFilters: async () => {+ throw new Error("boom");+ },+ list: async () => [],+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories();+ expect(result.filters).toEqual({ users: [], sessions: [], agents: [] });+ });++ it("rejects a search query when the adapter does not support search", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: false,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list: jest.fn(),+ search: jest.fn(),+ },+ });++ await expect(queryProjectMemories({ query: "hello" })).rejects.toThrow(+ MEMORY_CONNECTOR_QUERY_REQUIRED+ );+ });++ it("clamps limits above the max and below the minimum, and floors decimals", async () => {+ const list = jest.fn().mockResolvedValue([]);+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list,+ search: jest.fn(),+ },+ });++ await queryProjectMemories({ limit: 5000 });+ expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 100 }));++ await queryProjectMemories({ limit: -3 });+ expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 1 }));++ await queryProjectMemories({ limit: 12.9 });+ expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 12 }));+ });++ it("dedupes filter choices that appear in more than one source", async () => {+ (readRememberedMemoryFilters as jest.Mock).mockResolvedValueOnce({+ users: ["ada"],+ sessions: [],+ agents: [],+ });+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ listFilters: async () => ({+ users: [{ id: "ada", label: "ada" }],+ sessions: [],+ agents: [],+ }),+ list: async () => [{ id: "m1", content: "hi", userId: "ada" }],+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories();+ expect(result.filters.users).toEqual([{ id: "ada", label: "ada" }]);+ });++ it("includes the requested agent in scoped filters and remembers agent ids from records", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list: async () => [{ id: "m1", content: "hi", agentId: "bot-1" }],+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories({ agentId: "bot-1" });+ expect(result.filters.agents).toEqual([{ id: "bot-1", label: "bot-1" }]);+ });++ it("tolerates memory records missing userId/agentId when remembering filters", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list: async () => [{ id: "m1", content: "no identity fields" }],+ search: jest.fn(),+ },+ });++ await expect(queryProjectMemories()).resolves.toEqual(+ expect.objectContaining({ memories: expect.any(Array) })+ );+ });++ it("reads the connector's status off a SourceResponseError instance", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list: async () => {+ throw new SourceResponseError(401, "API key is invalid.");+ },+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories();+ expect(result.hint).toBe("auth_failed");+ });++ it("stringifies a non-Error thrown value when computing the list-error hint", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list: async () => {+ throw "boom";+ },+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories();+ expect(result.hint).toBe("unavailable");+ });++ it("treats a falsy listFilters resolution as empty filters", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ listFilters: async () => undefined,+ list: async () => [],+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories();+ expect(result.filters).toEqual({ users: [], sessions: [], agents: [] });+ });++ it("throws when the requested connector id does not match any connector", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ await expect(+ queryProjectMemories({ connectorId: "does-not-exist" })+ ).rejects.toThrow(MEMORY_CONNECTOR_NOT_FOUND);+ });++ it("falls back to default filter fields and copy metadata when the connector has no type", async () => {+ mockListMemoryConnectors.mockResolvedValue([{ ...connector, type: undefined }]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector: { ...connector, type: undefined },+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list: async () => [],+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories();+ expect(result.filterFields.length).toBeGreaterThan(0);+ expect(result.connector?.capabilities).toBeNull();+ });++ it("returns an empty result with a hint when the search call fails", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list: jest.fn(),+ search: async () => {+ throw new Error("Data source responded 404: search unavailable");+ },+ },+ });++ const result = await queryProjectMemories({ query: "hello" });+ expect(result.hint).toBe("unavailable");+ expect(result.memories).toEqual([]);+ });});describe("getProjectMemory", () => {@@ -375,6 +775,79 @@ describe("getProjectMemory", () => {MEMORY_DETAIL_NOT_FOUND);});++ it("throws when the id is blank", async () => {+ await expect(getProjectMemory({ id: " " })).rejects.toThrow(+ MEMORY_DETAIL_NOT_FOUND+ );+ expect(mockListMemoryConnectors).not.toHaveBeenCalled();+ });++ it("returns a get_unsupported hint when the adapter rejects get() as unsupported", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ get: async () => {+ throw new UnsupportedMemoryCapabilityError("mem0", "get");+ },+ },+ });++ const result = await getProjectMemory({ id: "mem-1" });+ expect(result.hint).toBe("get_unsupported");+ expect(result.memory).toBeNull();+ });++ it("rethrows unexpected errors from adapter.get", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ get: async () => {+ throw new Error("network down");+ },+ },+ });++ await expect(getProjectMemory({ id: "mem-1" })).rejects.toThrow("network down");+ });+});++describe("resolveProjectMemoryAdapter", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("throws when the project has no memory connectors", async () => {+ mockListMemoryConnectors.mockResolvedValue([]);+ await expect(resolveProjectMemoryAdapter()).rejects.toThrow(+ MEMORY_CONNECTOR_NOT_FOUND+ );+ });++ it("throws when the requested connector id does not match any connector", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ await expect(resolveProjectMemoryAdapter("does-not-exist")).rejects.toThrow(+ MEMORY_CONNECTOR_NOT_FOUND+ );+ });});describe("submitProjectMemoryFeedback", () => {@@ -447,4 +920,163 @@ describe("submitProjectMemoryFeedback", () => {submitProjectMemoryFeedback({ id: "mem-1", rating: "negative" })).rejects.toThrow(MEMORY_DETAIL_FEEDBACK_UNSUPPORTED);});++ it("throws when the id is blank", async () => {+ await expect(+ submitProjectMemoryFeedback({ id: " ", rating: "positive" })+ ).rejects.toThrow(MEMORY_DETAIL_NOT_FOUND);+ expect(mockListMemoryConnectors).not.toHaveBeenCalled();+ });++ it("rejects an invalid rating value", async () => {+ await expect(+ submitProjectMemoryFeedback({+ id: "mem-1",+ rating: "not-a-rating" as unknown as never,+ })+ ).rejects.toThrow(MEMORY_FEEDBACK_INVALID);+ expect(mockListMemoryConnectors).not.toHaveBeenCalled();+ });++ it("rejects a reason longer than the maximum length", async () => {+ await expect(+ submitProjectMemoryFeedback({+ id: "mem-1",+ rating: "positive",+ reason: "x".repeat(1001),+ })+ ).rejects.toThrow(MEMORY_FEEDBACK_REASON_TOO_LONG);+ expect(mockListMemoryConnectors).not.toHaveBeenCalled();+ });++ it("sends a null reason when none is provided", async () => {+ const feedback = jest.fn().mockResolvedValue({ rating: "positive" });+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: false,+ list: true,+ update: true,+ delete: true,+ feedback: true,+ }),+ feedback,+ },+ });++ await submitProjectMemoryFeedback({ id: "mem-1", rating: "positive" });+ expect(feedback).toHaveBeenCalledWith("mem-1", {+ rating: "positive",+ reason: null,+ });+ });++ it("normalizes an unsupported-capability error from adapter.feedback", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: false,+ list: true,+ update: true,+ delete: true,+ feedback: true,+ }),+ feedback: async () => {+ throw new UnsupportedMemoryCapabilityError("mem0", "feedback");+ },+ },+ });++ await expect(+ submitProjectMemoryFeedback({ id: "mem-1", rating: "positive" })+ ).rejects.toThrow(MEMORY_DETAIL_FEEDBACK_UNSUPPORTED);+ });++ it("rethrows unexpected errors from adapter.feedback", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: false,+ list: true,+ update: true,+ delete: true,+ feedback: true,+ }),+ feedback: async () => {+ throw new Error("vendor exploded");+ },+ },+ });++ await expect(+ submitProjectMemoryFeedback({ id: "mem-1", rating: "positive" })+ ).rejects.toThrow("vendor exploded");+ });++ it("falls back to the submitted feedback when the refreshed memory has none of its own", async () => {+ const feedback = jest.fn().mockResolvedValue({ rating: "positive", reason: "Accurate" });+ const get = jest.fn().mockResolvedValue({ id: "mem-1", content: "hello" });+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: true,+ }),+ feedback,+ get,+ },+ });++ const result = await submitProjectMemoryFeedback({+ id: "mem-1",+ rating: "positive",+ reason: "Accurate",+ });+ expect(result.memory?.feedback).toEqual({ rating: "positive", reason: "Accurate" });+ });++ it("leaves memory null when the post-feedback refresh fails", async () => {+ const feedback = jest.fn().mockResolvedValue({ rating: "positive" });+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: true,+ }),+ feedback,+ get: async () => {+ throw new Error("refresh failed");+ },+ },+ });++ const result = await submitProjectMemoryFeedback({ id: "mem-1", rating: "positive" });+ expect(result.memory).toBeNull();+ });});diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-write.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-write.test.tsindex 93094058..95875c64 100644--- a/src/client/src/__tests__/lib/platform/connectors/memory-write.test.ts+++ b/src/client/src/__tests__/lib/platform/connectors/memory-write.test.ts@@ -1,10 +1,11 @@const mockListMemoryConnectors = jest.fn();const mockGetMemoryRuntime = jest.fn();+const mockRememberMemoryFilters = jest.fn().mockResolvedValue(undefined);jest.mock("@/lib/platform/connectors/memory/crud", () => ({listMemoryConnectors: (...a: unknown[]) => mockListMemoryConnectors(...a),getMemoryRuntime: (...a: unknown[]) => mockGetMemoryRuntime(...a),- rememberMemoryFilters: jest.fn().mockResolvedValue(undefined),+ rememberMemoryFilters: (...a: unknown[]) => mockRememberMemoryFilters(...a),memoryConnectorId: (id: string) =>String(id).startsWith("memory:") ? id : `memory:${id}`,}));@@ -12,13 +13,17 @@ jest.mock("@/lib/platform/connectors/memory/crud", () => ({import {addProjectMemories,deleteProjectMemory,+ parseMemoryMessages,parseMemoryMetadata,updateProjectMemory,} from "@/lib/platform/connectors/memory/write";+import { UnsupportedMemoryCapabilityError } from "@/lib/platform/connectors/memory/types";import {MEMORY_ADD_UNSUPPORTED,MEMORY_CONNECTOR_CONTENT_REQUIRED,+ MEMORY_CONTENT_TOO_LONG,MEMORY_DELETE_UNSUPPORTED,+ MEMORY_DETAIL_NOT_FOUND,MEMORY_EDIT_UNSUPPORTED,MEMORY_INVALID_METADATA,} from "@/constants/messages/en";@@ -69,6 +74,48 @@ describe("addProjectMemories", () => {expect(result.connector).not.toHaveProperty("secretRef");});+ it("writes through the adapter using messages instead of content", async () => {+ const add = jest.fn().mockResolvedValue([+ { id: "m1", content: "Prefers tabs", userId: "ada" },+ ]);+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: { capabilities: () => capabilities, add },+ });++ await addProjectMemories({+ connectorId: "abc",+ messages: [{ role: "user", content: "hi" }],+ });+ expect(add).toHaveBeenCalledWith(+ expect.objectContaining({+ messages: [{ role: "user", content: "hi" }],+ })+ );+ });++ it("remembers session and agent ids returned by the adapter even without a userId", async () => {+ const add = jest.fn().mockResolvedValue([+ { id: "m1", content: "Prefers tabs", sessionId: "sess-1", agentId: "agent-1" },+ ]);+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: { capabilities: () => capabilities, add },+ });++ await addProjectMemories({ connectorId: "abc", content: "Prefers tabs" });+ expect(mockRememberMemoryFilters).toHaveBeenCalledWith(+ "memory:abc",+ expect.objectContaining({+ users: [],+ sessions: ["sess-1"],+ agents: ["agent-1"],+ })+ );+ });+it("rejects empty content", async () => {await expect(addProjectMemories({ content: " " })).rejects.toThrow(MEMORY_CONNECTOR_CONTENT_REQUIRED@@ -89,6 +136,41 @@ describe("addProjectMemories", () => {MEMORY_ADD_UNSUPPORTED);});++ it("rejects content longer than the max length", async () => {+ await expect(+ addProjectMemories({ content: "x".repeat(20_001) })+ ).rejects.toThrow(MEMORY_CONTENT_TOO_LONG);+ expect(mockGetMemoryRuntime).not.toHaveBeenCalled();+ });++ it("classifies an unsupported-capability error from the adapter as add-unsupported", async () => {+ const add = jest+ .fn()+ .mockRejectedValue(+ new UnsupportedMemoryCapabilityError("mem0", "add")+ );+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: { capabilities: () => capabilities, add },+ });+ await expect(addProjectMemories({ content: "hello" })).rejects.toThrow(+ MEMORY_ADD_UNSUPPORTED+ );+ });++ it("rethrows a generic adapter error unchanged", async () => {+ const add = jest.fn().mockRejectedValue(new Error("upstream down"));+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: { capabilities: () => capabilities, add },+ });+ await expect(addProjectMemories({ content: "hello" })).rejects.toThrow(+ "upstream down"+ );+ });});describe("updateProjectMemory", () => {@@ -117,6 +199,20 @@ describe("updateProjectMemory", () => {expect(result.memory.content).toBe("Prefers spaces");});+ it("rejects blank content", async () => {+ await expect(+ updateProjectMemory({ id: "m1", content: " " })+ ).rejects.toThrow(MEMORY_CONNECTOR_CONTENT_REQUIRED);+ expect(mockGetMemoryRuntime).not.toHaveBeenCalled();+ });++ it("rejects content longer than the max length", async () => {+ await expect(+ updateProjectMemory({ id: "m1", content: "x".repeat(20_001) })+ ).rejects.toThrow(MEMORY_CONTENT_TOO_LONG);+ expect(mockGetMemoryRuntime).not.toHaveBeenCalled();+ });+it("rejects vendors that cannot update", async () => {mockListMemoryConnectors.mockResolvedValue([{ ...connector, type: "zep" }]);mockGetMemoryRuntime.mockResolvedValue({@@ -130,6 +226,41 @@ describe("updateProjectMemory", () => {updateProjectMemory({ id: "m1", content: "hello" })).rejects.toThrow(MEMORY_EDIT_UNSUPPORTED);});++ it("rejects a blank id", async () => {+ await expect(+ updateProjectMemory({ id: " ", content: "hello" })+ ).rejects.toThrow(MEMORY_DETAIL_NOT_FOUND);+ expect(mockGetMemoryRuntime).not.toHaveBeenCalled();+ });++ it("classifies an unsupported-capability error from the adapter as edit-unsupported", async () => {+ const update = jest+ .fn()+ .mockRejectedValue(+ new UnsupportedMemoryCapabilityError("zep", "update")+ );+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: { capabilities: () => capabilities, update },+ });+ await expect(+ updateProjectMemory({ id: "m1", content: "hello" })+ ).rejects.toThrow(MEMORY_EDIT_UNSUPPORTED);+ });++ it("rethrows a generic adapter error unchanged", async () => {+ const update = jest.fn().mockRejectedValue(new Error("upstream down"));+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: { capabilities: () => capabilities, update },+ });+ await expect(+ updateProjectMemory({ id: "m1", content: "hello" })+ ).rejects.toThrow("upstream down");+ });});describe("deleteProjectMemory", () => {@@ -163,10 +294,114 @@ describe("deleteProjectMemory", () => {MEMORY_DELETE_UNSUPPORTED);});++ it("rejects a blank id", async () => {+ await expect(deleteProjectMemory({ id: " " })).rejects.toThrow(+ MEMORY_DETAIL_NOT_FOUND+ );+ expect(mockGetMemoryRuntime).not.toHaveBeenCalled();+ });++ it("classifies an unsupported-capability error from the adapter as delete-unsupported", async () => {+ const remove = jest+ .fn()+ .mockRejectedValue(+ new UnsupportedMemoryCapabilityError("zep", "delete")+ );+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: { capabilities: () => capabilities, delete: remove },+ });+ await expect(deleteProjectMemory({ id: "m1" })).rejects.toThrow(+ MEMORY_DELETE_UNSUPPORTED+ );+ });++ it("rethrows a generic adapter error unchanged", async () => {+ const remove = jest.fn().mockRejectedValue(new Error("upstream down"));+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: { capabilities: () => capabilities, delete: remove },+ });+ await expect(deleteProjectMemory({ id: "m1" })).rejects.toThrow(+ "upstream down"+ );+ });});describe("parseMemoryMetadata", () => {it("rejects arrays", () => {expect(() => parseMemoryMetadata([])).toThrow(MEMORY_INVALID_METADATA);});++ it("returns undefined for nullish input", () => {+ expect(parseMemoryMetadata(undefined)).toBeUndefined();+ expect(parseMemoryMetadata(null)).toBeUndefined();+ });++ it("returns the object when it is within the size limit", () => {+ const metadata = { source: "otter", confidence: 0.9 };+ expect(parseMemoryMetadata(metadata)).toEqual(metadata);+ });++ it("rejects metadata whose JSON encoding exceeds the max size", () => {+ expect(() =>+ parseMemoryMetadata({ blob: "x".repeat(4_001) })+ ).toThrow(MEMORY_INVALID_METADATA);+ });+});++describe("parseMemoryMessages", () => {+ it("returns undefined for nullish input", () => {+ expect(parseMemoryMessages(undefined)).toBeUndefined();+ expect(parseMemoryMessages(null)).toBeUndefined();+ });++ it("rejects non-array input", () => {+ expect(() => parseMemoryMessages("not-an-array")).toThrow(+ MEMORY_CONNECTOR_CONTENT_REQUIRED+ );+ });++ it("rejects items that are not plain objects", () => {+ expect(() => parseMemoryMessages([null])).toThrow(+ MEMORY_CONNECTOR_CONTENT_REQUIRED+ );+ expect(() => parseMemoryMessages([["role", "content"]])).toThrow(+ MEMORY_CONNECTOR_CONTENT_REQUIRED+ );+ });++ it("skips entries with neither role nor content", () => {+ expect(+ parseMemoryMessages([+ { role: "", content: "" },+ { role: "user", content: "hi" },+ ])+ ).toEqual([{ role: "user", content: "hi" }]);+ });++ it("rejects entries missing only role or only content", () => {+ expect(() => parseMemoryMessages([{ role: "user", content: "" }])).toThrow(+ MEMORY_CONNECTOR_CONTENT_REQUIRED+ );+ expect(() => parseMemoryMessages([{ role: "", content: "hi" }])).toThrow(+ MEMORY_CONNECTOR_CONTENT_REQUIRED+ );+ });++ it("rejects a role or content that is too long", () => {+ expect(() =>+ parseMemoryMessages([{ role: "x".repeat(65), content: "hi" }])+ ).toThrow(MEMORY_CONTENT_TOO_LONG);+ expect(() =>+ parseMemoryMessages([{ role: "user", content: "x".repeat(20_001) }])+ ).toThrow(MEMORY_CONTENT_TOO_LONG);+ });++ it("returns undefined when every entry is skipped", () => {+ expect(parseMemoryMessages([{ role: "", content: "" }])).toBeUndefined();+ });});diff --git a/src/client/src/__tests__/lib/platform/connectors/visible-types.test.ts b/src/client/src/__tests__/lib/platform/connectors/visible-types.test.tsnew file mode 100644index 00000000..607e6bab--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/visible-types.test.ts@@ -0,0 +1,21 @@+import {+ isVisibleConnectorType,+ VISIBLE_CONNECTOR_TYPES,+} from "@/lib/platform/connectors/visible-types";++describe("isVisibleConnectorType", () => {+ it.each(VISIBLE_CONNECTOR_TYPES)("returns true for %s", (type) => {+ expect(isVisibleConnectorType(type)).toBe(true);+ });++ it("returns false for an unlisted string", () => {+ expect(isVisibleConnectorType("datadog")).toBe(false);+ });++ it("returns false for non-string input via String() coercion", () => {+ expect(isVisibleConnectorType(undefined)).toBe(false);+ expect(isVisibleConnectorType(null)).toBe(false);+ expect(isVisibleConnectorType(42)).toBe(false);+ expect(isVisibleConnectorType({})).toBe(false);+ });+});diff --git a/src/client/src/__tests__/lib/platform/context/context.test.ts b/src/client/src/__tests__/lib/platform/context/context.test.tsindex 9c6da826..eb300275 100644--- a/src/client/src/__tests__/lib/platform/context/context.test.ts+++ b/src/client/src/__tests__/lib/platform/context/context.test.ts@@ -114,6 +114,15 @@ describe('createContext', () => {const [{ table }] = (dataCollector as jest.Mock).mock.calls[0];expect(table).toBe('openlit_contexts');});++ it('defaults status to ACTIVE and falls back to the generated id in the alert message when name is omitted', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null, data: {} });+ const result = await createContext({ content: 'body' });+ const [{ values }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(values[0].status).toBe('ACTIVE');+ expect(values[0].description).toBe('');+ expect(result.id).toBeTruthy();+ });});describe('updateContext', () => {@@ -144,6 +153,29 @@ describe('updateContext', () => {const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];expect(query).toContain('ctx-abc');});++ it('includes description, tags, meta_properties, and status set-clauses when provided', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null, data: { query_id: 'q1' } });+ await updateContext('c1', {+ name: 'x',+ content: 'y',+ description: 'a new description',+ tags: '["a"]',+ meta_properties: '{"k":"v"}',+ status: 'INACTIVE',+ });+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).toContain("description = 'a new description'");+ expect(query).toContain('tags = \'["a"]\'');+ expect(query).toContain('meta_properties = \'{"k":"v"}\'');+ expect(query).toContain("status = 'INACTIVE'");+ });++ it('falls back to the id in the alert message and empty name field when name is omitted', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null, data: { query_id: 'q1' } });+ const result = await updateContext('ctx-no-name', { content: 'y' });+ expect(result).toEqual({ message: 'Context updated!' });+ });});describe('deleteContext', () => {diff --git a/src/client/src/__tests__/lib/platform/controller/controller.test.ts b/src/client/src/__tests__/lib/platform/controller/controller.test.tsindex 99312e47..43463948 100644--- a/src/client/src/__tests__/lib/platform/controller/controller.test.ts+++ b/src/client/src/__tests__/lib/platform/controller/controller.test.ts@@ -15,10 +15,14 @@ import {getControllerIdsForWorkload,getControllerConfig,saveControllerConfig,+ getFeatureDesiredStates,updateDesiredStatus,+ getEnvironmentFeatureConfigs,+ saveEnvironmentFeatureConfig,queueAction,getPendingActions,markActionsAcknowledged,+ getActionsByIds,completeAction,} from "@/lib/platform/controller";@@ -88,6 +92,71 @@ describe("getDesiredStatesForWorkloads", () => {expect((call[0] as any).query).toContain("wk-1");expect((call[0] as any).query).toContain("wk-2");});++ it("propagates an error from the underlying query", async () => {+ mockedDataCollector.mockResolvedValue({ err: "boom" } as any);+ const result = await getDesiredStatesForWorkloads(["wk-1"], "default", "db-1");+ expect(result).toEqual({ err: "boom" });+ });++ it("pivots feature rows into instrumentation/agent columns per workload", async () => {+ mockedDataCollector.mockResolvedValue({+ data: [+ { workload_key: "wk-1", feature: "instrumentation", desired_status: "instrumented" },+ { workload_key: "wk-1", feature: "agent", desired_status: "enabled" },+ { workload_key: "wk-2", feature: "unrelated-feature", desired_status: "x" },+ ],+ } as any);++ const result = await getDesiredStatesForWorkloads(["wk-1", "wk-2"], "default", "db-1");+ expect(result.data).toEqual(+ expect.arrayContaining([+ {+ workload_key: "wk-1",+ desired_instrumentation_status: "instrumented",+ desired_agent_status: "enabled",+ },+ {+ workload_key: "wk-2",+ desired_instrumentation_status: "none",+ desired_agent_status: "none",+ },+ ])+ );+ });++ it("defaults to an empty result set when no data rows are returned", async () => {+ mockedDataCollector.mockResolvedValue({} as any);+ const result = await getDesiredStatesForWorkloads(["wk-1"], "default", "db-1");+ expect(result).toEqual({ data: [] });+ });+});++describe("getFeatureDesiredStates", () => {+ it("returns empty array for empty workload keys", async () => {+ const result = await getFeatureDesiredStates([], "default", undefined, "db-1");+ expect(result).toEqual({ data: [] });+ expect(mockedDataCollector).not.toHaveBeenCalled();+ });++ it("omits the feature filter when no features are provided", async () => {+ mockedDataCollector.mockResolvedValue({ data: [] } as any);+ await getFeatureDesiredStates(["wk-1"], "default", undefined, "db-1");+ const q = (mockedDataCollector.mock.calls[0][0] as any).query;+ expect(q).not.toContain("AND feature IN");+ });++ it("adds a feature filter when features are provided", async () => {+ mockedDataCollector.mockResolvedValue({ data: [] } as any);+ await getFeatureDesiredStates(+ ["wk-1"],+ "default",+ ["instrumentation", "agent"],+ "db-1"+ );+ const q = (mockedDataCollector.mock.calls[0][0] as any).query;+ expect(q).toContain("AND feature IN ('instrumentation','agent')");+ });});describe("getControllerInstances", () => {@@ -243,6 +312,59 @@ describe("updateDesiredStatus", () => {});});+describe("getEnvironmentFeatureConfigs", () => {+ it("omits the feature filter when no features are provided", async () => {+ mockedDataCollector.mockResolvedValue({ data: [] } as any);+ await getEnvironmentFeatureConfigs("prod", "cluster-1", undefined, "db-1");+ const q = (mockedDataCollector.mock.calls[0][0] as any).query;+ expect(q).not.toContain("AND feature IN");+ });++ it("adds a feature filter when features are provided", async () => {+ mockedDataCollector.mockResolvedValue({ data: [] } as any);+ await getEnvironmentFeatureConfigs("prod", "cluster-1", ["agent"], "db-1");+ const q = (mockedDataCollector.mock.calls[0][0] as any).query;+ expect(q).toContain("AND feature IN ('agent')");+ expect(q).toContain("prod");+ expect(q).toContain("cluster-1");+ });+});++describe("saveEnvironmentFeatureConfig", () => {+ it("inserts an environment feature config row", async () => {+ mockedDataCollector.mockResolvedValue({ data: "ok" } as any);+ await saveEnvironmentFeatureConfig("prod", "cluster-1", "agent", "{}", "db-1");+ const [args, action, dbId] = mockedDataCollector.mock.calls[0];+ expect((args as any).values[0]).toEqual(+ expect.objectContaining({+ environment: "prod",+ cluster_id: "cluster-1",+ feature: "agent",+ config: "{}",+ })+ );+ expect(action).toBe("insert");+ expect(dbId).toBe("db-1");+ });+});++describe("getActionsByIds", () => {+ it("returns an empty array for an empty id list", async () => {+ const result = await getActionsByIds([], "ctrl-1", "db-1");+ expect(result).toEqual({ data: [] });+ expect(mockedDataCollector).not.toHaveBeenCalled();+ });++ it("queries actions filtered by ids and instance id", async () => {+ mockedDataCollector.mockResolvedValue({ data: [] } as any);+ await getActionsByIds(["act-1", "act-2"], "ctrl-1", "db-1");+ const q = (mockedDataCollector.mock.calls[0][0] as any).query;+ expect(q).toContain("act-1");+ expect(q).toContain("act-2");+ expect(q).toContain("ctrl-1");+ });+});+describe("queueAction", () => {it("inserts a pending action with a deterministic id", async () => {mockedDataCollector.mockResolvedValue({ data: "ok" } as any);diff --git a/src/client/src/__tests__/lib/platform/datasource/ai-selector.test.ts b/src/client/src/__tests__/lib/platform/datasource/ai-selector.test.tsindex a85c127f..aeb58019 100644--- a/src/client/src/__tests__/lib/platform/datasource/ai-selector.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/ai-selector.test.ts@@ -4,6 +4,7 @@ import {buildAITelemetrySelector,evalOperationClauseToClickHouse,operationTypeClauseToClickHouse,+ type AITelemetrySelector,} from "@/lib/platform/connectors/datasource/ai-selector";import { CODING_AGENT_SPAN_NAMES } from "@/lib/platform/coding-agents/table-details";import { SUPPORTED_EVALUATION_OPERATIONS } from "@/constants/traces";@@ -146,4 +147,157 @@ describe("AI telemetry selector", () => {});});});++ describe("conditionToClickHouse via custom selectors (session-2 branch coverage)", () => {+ it("maps the log and metric attribute scopes to their ClickHouse columns", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ { allOf: [{ target: "attribute", scope: "log", key: "k1", op: "exists" }] },+ {+ allOf: [+ { target: "attribute", scope: "metric", key: "k2", op: "exists" },+ ],+ },+ ],+ };+ const sql = aiSelectorToClickHouse(selector);+ expect(sql).toContain("notEmpty(LogAttributes['k1'])");+ expect(sql).toContain("notEmpty(Attributes['k2'])");+ });++ it("translates a spanName 'eq' condition with a string value", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ { allOf: [{ target: "spanName", op: "eq", value: "chat completion" }] },+ ],+ };+ const sql = aiSelectorToClickHouse(selector);+ expect(sql).toBe("(SpanName = 'chat completion')");+ });++ it("throws for a spanName condition with an unsupported op", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ {+ allOf: [+ { target: "spanName", op: "exists" as unknown as "eq" },+ ],+ },+ ],+ };+ expect(() => aiSelectorToClickHouse(selector)).toThrow(+ "Unsupported spanName op: exists"+ );+ });++ it("throws for a spanName 'eq' condition whose value isn't a string", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ { allOf: [{ target: "spanName", op: "eq", value: ["a", "b"] }] },+ ],+ };+ expect(() => aiSelectorToClickHouse(selector)).toThrow(+ "Unsupported spanName op: eq"+ );+ });++ it("throws for a spanName 'in' condition whose value isn't an array", () => {+ const selector: AITelemetrySelector = {+ anyOf: [{ allOf: [{ target: "spanName", op: "in", value: "solo" }] }],+ };+ expect(() => aiSelectorToClickHouse(selector)).toThrow(+ "Unsupported spanName op: in"+ );+ });++ it("translates an attribute 'in' condition with an array value to an IN clause", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ {+ allOf: [+ {+ target: "attribute",+ scope: "span",+ key: "gen_ai.system",+ op: "in",+ value: ["openai", "anthropic"],+ },+ ],+ },+ ],+ };+ const sql = aiSelectorToClickHouse(selector);+ expect(sql).toContain(+ "SpanAttributes['gen_ai.system'] IN ('openai', 'anthropic')"+ );+ });++ it("translates an attribute 'in' condition with a scalar (non-array) value", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ {+ allOf: [+ {+ target: "attribute",+ scope: "span",+ key: "gen_ai.system",+ op: "in",+ value: "openai",+ },+ ],+ },+ ],+ };+ const sql = aiSelectorToClickHouse(selector);+ expect(sql).toContain("SpanAttributes['gen_ai.system'] IN ('openai')");+ });++ it("defaults the attribute key to an empty string when none is provided", () => {+ const selector: AITelemetrySelector = {+ anyOf: [{ allOf: [{ target: "attribute", scope: "span", op: "exists" }] }],+ };+ const sql = aiSelectorToClickHouse(selector);+ expect(sql).toContain("notEmpty(SpanAttributes[''])");+ });++ it("defaults an attribute 'eq' condition's value to an empty string when none is provided", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ { allOf: [{ target: "attribute", scope: "span", key: "k", op: "eq" }] },+ ],+ };+ const sql = aiSelectorToClickHouse(selector);+ expect(sql).toContain("SpanAttributes['k'] = ''");+ });++ it("defaults an attribute 'in' condition's scalar value to an empty string when none is provided", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ { allOf: [{ target: "attribute", scope: "span", key: "k", op: "in" }] },+ ],+ };+ const sql = aiSelectorToClickHouse(selector);+ expect(sql).toContain("SpanAttributes['k'] IN ('')");+ });++ it("throws for an attribute condition with an unsupported op", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ {+ allOf: [+ {+ target: "attribute",+ scope: "span",+ key: "k",+ op: "unsupported" as unknown as "exists",+ },+ ],+ },+ ],+ };+ expect(() => aiSelectorToClickHouse(selector)).toThrow(+ "Unsupported attribute op: unsupported"+ );+ });+ });});diff --git a/src/client/src/__tests__/lib/platform/datasource/base-adapter.test.ts b/src/client/src/__tests__/lib/platform/datasource/base-adapter.test.tsnew file mode 100644index 00000000..193e9229--- /dev/null+++ b/src/client/src/__tests__/lib/platform/datasource/base-adapter.test.ts@@ -0,0 +1,144 @@+import { BaseExternalAdapter } from "@/lib/platform/connectors/datasource/base-adapter";+import {+ UnsupportedCapabilityError,+ type HealthCheckResult,+ type SourceCapabilities,+ type TelemetrySourceDescriptor,+} from "@/lib/platform/connectors/datasource/types";++class TestAdapter extends BaseExternalAdapter {+ readonly type = "test-vendor";++ capabilities(): SourceCapabilities {+ return {+ signals: ["traces"],+ traceTree: false,+ spanEvents: false,+ serverAggregation: false,+ spanMutation: false,+ distinctValues: false,+ crossTraceSession: false,+ rawQuery: false,+ };+ }++ async healthCheck(): Promise<HealthCheckResult> {+ return { ok: true };+ }+}++const descriptor: TelemetrySourceDescriptor = {+ type: "test-vendor",+ id: "conn-1",+ isBuiltIn: false,+ settings: {},+ signals: ["traces"],+ name: "Test Vendor",+};++const window = {+ start: new Date("2026-07-01T00:00:00.000Z"),+ end: new Date("2026-07-02T00:00:00.000Z"),+};++const baseQuery = {+ signal: "traces" as const,+ timeRange: window,+};++describe("BaseExternalAdapter", () => {+ let adapter: TestAdapter;++ beforeEach(() => {+ adapter = new TestAdapter(descriptor);+ });++ it("exposes the descriptor id as the sample cache key", () => {+ expect(adapter.sampleCacheKey).toBe("conn-1");+ });++ it("implements capabilities() and healthCheck() per subclass", async () => {+ expect(adapter.capabilities().signals).toEqual(["traces"]);+ expect(await adapter.healthCheck()).toEqual({ ok: true });+ });++ const unsupportedCases: Array<{+ name: string;+ invoke: () => Promise<unknown>;+ }> = [+ {+ name: "validateAISignal",+ invoke: () => adapter.validateAISignal(window),+ },+ { name: "listSpans", invoke: () => adapter.listSpans(baseQuery) },+ { name: "getSpan", invoke: () => adapter.getSpan("span-1") },+ { name: "getTraceSpans", invoke: () => adapter.getTraceSpans("trace-1") },+ {+ name: "getSpansBySession",+ invoke: () => adapter.getSpansBySession("session-1"),+ },+ { name: "aggregateSpans", invoke: () => adapter.aggregateSpans(baseQuery) },+ { name: "spanTimeSeries", invoke: () => adapter.spanTimeSeries(baseQuery) },+ {+ name: "distinctValues",+ invoke: () => adapter.distinctValues("service.name", baseQuery),+ },+ {+ name: "attributeKeys",+ invoke: () => adapter.attributeKeys("traces", window),+ },+ { name: "listLogs", invoke: () => adapter.listLogs(baseQuery) },+ { name: "getLog", invoke: () => adapter.getLog("log-1") },+ { name: "logTimeSeries", invoke: () => adapter.logTimeSeries(baseQuery) },+ {+ name: "listMetricSeries",+ invoke: () => adapter.listMetricSeries(baseQuery),+ },+ {+ name: "metricTimeSeries",+ invoke: () => adapter.metricTimeSeries(baseQuery),+ },+ { name: "metricNames", invoke: () => adapter.metricNames(window) },+ {+ name: "discoverServices",+ invoke: () => adapter.discoverServices(window),+ },+ {+ name: "aggregateByService",+ invoke: () => adapter.aggregateByService(window),+ },+ {+ name: "sampleTracesForGraph",+ invoke: () => adapter.sampleTracesForGraph(baseQuery, 10),+ },+ ];++ it.each(unsupportedCases)(+ "$name throws UnsupportedCapabilityError naming the capability and source type",+ async ({ name, invoke }) => {+ await expect(invoke()).rejects.toThrow(UnsupportedCapabilityError);+ await expect(invoke()).rejects.toMatchObject({+ capability: name,+ sourceType: "test-vendor",+ message: `Capability "${name}" is not supported by data source "test-vendor".`,+ });+ }+ );++ it("getLog accepts optional lookup options without changing default behavior", async () => {+ await expect(+ adapter.getLog("log-1", {+ aroundTimestamp: "2026-07-01T00:00:00.000Z",+ timeRange: window,+ })+ ).rejects.toThrow(UnsupportedCapabilityError);+ });++ it("UnsupportedCapabilityError supports a custom message override", () => {+ const err = new UnsupportedCapabilityError("vendor-x", "rawQuery", "nope");+ expect(err.message).toBe("nope");+ expect(err.name).toBe("UnsupportedCapabilityError");+ expect(err.capability).toBe("rawQuery");+ expect(err.sourceType).toBe("vendor-x");+ });+});diff --git a/src/client/src/__tests__/lib/platform/datasource/cache.test.ts b/src/client/src/__tests__/lib/platform/datasource/cache.test.tsindex 52daba79..342b5037 100644--- a/src/client/src/__tests__/lib/platform/datasource/cache.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/cache.test.ts@@ -2,6 +2,7 @@ import {__clearCache,cachedQuery,cacheKey,+ estimateCacheBytes,} from "@/lib/platform/connectors/datasource/http/cache";beforeEach(() => __clearCache());@@ -13,6 +14,12 @@ describe("cacheKey", () => {it("differs by source id", () => {expect(cacheKey("s1", { a: 1 })).not.toBe(cacheKey("s2", { a: 1 }));});+ it("stringifies array-valued parts element-by-element", () => {+ expect(cacheKey("s1", { filters: [1, "a", { b: 2 }] })).toBe(+ cacheKey("s1", { filters: [1, "a", { b: 2 }] })+ );+ expect(cacheKey("s1", [1, 2])).not.toBe(cacheKey("s1", [2, 1]));+ });});describe("cachedQuery", () => {@@ -65,3 +72,38 @@ describe("cachedQuery", () => {expect(stats.bytes).toBeLessThanOrEqual(MAX_CACHE_BYTES);});});++describe("estimateCacheBytes", () => {+ it("charges a fixed cost for values JSON.stringify cannot serialize", () => {+ const circular: Record<string, unknown> = {};+ circular.self = circular;+ expect(estimateCacheBytes(circular)).toBe(4 * 1024);+ });++ it("charges a fixed cost for BigInt values", () => {+ expect(estimateCacheBytes(BigInt(10))).toBe(4 * 1024);+ });++ it("estimates the UTF-8 byte length for serializable values", () => {+ expect(estimateCacheBytes({ a: 1 })).toBe(+ Buffer.byteLength(JSON.stringify({ a: 1 }), "utf8")+ );+ });++ it("treats a top-level undefined value as the literal string 'null'", () => {+ // JSON.stringify(undefined) returns undefined, exercising the `?? "null"` fallback.+ expect(estimateCacheBytes(undefined)).toBe(Buffer.byteLength("null", "utf8"));+ });++ it("falls back to string length when Buffer is unavailable", () => {+ const originalBuffer = globalThis.Buffer;+ // @ts-expect-error -- simulate a runtime without the Node Buffer global.+ delete globalThis.Buffer;+ try {+ const value = { a: 1 };+ expect(estimateCacheBytes(value)).toBe(JSON.stringify(value).length);+ } finally {+ globalThis.Buffer = originalBuffer;+ }+ });+});diff --git a/src/client/src/__tests__/lib/platform/datasource/clickhouse-adapter.test.ts b/src/client/src/__tests__/lib/platform/datasource/clickhouse-adapter.test.tsindex 013723f0..ea9db7e5 100644--- a/src/client/src/__tests__/lib/platform/datasource/clickhouse-adapter.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/clickhouse-adapter.test.ts@@ -5,6 +5,8 @@ const mockGetLogs = jest.fn();const mockGetLogByRowId = jest.fn();const mockGetMetrics = jest.fn();const mockGetMetricsConfig = jest.fn();+const mockGetMetricDetail = jest.fn();+const mockGetLogsConfig = jest.fn();const mockGetLogAttributeKeys = jest.fn();const mockGetMetricAttributeKeys = jest.fn();const mockGetSignalSummary = jest.fn();@@ -30,13 +32,18 @@ jest.mock("@/lib/platform/observability", () => ({getLogByRowId: (...args: unknown[]) => mockGetLogByRowId(...args),getMetrics: (...args: unknown[]) => mockGetMetrics(...args),getMetricsConfig: (...args: unknown[]) => mockGetMetricsConfig(...args),+ getMetricDetail: (...args: unknown[]) => mockGetMetricDetail(...args),+ getLogsConfig: (...args: unknown[]) => mockGetLogsConfig(...args),getLogAttributeKeys: (...args: unknown[]) => mockGetLogAttributeKeys(...args),getMetricAttributeKeys: (...args: unknown[]) =>mockGetMetricAttributeKeys(...args),getSignalSummary: (...args: unknown[]) => mockGetSignalSummary(...args),}));-import { ClickHouseAdapter } from "@/lib/platform/connectors/datasource/clickhouse/adapter";+import {+ ClickHouseAdapter,+ clickHouseAdapterFactory,+} from "@/lib/platform/connectors/datasource/clickhouse/adapter";import type {OpenLITQuery,TelemetrySourceDescriptor,@@ -133,6 +140,11 @@ describe("ClickHouseAdapter", () => {]);});+ it("getTraceSpans defaults to [] when the query returns no data field", async () => {+ mockDataCollector.mockResolvedValue({});+ expect(await adapter.getTraceSpans("t1")).toEqual([]);+ });+it("getTraceSpans queries by TraceId and targets the db config", async () => {mockDataCollector.mockResolvedValue({ data: [rawSpan] });const spans = await adapter.getTraceSpans("t1");@@ -144,6 +156,11 @@ describe("ClickHouseAdapter", () => {expect(dbId).toBe("db-1");});+ it("getSpansBySession defaults to [] when the query returns no data field", async () => {+ mockDataCollector.mockResolvedValue({});+ expect(await adapter.getSpansBySession("sess-1")).toEqual([]);+ });+it("getSpansBySession unions coding-agent session + parent ids", async () => {mockDataCollector.mockResolvedValue({ data: [] });await adapter.getSpansBySession("sess-1");@@ -163,6 +180,12 @@ describe("ClickHouseAdapter", () => {expect(sql).toContain("ResourceAttributes['telemetry.sdk.name'] = 'openlit'");});+ it("aggregateSpans defaults rows to [] when the query returns no data field", async () => {+ mockDataCollector.mockResolvedValue({});+ const frame = await adapter.aggregateSpans(baseQuery);+ expect(frame.rows).toEqual([]);+ });+it("aggregateSpans builds group-by + aggregation SQL", async () => {mockDataCollector.mockResolvedValue({ data: [{ g0: "gpt-4", total: 5 }] });await adapter.aggregateSpans({@@ -188,6 +211,12 @@ describe("ClickHouseAdapter", () => {expect(mockDataCollector).not.toHaveBeenCalled();});+ it("spanTimeSeries defaults rows to [] when getSignalSummary returns no buckets", async () => {+ mockGetSignalSummary.mockResolvedValue({});+ const frame = await adapter.spanTimeSeries(baseQuery);+ expect(frame.rows).toEqual([]);+ });+it("spanTimeSeries buckets by interval", async () => {mockGetSignalSummary.mockResolvedValue({ buckets: [{ label: "10:00", count: 2 }] });const frame = await adapter.spanTimeSeries({ ...baseQuery, interval: "1h" });@@ -198,6 +227,11 @@ describe("ClickHouseAdapter", () => {expect(frame.rows).toEqual([{ label: "10:00", count: 2 }]);});+ it("distinctValues defaults to [] when the traces query returns no data field", async () => {+ mockDataCollector.mockResolvedValue({});+ expect(await adapter.distinctValues("service.name", baseQuery)).toEqual([]);+ });+it("distinctValues returns non-empty string values", async () => {mockDataCollector.mockResolvedValue({data: [{ v: "gpt-4" }, { v: "" }, { v: "claude" }],@@ -213,6 +247,19 @@ describe("ClickHouseAdapter", () => {expect(sql).toContain("ResourceAttributes['deployment.environment'] AS v");});+ it("distinctValues respects span-scoped attribute fields (span: prefix)", async () => {+ mockDataCollector.mockResolvedValue({ data: [{ v: "gpt-4o" }] });+ await adapter.distinctValues("span:gen_ai.request.model", baseQuery);+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).toContain("SpanAttributes['gen_ai.request.model'] AS v");+ });++ it("distinctValues coalesces a nullish v column to '' before filtering", async () => {+ mockDataCollector.mockResolvedValue({ data: [{ v: null }, { v: undefined }, { v: "ok" }] });+ const values = await adapter.distinctValues("service.name", baseQuery);+ expect(values).toEqual(["ok"]);+ });+it("attributeKeys(traces) merges span + resource keys", async () => {mockGetAttributeKeys.mockResolvedValue({spanAttributeKeys: ["a"],@@ -221,6 +268,11 @@ describe("ClickHouseAdapter", () => {expect(await adapter.attributeKeys("traces", window)).toEqual(["a", "b"]);});+ it("attributeKeys(traces) defaults to [] when getAttributeKeys returns neither key list", async () => {+ mockGetAttributeKeys.mockResolvedValue({});+ expect(await adapter.attributeKeys("traces", window)).toEqual([]);+ });+it("discoverServices maps rollup rows", async () => {mockDataCollector.mockResolvedValue({data: [@@ -258,4 +310,728 @@ describe("ClickHouseAdapter", () => {mockDataCollector.mockResolvedValueOnce({ data: [] });expect(await adapter.sampleTracesForGraph(baseQuery, 50)).toEqual([]);});++ it("listSpans throws the legacy error when getRequests fails", async () => {+ const boom = new Error("boom");+ mockGetRequests.mockResolvedValue({ err: boom });+ await expect(adapter.listSpans(baseQuery)).rejects.toThrow("boom");+ });++ it("listSpans wraps a non-Error err value", async () => {+ mockGetRequests.mockResolvedValue({ err: "string-error" });+ await expect(adapter.listSpans(baseQuery)).rejects.toThrow("string-error");+ });++ it("listSpans defaults rowsScanned to rows.length when total is not a number", async () => {+ mockGetRequests.mockResolvedValue({ records: [rawSpan], total: undefined });+ const frame = await adapter.listSpans(baseQuery);+ expect(frame.meta?.rowsScanned).toBe(1);+ });++ it("listSpans defaults rows to [] when getRequests returns no records field", async () => {+ mockGetRequests.mockResolvedValue({});+ const frame = await adapter.listSpans(baseQuery);+ expect(frame.rows).toEqual([]);+ });++ // ---- fieldToExpr (via aggregateSpans/distinctValues groupBy & field) --++ it("aggregateSpans resolves a resource-scoped groupBy field", async () => {+ mockDataCollector.mockResolvedValue({ data: [] });+ await adapter.aggregateSpans({+ ...baseQuery,+ groupBy: ["resource:deployment.environment"],+ });+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).toContain("ResourceAttributes['deployment.environment'] AS g0");+ });++ it("aggregateSpans resolves the duration field to seconds", async () => {+ mockDataCollector.mockResolvedValue({ data: [] });+ await adapter.aggregateSpans({+ ...baseQuery,+ groupBy: ["duration"],+ aggregations: [{ fn: "avg", field: "duration", as: "avgDur" }],+ });+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).toContain("Duration / 1000000000 AS g0");+ expect(sql).toContain("avg(toFloat64OrZero(Duration / 1000000000)) AS avgDur");+ });++ it("aggregateSpans resolves plain allowed field names (SpanName/ServiceName/Duration)", async () => {+ mockDataCollector.mockResolvedValue({ data: [] });+ await adapter.aggregateSpans({+ ...baseQuery,+ groupBy: ["SpanName", "ServiceName", "Duration"],+ });+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).toContain("SpanName AS g0");+ expect(sql).toContain("ServiceName AS g1");+ expect(sql).toContain("Duration AS g2");+ });++ it("aggregateSpans resolves an un-scoped deployment.environment field", async () => {+ mockDataCollector.mockResolvedValue({ data: [] });+ await adapter.aggregateSpans({+ ...baseQuery,+ groupBy: ["deployment.environment"],+ });+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).toContain("ResourceAttributes['deployment.environment'] AS g0");+ });++ it("aggregateSpans passes through any other allow-listed field verbatim (e.g. StatusCode)", async () => {+ mockDataCollector.mockResolvedValue({ data: [] });+ await adapter.aggregateSpans({ ...baseQuery, groupBy: ["StatusCode"] });+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).toContain("StatusCode AS g0");+ });++ it("aggregateSpans throws for an unsupported field", async () => {+ await expect(+ adapter.aggregateSpans({ ...baseQuery, groupBy: ["NotAllowedField"] })+ ).rejects.toThrow("Unsupported ClickHouse field: NotAllowedField");+ });++ it("aggregateSpans defaults to a count() aggregation when none is given", async () => {+ mockDataCollector.mockResolvedValue({ data: [] });+ await adapter.aggregateSpans(baseQuery);+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).toContain("count() AS agg0");+ });++ it.each([+ ["avg", "avg(toFloat64OrZero("],+ ["min", "min(toFloat64OrZero("],+ ["max", "max(toFloat64OrZero("],+ ["p50", "quantile(0.5)(toFloat64OrZero("],+ ["p90", "quantile(0.9)(toFloat64OrZero("],+ ["p95", "quantile(0.95)(toFloat64OrZero("],+ ["p99", "quantile(0.99)(toFloat64OrZero("],+ ["cardinality", "uniqExact("],+ ])("aggregateSpans maps the %s aggregation function", async (fn, expected) => {+ mockDataCollector.mockResolvedValue({ data: [] });+ await adapter.aggregateSpans({+ ...baseQuery,+ aggregations: [{ fn: fn as any, field: "gen_ai.usage.cost", as: "x" }],+ });+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).toContain(expected);+ });++ it("aggregateSpans falls back to count() for an unknown aggregation fn", async () => {+ mockDataCollector.mockResolvedValue({ data: [] });+ await adapter.aggregateSpans({+ ...baseQuery,+ aggregations: [{ fn: "totally-unknown" as any, as: "x" }],+ });+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).toContain("count() AS x");+ });++ it("aggregateSpans omits GROUP BY and LIMIT when neither is set", async () => {+ mockDataCollector.mockResolvedValue({ data: [] });+ await adapter.aggregateSpans(baseQuery);+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).not.toContain("GROUP BY");+ expect(sql).not.toContain("LIMIT");+ });++ it("aggregateSpans applies LIMIT when set and omits the aiSelector when aiSelector is false", async () => {+ mockDataCollector.mockResolvedValue({ data: [] });+ await adapter.aggregateSpans({ ...baseQuery, limit: 25, aiSelector: false });+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).toContain("LIMIT 25");+ expect(sql).not.toContain("telemetry.sdk.name");+ });++ it("aggregateSpans throws the legacy error when the query fails", async () => {+ mockDataCollector.mockResolvedValue({ err: new Error("query failed") });+ await expect(adapter.aggregateSpans(baseQuery)).rejects.toThrow("query failed");+ });++ // ---- distinctValues (logs / metrics / unsupported field) --------------++ it("distinctValues(logs) returns services/severities from getLogsConfig and [] for unknown keys", async () => {+ mockGetLogsConfig.mockResolvedValue({+ data: [{ services: ["api"], severities: ["ERROR"] }],+ });+ const logQuery = { ...baseQuery, signal: "logs" as const };+ expect(await adapter.distinctValues("service.name", logQuery)).toEqual(["api"]);+ expect(await adapter.distinctValues("severity", logQuery)).toEqual(["ERROR"]);+ expect(await adapter.distinctValues("other", logQuery)).toEqual([]);+ });++ it("distinctValues(logs) defaults to [] when the config row is empty and throws on legacy error", async () => {+ mockGetLogsConfig.mockResolvedValue({ data: [] });+ const logQuery = { ...baseQuery, signal: "logs" as const };+ expect(await adapter.distinctValues("service.name", logQuery)).toEqual([]);+ expect(await adapter.distinctValues("severity", logQuery)).toEqual([]);++ mockGetLogsConfig.mockResolvedValue({ err: new Error("logs config failed") });+ await expect(+ adapter.distinctValues("service.name", logQuery)+ ).rejects.toThrow("logs config failed");+ });++ it("distinctValues(metrics) returns services/metric names from getMetricsConfig for both metric-name aliases", async () => {+ mockGetMetricsConfig.mockResolvedValue({+ data: [{ services: ["api"], metricNames: ["gen_ai.client.token.usage"] }],+ });+ const metricQuery = { ...baseQuery, signal: "metrics" as const };+ expect(await adapter.distinctValues("service.name", metricQuery)).toEqual(["api"]);+ expect(await adapter.distinctValues("metric.name", metricQuery)).toEqual([+ "gen_ai.client.token.usage",+ ]);+ expect(await adapter.distinctValues("MetricName", metricQuery)).toEqual([+ "gen_ai.client.token.usage",+ ]);+ expect(await adapter.distinctValues("other", metricQuery)).toEqual([]);+ });++ it("distinctValues(metrics) defaults to [] when the config row is empty", async () => {+ mockGetMetricsConfig.mockResolvedValue({ data: [] });+ const metricQuery = { ...baseQuery, signal: "metrics" as const };+ expect(await adapter.distinctValues("service.name", metricQuery)).toEqual([]);+ expect(await adapter.distinctValues("metric.name", metricQuery)).toEqual([]);+ });++ it("distinctValues throws for an unsupported ClickHouse field on the traces path", async () => {+ await expect(+ adapter.distinctValues("NotAllowedField", baseQuery)+ ).rejects.toThrow("Unsupported ClickHouse field: NotAllowedField");+ expect(mockDataCollector).not.toHaveBeenCalled();+ });++ it("distinctValues omits the aiSelector clause when aiSelector is false", async () => {+ mockDataCollector.mockResolvedValue({ data: [] });+ await adapter.distinctValues("service.name", { ...baseQuery, aiSelector: false });+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).not.toContain("telemetry.sdk.name");+ });++ it("distinctValues throws the legacy error when the underlying query fails", async () => {+ mockDataCollector.mockResolvedValue({ err: new Error("distinct failed") });+ await expect(+ adapter.distinctValues("service.name", baseQuery)+ ).rejects.toThrow("distinct failed");+ });++ // ---- attributeKeys (logs / metrics) ------------------------------------++ it("attributeKeys(logs) dedupes keys returned by getLogAttributeKeys", async () => {+ mockGetLogAttributeKeys.mockResolvedValue({+ logAttributeKeys: ["a", "b"],+ resourceAttributeKeys: ["b", "c"],+ });+ expect(await adapter.attributeKeys("logs", window)).toEqual(["a", "b", "c"]);+ });++ it("attributeKeys(metrics) dedupes keys returned by getMetricAttributeKeys", async () => {+ mockGetMetricAttributeKeys.mockResolvedValue({+ metricAttributeKeys: ["x"],+ resourceAttributeKeys: ["x", "y"],+ });+ expect(await adapter.attributeKeys("metrics", window)).toEqual(["x", "y"]);+ });++ it("attributeKeys(logs) dedupeKeys ignores non-array values in the result object", async () => {+ mockGetLogAttributeKeys.mockResolvedValue({+ logAttributeKeys: ["a", "b"],+ resourceAttributeKeys: "not-an-array",+ someScalar: 42,+ });+ expect(await adapter.attributeKeys("logs", window)).toEqual(["a", "b"]);+ });++ // ---- Logs ---------------------------------------------------------------++ it("listLogs normalizes getLogs records into NormalizedLog", async () => {+ mockGetLogs.mockResolvedValue({+ records: [+ {+ Timestamp: "2026-07-01T00:00:00Z",+ Body: "boom",+ SeverityText: "ERROR",+ ServiceName: "svc",+ },+ ],+ total: 1,+ });+ const frame = await adapter.listLogs({ ...baseQuery, signal: "logs" });+ expect(frame.rows).toHaveLength(1);+ expect(frame.rows[0]).toMatchObject({ body: "boom", severityText: "ERROR" });+ expect(frame.meta?.rowsScanned).toBe(1);+ });++ it("listLogs defaults rowsScanned to rows.length and throws on legacy error", async () => {+ mockGetLogs.mockResolvedValue({ records: [], total: undefined });+ const frame = await adapter.listLogs({ ...baseQuery, signal: "logs" });+ expect(frame.meta?.rowsScanned).toBe(0);++ mockGetLogs.mockResolvedValue({ err: new Error("logs failed") });+ await expect(adapter.listLogs({ ...baseQuery, signal: "logs" })).rejects.toThrow(+ "logs failed"+ );+ });++ it("listLogs defaults rows to [] when getLogs returns no records field", async () => {+ mockGetLogs.mockResolvedValue({});+ const frame = await adapter.listLogs({ ...baseQuery, signal: "logs" });+ expect(frame.rows).toEqual([]);+ });++ it("getLog returns null when not found and normalizes when found", async () => {+ mockGetLogByRowId.mockResolvedValue({ record: undefined });+ expect(await adapter.getLog("row-1")).toBeNull();++ mockGetLogByRowId.mockResolvedValue({+ record: { Timestamp: "2026-07-01T00:00:00Z", Body: "boom" },+ });+ const log = await adapter.getLog("row-1");+ expect(log?.body).toBe("boom");+ });++ it("getLog throws the legacy error when the read fails", async () => {+ mockGetLogByRowId.mockResolvedValue({ err: new Error("log read failed") });+ await expect(adapter.getLog("row-1")).rejects.toThrow("log read failed");+ });++ it("logTimeSeries defaults rows to [] when getSignalSummary returns no buckets", async () => {+ mockGetSignalSummary.mockResolvedValue({});+ const frame = await adapter.logTimeSeries({ ...baseQuery, signal: "logs" });+ expect(frame.rows).toEqual([]);+ });++ it("logTimeSeries buckets by interval and throws the legacy error on failure", async () => {+ mockGetSignalSummary.mockResolvedValue({ buckets: [{ label: "10:00", count: 1 }] });+ const frame = await adapter.logTimeSeries({ ...baseQuery, signal: "logs" });+ expect(mockGetSignalSummary).toHaveBeenCalledWith(+ expect.objectContaining({ databaseConfigId: "db-1" }),+ "logs"+ );+ expect(frame.rows).toEqual([{ label: "10:00", count: 1 }]);++ mockGetSignalSummary.mockResolvedValue({ err: new Error("summary failed") });+ await expect(+ adapter.logTimeSeries({ ...baseQuery, signal: "logs" })+ ).rejects.toThrow("summary failed");+ });++ // ---- Metrics --------------------------------------------------------------++ it("listMetricSeries normalizes rows from the `records` shape with all optional fields present", async () => {+ mockGetMetrics.mockResolvedValue({+ records: [+ {+ metricName: "gen_ai.client.token.usage",+ metricDescription: "tokens",+ metricUnit: "tokens",+ serviceName: "svc",+ lastSeen: "2026-07-01T00:00:00Z",+ latestValue: "42",+ },+ ],+ total: 1,+ });+ const frame = await adapter.listMetricSeries({ ...baseQuery, signal: "metrics" });+ expect(frame.rows[0]).toMatchObject({+ metricName: "gen_ai.client.token.usage",+ description: "tokens",+ unit: "tokens",+ serviceName: "svc",+ timestamp: "2026-07-01T00:00:00Z",+ value: 42,+ });+ expect(frame.meta?.rowsScanned).toBe(1);+ });++ it("listMetricSeries falls back to the `data` shape and defaults missing optional fields", async () => {+ mockGetMetrics.mockResolvedValue({+ data: [{ metricName: "m" }],+ });+ const frame = await adapter.listMetricSeries({ ...baseQuery, signal: "metrics" });+ expect(frame.rows[0]).toMatchObject({+ metricName: "m",+ description: undefined,+ unit: undefined,+ serviceName: undefined,+ timestamp: "",+ value: 0,+ });+ expect(frame.meta?.rowsScanned).toBe(1);+ });++ it("listMetricSeries defaults metricName to '' when the row carries none", async () => {+ mockGetMetrics.mockResolvedValue({ records: [{}] });+ const frame = await adapter.listMetricSeries({ ...baseQuery, signal: "metrics" });+ expect(frame.rows[0].metricName).toBe("");+ });++ it("listMetricSeries defaults to [] when neither records nor data is present", async () => {+ mockGetMetrics.mockResolvedValue({});+ const frame = await adapter.listMetricSeries({ ...baseQuery, signal: "metrics" });+ expect(frame.rows).toEqual([]);+ });++ it("listMetricSeries throws the legacy error on failure", async () => {+ mockGetMetrics.mockResolvedValue({ err: new Error("metrics failed") });+ await expect(+ adapter.listMetricSeries({ ...baseQuery, signal: "metrics" })+ ).rejects.toThrow("metrics failed");+ });++ it("metricTimeSeries fetches per-metric detail series when a spanName filter names a metric", async () => {+ mockGetMetricDetail.mockResolvedValue({+ series: [{ request_time: "2026-07-01T00:00:00Z", value: "5" }],+ });+ const frame = await adapter.metricTimeSeries({+ ...baseQuery,+ signal: "metrics",+ filters: [+ { target: "spanName", op: "eq", value: "gen_ai.client.token.usage" },+ { target: "attribute", scope: "resource", key: "service.name", op: "eq", value: "svc" },+ ],+ });+ expect(mockGetMetricDetail).toHaveBeenCalledWith(+ "gen_ai.client.token.usage",+ undefined,+ "svc",+ expect.objectContaining({ databaseConfigId: "db-1" })+ );+ expect(frame.rows[0]).toMatchObject({+ metricName: "gen_ai.client.token.usage",+ serviceName: "svc",+ timestamp: "2026-07-01T00:00:00Z",+ value: 5,+ });+ });++ it("metricTimeSeries resolves array-valued spanName/service.name filters to their first element", async () => {+ mockGetMetricDetail.mockResolvedValue({ series: [] });+ await adapter.metricTimeSeries({+ ...baseQuery,+ signal: "metrics",+ filters: [+ { target: "spanName", op: "in", value: ["metric-a", "metric-b"] },+ {+ target: "attribute",+ scope: "resource",+ key: "service.name",+ op: "in",+ value: ["svc-a", "svc-b"],+ },+ ],+ });+ expect(mockGetMetricDetail).toHaveBeenCalledWith(+ "metric-a",+ undefined,+ "svc-a",+ expect.anything()+ );+ });++ it("metricTimeSeries omits serviceName when no service.name filter is present", async () => {+ mockGetMetricDetail.mockResolvedValue({ series: [] });+ await adapter.metricTimeSeries({+ ...baseQuery,+ signal: "metrics",+ filters: [{ target: "spanName", op: "eq", value: "m" }],+ });+ expect(mockGetMetricDetail).toHaveBeenCalledWith("m", undefined, undefined, expect.anything());+ });++ it("metricTimeSeries ignores an attribute filter whose key is not service.name", async () => {+ mockGetMetricDetail.mockResolvedValue({ series: [] });+ await adapter.metricTimeSeries({+ ...baseQuery,+ signal: "metrics",+ filters: [+ { target: "spanName", op: "eq", value: "m" },+ { target: "attribute", scope: "span", key: "gen_ai.system", op: "eq", value: "openai" },+ ],+ });+ expect(mockGetMetricDetail).toHaveBeenCalledWith("m", undefined, undefined, expect.anything());+ });++ it("metricTimeSeries defaults rows to [] when detail carries no series field", async () => {+ mockGetMetricDetail.mockResolvedValue({});+ const frame = await adapter.metricTimeSeries({+ ...baseQuery,+ signal: "metrics",+ filters: [{ target: "spanName", op: "eq", value: "m" }],+ });+ expect(frame.rows).toEqual([]);+ });++ it("metricTimeSeries defaults detail rows to '' timestamp / 0 value and throws the legacy error on failure", async () => {+ mockGetMetricDetail.mockResolvedValue({ series: [{}] });+ const frame = await adapter.metricTimeSeries({+ ...baseQuery,+ signal: "metrics",+ filters: [{ target: "spanName", op: "eq", value: "m" }],+ });+ expect(frame.rows[0]).toMatchObject({ timestamp: "", value: 0 });++ mockGetMetricDetail.mockResolvedValue({ err: new Error("detail failed") });+ await expect(+ adapter.metricTimeSeries({+ ...baseQuery,+ signal: "metrics",+ filters: [{ target: "spanName", op: "eq", value: "m" }],+ })+ ).rejects.toThrow("detail failed");+ });++ it("metricTimeSeries falls back to getSignalSummary when no spanName filter names a metric", async () => {+ mockGetSignalSummary.mockResolvedValue({ buckets: [{ label: "x", value: 1 }] });+ const frame = await adapter.metricTimeSeries({ ...baseQuery, signal: "metrics" });+ expect(mockGetSignalSummary).toHaveBeenCalledWith(expect.anything(), "metrics");+ expect(frame.rows).toEqual([{ label: "x", value: 1 }]);+ });++ it("metricTimeSeries falls back to getSignalSummary and throws the legacy error on failure", async () => {+ mockGetSignalSummary.mockResolvedValue({ err: new Error("metrics summary failed") });+ await expect(+ adapter.metricTimeSeries({ ...baseQuery, signal: "metrics" })+ ).rejects.toThrow("metrics summary failed");+ });++ it("metricNames returns the configured metric names, defaulting to [] when absent", async () => {+ mockGetMetricsConfig.mockResolvedValue({ data: [{ metricNames: ["m1", "m2"] }] });+ expect(await adapter.metricNames(window)).toEqual(["m1", "m2"]);++ mockGetMetricsConfig.mockResolvedValue({ data: [{}] });+ expect(await adapter.metricNames(window)).toEqual([]);+ });++ it("metricNames throws the legacy error on failure", async () => {+ mockGetMetricsConfig.mockResolvedValue({ err: new Error("metric names failed") });+ await expect(adapter.metricNames(window)).rejects.toThrow("metric names failed");+ });++ // ---- Discovery ------------------------------------------------------------++ it("discoverServices defaults to [] when the query returns no data field", async () => {+ mockDataCollector.mockResolvedValue({});+ expect(await adapter.discoverServices(window)).toEqual([]);+ });++ it("discoverServices passes through sdkLanguage/sdkVersion when present", async () => {+ mockDataCollector.mockResolvedValue({+ data: [+ {+ serviceName: "svc",+ sdkLanguage: "python",+ sdkVersion: "1.2.3",+ },+ ],+ });+ const services = await adapter.discoverServices(window);+ expect(services[0]).toMatchObject({ sdkLanguage: "python", sdkVersion: "1.2.3" });+ });++ it("discoverServices defaults optional sdk/timestamp fields to undefined and required fields to ''", async () => {+ mockDataCollector.mockResolvedValue({ data: [{}] });+ const services = await adapter.discoverServices(window);+ expect(services[0]).toEqual({+ serviceName: "",+ environment: "",+ clusterId: "",+ sdkName: undefined,+ sdkLanguage: undefined,+ sdkVersion: undefined,+ firstSeen: undefined,+ lastSeen: undefined,+ });+ });++ it("discoverServices throws the legacy error on failure", async () => {+ mockDataCollector.mockResolvedValue({ err: new Error("discover failed") });+ await expect(adapter.discoverServices(window)).rejects.toThrow("discover failed");+ });++ it("aggregateByService defaults to [] when the query returns no data field", async () => {+ mockDataCollector.mockResolvedValue({});+ expect(await adapter.aggregateByService(window)).toEqual([]);+ });++ it("aggregateByService maps rollup rows, filtering out falsy model/provider entries", async () => {+ mockDataCollector.mockResolvedValue({+ data: [+ {+ serviceName: "svc",+ environment: "prod",+ clusterId: "c1",+ requestCount: "5",+ models: ["gpt-4", "", null],+ providers: ["openai", undefined],+ },+ ],+ });+ const rollups = await adapter.aggregateByService(window);+ expect(rollups[0]).toEqual({+ serviceName: "svc",+ environment: "prod",+ clusterId: "c1",+ requestCount: 5,+ models: ["gpt-4"],+ providers: ["openai"],+ });+ });++ it("aggregateByService defaults requestCount/models/providers when rows are sparse", async () => {+ mockDataCollector.mockResolvedValue({ data: [{}] });+ const rollups = await adapter.aggregateByService(window);+ expect(rollups[0]).toMatchObject({+ serviceName: "",+ environment: "",+ clusterId: "",+ requestCount: 0,+ models: [],+ providers: [],+ });+ });++ it("aggregateByService throws the legacy error on failure", async () => {+ mockDataCollector.mockResolvedValue({ err: new Error("rollup failed") });+ await expect(adapter.aggregateByService(window)).rejects.toThrow("rollup failed");+ });++ // ---- sampleTracesForGraph edge cases ---------------------------------------++ it("sampleTracesForGraph defaults maxTraces to 100 when falsy/NaN", async () => {+ mockDataCollector+ .mockResolvedValueOnce({ data: [{ TraceId: "t1" }] })+ .mockResolvedValueOnce({ data: [] });+ await adapter.sampleTracesForGraph(baseQuery, NaN);+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).toContain("LIMIT 100");+ });++ it("sampleTracesForGraph throws the legacy error when the id lookup fails", async () => {+ mockDataCollector.mockResolvedValueOnce({ err: new Error("id lookup failed") });+ await expect(adapter.sampleTracesForGraph(baseQuery, 10)).rejects.toThrow(+ "id lookup failed"+ );+ });++ it("sampleTracesForGraph throws the legacy error when the span fetch fails", async () => {+ mockDataCollector+ .mockResolvedValueOnce({ data: [{ TraceId: "t1" }] })+ .mockResolvedValueOnce({ err: new Error("span fetch failed") });+ await expect(adapter.sampleTracesForGraph(baseQuery, 10)).rejects.toThrow(+ "span fetch failed"+ );+ });++ it("sampleTracesForGraph filters out rows with no TraceId before building the IN clause", async () => {+ mockDataCollector+ .mockResolvedValueOnce({ data: [{ TraceId: "t1" }, {}, { TraceId: "" }] })+ .mockResolvedValueOnce({ data: [] });+ await adapter.sampleTracesForGraph(baseQuery, 10);+ const secondSql = (mockDataCollector.mock.calls[1][0] as { query: string }).query;+ expect(secondSql).toContain("TraceId IN ('t1')");+ });++ it("sampleTracesForGraph treats a missing idResult.data field as no matching traces", async () => {+ mockDataCollector.mockResolvedValueOnce({});+ expect(await adapter.sampleTracesForGraph(baseQuery, 10)).toEqual([]);+ });++ it("sampleTracesForGraph defaults spans to [] when the span fetch returns no data field", async () => {+ mockDataCollector+ .mockResolvedValueOnce({ data: [{ TraceId: "t1" }] })+ .mockResolvedValueOnce({});+ expect(await adapter.sampleTracesForGraph(baseQuery, 10)).toEqual([]);+ });++ it("sampleTracesForGraph omits the aiSelector clause when aiSelector is false", async () => {+ mockDataCollector+ .mockResolvedValueOnce({ data: [{ TraceId: "t1" }] })+ .mockResolvedValueOnce({ data: [] });+ await adapter.sampleTracesForGraph({ ...baseQuery, aiSelector: false }, 10);+ const sql = (mockDataCollector.mock.calls[0][0] as { query: string }).query;+ expect(sql).not.toContain("telemetry.sdk.name");+ });++ // ---- validateAISignal / getTraceSpans / getSpansBySession legacy errors ---++ it("validateAISignal reports ok:false with the error message when the query fails (no throw)", async () => {+ mockDataCollector.mockResolvedValue({ err: new Error("validate failed") });+ const result = await adapter.validateAISignal(window);+ expect(result.ok).toBe(false);+ expect(result.message).toBe("Error: validate failed");+ });++ it("validateAISignal defaults sampleCount to 0 when no rows are returned", async () => {+ mockDataCollector.mockResolvedValue({ data: [] });+ const result = await adapter.validateAISignal(window);+ expect(result.sampleCount).toBe(0);+ expect(result.ok).toBe(false);+ });++ it("getTraceSpans throws the legacy error on failure", async () => {+ mockDataCollector.mockResolvedValue({ err: new Error("trace spans failed") });+ await expect(adapter.getTraceSpans("t1")).rejects.toThrow("trace spans failed");+ });++ it("getSpansBySession throws the legacy error on failure", async () => {+ mockDataCollector.mockResolvedValue({ err: new Error("session spans failed") });+ await expect(adapter.getSpansBySession("sess-1")).rejects.toThrow(+ "session spans failed"+ );+ });++ it("getSpan throws the legacy error on failure", async () => {+ mockDataCollector.mockResolvedValue({ err: new Error("get span failed") });+ await expect(adapter.getSpan("s1")).rejects.toThrow("get span failed");+ });++ it("healthCheck reports ok:false with the error message when the ping fails", async () => {+ mockDataCollector.mockResolvedValue({ err: new Error("ping failed") });+ const result = await adapter.healthCheck();+ expect(result.ok).toBe(false);+ expect(result.message).toBe("Error: ping failed");+ });++ it("spanTimeSeries throws the legacy error on failure", async () => {+ mockGetSignalSummary.mockResolvedValue({ err: new Error("span summary failed") });+ await expect(adapter.spanTimeSeries(baseQuery)).rejects.toThrow(+ "span summary failed"+ );+ });+});++describe("clickHouseAdapterFactory", () => {+ it("creates a ClickHouseAdapter instance bound to the given descriptor", () => {+ const created = clickHouseAdapterFactory.create(descriptor);+ expect(created).toBeInstanceOf(ClickHouseAdapter);+ expect(created.type).toBe("clickhouse");+ expect((created as ClickHouseAdapter).sampleCacheKey).toBe(descriptor.id);+ });++ it("describes the static ClickHouse source type", () => {+ const desc = clickHouseAdapterFactory.describe();+ expect(desc).toMatchObject({+ type: "clickhouse",+ displayName: "ClickHouse",+ declaredSignals: ["traces", "logs", "metrics"],+ authStyle: "none",+ configFields: [],+ capabilities: {+ traceTree: true,+ spanEvents: true,+ serverAggregation: true,+ spanMutation: true,+ distinctValues: true,+ crossTraceSession: true,+ rawQuery: true,+ },+ correlation: {+ crossSignal: true,+ keys: ["traceId", "spanId", "service", "session"],+ },+ });+ });});diff --git a/src/client/src/__tests__/lib/platform/datasource/downsample.test.ts b/src/client/src/__tests__/lib/platform/datasource/downsample.test.tsindex 451a74e6..962a7db2 100644--- a/src/client/src/__tests__/lib/platform/datasource/downsample.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/downsample.test.ts@@ -63,6 +63,28 @@ describe("computeIntervalMs", () => {expect(ms).toBe(5 * MIN);});+ it("defaults maxDataPoints to DEFAULT_MAX_DATA_POINTS when omitted", () => {+ const withDefault = computeIntervalMs({+ timeRange: range(HOUR),+ maxDataPoints: DEFAULT_MAX_DATA_POINTS,+ });+ const omitted = computeIntervalMs({ timeRange: range(HOUR) });+ expect(omitted).toBe(withDefault);+ });++ it("treats a zero or negative maxDataPoints as unset", () => {+ const withDefault = computeIntervalMs({+ timeRange: range(HOUR),+ maxDataPoints: DEFAULT_MAX_DATA_POINTS,+ });+ expect(computeIntervalMs({ timeRange: range(HOUR), maxDataPoints: 0 })).toBe(+ withDefault+ );+ expect(computeIntervalMs({ timeRange: range(HOUR), maxDataPoints: -5 })).toBe(+ withDefault+ );+ });+it("wider ranges produce coarser steps", () => {const hour = computeIntervalMs({ timeRange: range(HOUR), maxDataPoints: 300 });const week = computeIntervalMs({@@ -84,6 +106,11 @@ describe("rateIntervalMs", () => {});describe("clampStepMs", () => {+ it("floors a zero or negative step to the minimum interval", () => {+ expect(clampStepMs(HOUR, 0)).toBe(MIN_INTERVAL_MS);+ expect(clampStepMs(HOUR, -1000)).toBe(MIN_INTERVAL_MS);+ });+it("widens the step when points would exceed the cap", () => {const rangeMs = MAX_SERIES_POINTS * 10_000 * 2; // 2x the cap at 10s stepsconst step = clampStepMs(rangeMs, 10_000);@@ -126,6 +153,13 @@ describe("interval formatting", () => {});describe("alignRangeToStep", () => {+ it("returns the range unchanged when stepMs is zero or negative", () => {+ const start = new Date(1_000_000_000_123);+ const end = new Date(1_000_000_030_456);+ expect(alignRangeToStep({ start, end }, 0)).toEqual({ start, end });+ expect(alignRangeToStep({ start, end }, -1000)).toEqual({ start, end });+ });+it("floors start and ceils end to the step so windows dedupe", () => {const start = new Date(1_000_000_000_123);const end = new Date(1_000_000_030_456);diff --git a/src/client/src/__tests__/lib/platform/datasource/endpoint-url.test.ts b/src/client/src/__tests__/lib/platform/datasource/endpoint-url.test.tsindex 34ffc11c..06af3b59 100644--- a/src/client/src/__tests__/lib/platform/datasource/endpoint-url.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/endpoint-url.test.ts@@ -1,5 +1,8 @@import {+ canonicalizeFetchUrl,isEnabledSetting,+ isRunningInDocker,+ joinDatasourceRequestUrl,normalizeDatasourceEndpointUrl,rewriteLoopbackEndpointForDocker,} from "@/lib/platform/connectors/datasource/http/endpoint-url";@@ -20,6 +23,96 @@ describe("normalizeDatasourceEndpointUrl", () => {"http://localhost:9090");});++ it("returns an empty string unchanged", () => {+ expect(normalizeDatasourceEndpointUrl("")).toBe("");+ });++ it("strips trailing slashes from non-http(s) protocols without throwing", () => {+ expect(normalizeDatasourceEndpointUrl("ftp://files.example.com/dir/")).toBe(+ "ftp://files.example.com/dir"+ );+ });++ it("falls back to trailing-slash stripping when the URL cannot be parsed", () => {+ expect(normalizeDatasourceEndpointUrl("not a url///")).toBe("not a url");+ });+});++describe("canonicalizeFetchUrl", () => {+ it("trims whitespace and leaves well-formed URLs unchanged", () => {+ expect(canonicalizeFetchUrl(" https://example.com/path ")).toBe(+ "https://example.com/path"+ );+ });++ it("returns an empty string for nullish input", () => {+ expect(canonicalizeFetchUrl(undefined as unknown as string)).toBe("");+ });+});++describe("joinDatasourceRequestUrl", () => {+ it("joins a base and a path with exactly one slash", () => {+ expect(joinDatasourceRequestUrl("http://localhost:3100", "loki/api/v1/push")).toBe(+ "http://localhost:3100/loki/api/v1/push"+ );+ });++ it("normalizes duplicated slashes at the join point", () => {+ expect(joinDatasourceRequestUrl("http://localhost:3100/", "/loki/push")).toBe(+ "http://localhost:3100/loki/push"+ );+ });++ it("returns just the suffix when the base is empty", () => {+ expect(joinDatasourceRequestUrl("", "v1/memories/123/")).toBe(+ "v1/memories/123/"+ );+ });++ it("returns just the base when the path is empty", () => {+ expect(joinDatasourceRequestUrl("http://localhost:3100", "")).toBe(+ "http://localhost:3100"+ );+ });++ it("preserves a trailing slash on the joined path", () => {+ expect(+ joinDatasourceRequestUrl("http://localhost:3100", "v1/memories/123/")+ ).toBe("http://localhost:3100/v1/memories/123/");+ });+});++describe("isRunningInDocker", () => {+ it("returns the injected exists() result", () => {+ expect(isRunningInDocker(() => true)).toBe(true);+ expect(isRunningInDocker(() => false)).toBe(false);+ });++ it("returns false when the exists() check throws", () => {+ expect(+ isRunningInDocker(() => {+ throw new Error("fs unavailable");+ })+ ).toBe(false);+ });++ it("uses the default fs.existsSync-backed check and survives it throwing", () => {+ // Use the same require("fs") reference the source module resolves at+ // call time (a namespace `import * as fs` would spy on a separate+ // interop-copied object and silently miss the real module).+ const fs = require("fs");+ const spy = jest+ .spyOn(fs, "existsSync")+ .mockImplementation(() => {+ throw new Error("boom");+ });+ try {+ expect(isRunningInDocker()).toBe(false);+ } finally {+ spy.mockRestore();+ }+ });});describe("rewriteLoopbackEndpointForDocker", () => {@@ -45,6 +138,30 @@ describe("rewriteLoopbackEndpointForDocker", () => {rewriteLoopbackEndpointForDocker("http://localhost:3100", { enabled: false })).toBe("http://localhost:3100");});++ it("returns the raw URL unchanged when it cannot be parsed even when enabled", () => {+ expect(+ rewriteLoopbackEndpointForDocker("not a url", { enabled: true })+ ).toBe("not a url");+ });++ it("returns the raw URL unchanged when canonicalization yields an empty string", () => {+ expect(rewriteLoopbackEndpointForDocker("", { enabled: true })).toBe("");+ });++ it("preserves a trailing slash on the rewritten loopback URL", () => {+ expect(+ rewriteLoopbackEndpointForDocker("http://localhost:3100/loki/", {+ enabled: true,+ })+ ).toBe("http://host.docker.internal:3100/loki/");+ });++ it("defaults enabled to isRunningInDocker() when not explicitly set", () => {+ expect(rewriteLoopbackEndpointForDocker("http://localhost:3100")).toBe(+ "http://localhost:3100"+ );+ });});describe("isEnabledSetting / selfHostedNetworkOptions", () => {diff --git a/src/client/src/__tests__/lib/platform/datasource/grafana-coverage.test.ts b/src/client/src/__tests__/lib/platform/datasource/grafana-coverage.test.tsnew file mode 100644index 00000000..d9ad3ca8--- /dev/null+++ b/src/client/src/__tests__/lib/platform/datasource/grafana-coverage.test.ts@@ -0,0 +1,1398 @@+/**+ * Extra coverage for the Grafana connector adapters (tempo.ts, loki.ts,+ * openplait-http.ts). This file targets uncovered branches/statements+ * (error-handling paths, format fallbacks, aggregation switch cases, cache+ * eviction, query-mode variants) that the primary `grafana.test.ts` suite+ * does not exercise. See that file for the base mocking setup this mirrors.+ */+const mockSafeFetch = jest.fn();++jest.mock("@/lib/platform/connectors/datasource/http/safe-fetch", () => ({+ safeFetch: (...args: unknown[]) => mockSafeFetch(...args),+ SourceResponseError: class SourceResponseError extends Error {+ status: number;+ constructor(status: number, message: string) {+ super(message);+ this.status = status;+ }+ },+ selfHostedNetworkOptions: () => ({+ allowHttp: true,+ allowPrivateNetwork: true,+ }),+}));+jest.mock("@/lib/platform/connectors/datasource/http/secret", () => ({+ resolveSourceSecret: jest.fn().mockResolvedValue({+ raw: "tok",+ credentials: { token: "tok" },+ }),+ redactableSecretValues: () => ["tok"],+}));++import {+ TempoAdapter,+ tempoAdapterFactory,+ buildTempoSearchQuery,+ tempoAISelectorQuery,+ __clearTempoSpanIndex,+} from "@/lib/platform/connectors/datasource/grafana/tempo";+import {+ LokiAdapter,+ lokiAdapterFactory,+ parseLokiDurationMs,+ reportedLokiMaxQueryRangeMs,+ __resetLokiLearningForTests,+} from "@/lib/platform/connectors/datasource/grafana/loki";+import { SourceResponseError } from "@/lib/platform/connectors/datasource/http/safe-fetch";+import { resolveSourceSecret } from "@/lib/platform/connectors/datasource/http/secret";+import { __clearCache } from "@/lib/platform/connectors/datasource/http/cache";+import type {+ TelemetrySourceDescriptor,+} from "@/lib/platform/connectors/datasource/types";++const window = {+ start: new Date("2026-07-01T00:00:00.000Z"),+ end: new Date("2026-07-02T00:00:00.000Z"),+};++const TRACE_1 = "0123456789abcdef0123456789abcdef";+const TRACE_2 = "fedcba9876543210fedcba9876543210";+const SPAN_1 = "0123456789abcdef";+const SPAN_2 = "fedcba9876543210";++function otlpForTrace(+ traceId: string,+ spanId: string,+ overrides: Record<string, unknown> = {}+) {+ return {+ batches: [+ {+ resource: {+ attributes: [+ { key: "service.name", value: { stringValue: "svc" } },+ ],+ },+ scopeSpans: [+ {+ spans: [+ {+ traceId,+ spanId,+ parentSpanId: "",+ name: "chat",+ startTimeUnixNano: "1719792000000000000",+ endTimeUnixNano: "1719792001000000000",+ status: { code: 1 },+ attributes: [+ { key: "gen_ai.request.model", value: { stringValue: "gpt-4" } },+ ],+ events: [],+ ...overrides,+ },+ ],+ },+ ],+ },+ ],+ };+}++beforeEach(() => {+ // Full reset (not just clearAllMocks) so an unconsumed `mockResolvedValueOnce`/+ // `mockRejectedValueOnce` queued by one test can never leak into the next.+ mockSafeFetch.mockReset();+ (resolveSourceSecret as jest.Mock).mockReset();+ (resolveSourceSecret as jest.Mock).mockResolvedValue({+ raw: "tok",+ credentials: { token: "tok" },+ });+ __clearCache();+ __clearTempoSpanIndex();+ __resetLokiLearningForTests();+});++describe("tempoAdapterFactory", () => {+ it("describes config fields and creates a TempoAdapter instance", () => {+ const info = tempoAdapterFactory.describe();+ expect(info.type).toBe("tempo");+ expect(info.declaredSignals).toEqual(["traces"]);+ expect(info.configFields.some((f) => f.key === "tempoVersion")).toBe(true);+ expect(info.configFields.some((f) => f.key === "enableMostRecent")).toBe(true);+ expect(info.configFields.some((f) => f.key === "metricsMaxTimeRangeHours")).toBe(true);+ const created = tempoAdapterFactory.create({+ type: "tempo",+ id: "factory-tempo",+ isBuiltIn: false,+ settings: { url: "https://tempo.example.com" },+ signals: ["traces"],+ name: "Tempo",+ });+ expect(created).toBeInstanceOf(TempoAdapter);+ });+});++describe("TempoAdapter additional coverage", () => {+ const descriptor: TelemetrySourceDescriptor = {+ type: "tempo",+ id: "src-tempo-cov",+ isBuiltIn: false,+ settings: { url: "https://tempo.example.com", allowHttp: false },+ signals: ["traces"],+ name: "Tempo",+ };++ it("normalizes span events, unset status, and non-object event items defensively", async () => {+ const adapter = new TempoAdapter(descriptor);+ mockSafeFetch.mockResolvedValueOnce(+ otlpForTrace(TRACE_1, SPAN_1, {+ status: { code: 0 },+ events: [+ null,+ "not-an-object",+ {+ name: "gen_ai.content.completion",+ // Non-integer nanos: BigInt() throws -> eventTimestamp catch path.+ timeUnixNano: 1.5,+ attributes: [+ { key: "int", value: { intValue: 5 } },+ { key: "double", value: { doubleValue: 1.5 } },+ { key: "bool", value: { boolValue: true } },+ { key: "empty", value: {} },+ { key: 123, value: { stringValue: "skip-non-string-key" } },+ "not-an-object-attr",+ ],+ },+ ],+ })+ );++ const spans = await adapter.getTraceSpans(TRACE_1);+ expect(spans).toHaveLength(1);+ expect(spans[0].statusCode).toBe("STATUS_CODE_UNSET");+ expect(spans[0].events).toHaveLength(3);+ expect(spans[0].events?.[0]).toMatchObject({ name: "", timestamp: undefined });+ expect(spans[0].events?.[1]).toMatchObject({ name: "", timestamp: undefined });+ const real = spans[0].events?.[2];+ expect(real?.name).toBe("gen_ai.content.completion");+ expect(real?.timestamp).toBeUndefined();+ expect(real?.attributes).toMatchObject({+ int: "5",+ double: "1.5",+ bool: "true",+ empty: "",+ });+ });++ it("evicts the oldest indexed span once the process-wide span index is full", async () => {+ const adapter = new TempoAdapter({+ ...descriptor,+ id: "src-tempo-span-index",+ });+ const SPAN_INDEX_MAX = 5_000;+ let call = 0;+ const hex = (n: number, len: number) => n.toString(16).padStart(len, "0");+ mockSafeFetch.mockImplementation(async () => {+ const idx = call++;+ return otlpForTrace(hex(idx, 32), hex(idx, 16));+ });+ for (let i = 0; i <= SPAN_INDEX_MAX; i++) {+ // eslint-disable-next-line no-await-in-loop+ await adapter.getTraceSpans(hex(i, 32));+ }++ mockSafeFetch.mockReset();+ mockSafeFetch.mockResolvedValueOnce({ traces: [] });+ const evicted = await adapter.getSpan(hex(0, 16));+ expect(evicted).toBeNull();+ expect(mockSafeFetch).toHaveBeenCalledTimes(1);++ const recent = await adapter.getSpan(hex(SPAN_INDEX_MAX, 16));+ expect(recent?.spanId).toBe(hex(SPAN_INDEX_MAX, 16));+ // Resolved straight from the warm index — no extra HTTP call.+ expect(mockSafeFetch).toHaveBeenCalledTimes(1);+ }, 20_000);++ it("filters listSpans issue rows by generationHealth chips and drops non-matching traces", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-genhealth" });+ mockSafeFetch+ .mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }, { traceID: TRACE_2 }] })+ .mockResolvedValueOnce(+ otlpForTrace(TRACE_1, SPAN_1, {+ attributes: [+ {+ key: "gen_ai.response.finish_reasons",+ value: { stringValue: "length" },+ },+ ],+ })+ )+ .mockResolvedValueOnce(otlpForTrace(TRACE_2, SPAN_2));++ const frame = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ limit: 25,+ aiSelector: false,+ generationHealth: ["truncated"],+ });++ expect(frame.rows).toHaveLength(1);+ expect(frame.rows[0]).toMatchObject({ traceId: TRACE_1 });+ });++ it("uses an explicit maxTimeRangeMs setting (not just maxTimeRangeDays)", () => {+ const adapter = new TempoAdapter({+ ...descriptor,+ id: "src-tempo-ms",+ settings: { ...descriptor.settings, maxTimeRangeMs: 3 * 60 * 60 * 1000 },+ });+ expect(adapter.capabilities().maxTimeRangeMs).toBe(3 * 60 * 60 * 1000);+ });++ it("floors a tiny configured maxTimeRangeMs to the 60s minimum", () => {+ const adapter = new TempoAdapter({+ ...descriptor,+ id: "src-tempo-ms-floor",+ settings: { ...descriptor.settings, maxTimeRangeMs: 10 },+ });+ expect(adapter.capabilities().maxTimeRangeMs).toBe(60_000);+ });++ it("honors an explicit enableMostRecent=true setting without a prior health check", async () => {+ const adapter = new TempoAdapter({+ ...descriptor,+ id: "src-tempo-explicit-mostrecent",+ settings: { ...descriptor.settings, enableMostRecent: true },+ });+ mockSafeFetch.mockResolvedValueOnce({ traces: [] });+ await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ limit: 1,+ });+ const searchUrl = decodeURIComponent(mockSafeFetch.mock.calls[0][0] as string).replace(/\+/g, " ");+ expect(searchUrl).toContain("with (most_recent=true)");+ });++ it("downgrades a cached most_recent profile when a generic 400 rejects the hint, then retries", async () => {+ const adapter = new TempoAdapter({+ ...descriptor,+ id: "src-tempo-hint-downgrade",+ });+ mockSafeFetch+ .mockResolvedValueOnce({ version: "2.8.2" }) // buildinfo -> caches mostRecent undefined (no explicit feature flag in this shape)+ .mockRejectedValueOnce(+ new SourceResponseError(400, "invalid TraceQL near with (most_recent=true)")+ )+ .mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }] });+ await adapter.healthCheck();+ // Force most_recent on via settings so the search actually includes the hint,+ // independent of whatever the health probe inferred.+ (adapter as unknown as { descriptor: TelemetrySourceDescriptor }).descriptor.settings.enableMostRecent = true;+ const ids = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ limit: 1,+ });+ expect(ids.rows).toHaveLength(1);+ expect(mockSafeFetch).toHaveBeenCalledTimes(3);+ const retried = decodeURIComponent(mockSafeFetch.mock.calls[2][0] as string).replace(/\+/g, " ");+ expect(retried).not.toContain("most_recent");+ });++ it("retries the hint without touching the profile cache when no health check has run yet", async () => {+ const adapter = new TempoAdapter({+ ...descriptor,+ id: "src-tempo-hint-no-profile",+ settings: { ...descriptor.settings, enableMostRecent: true },+ });+ mockSafeFetch+ .mockRejectedValueOnce(new SourceResponseError(400, "invalid TraceQL near with"))+ .mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }] });+ const frame = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ limit: 1,+ });+ expect(frame.rows).toHaveLength(1);+ expect(mockSafeFetch).toHaveBeenCalledTimes(2);+ });++ it("clamps a fixed-window health-check fallback search to a tight configured maxTimeRangeMs", async () => {+ const adapter = new TempoAdapter({+ ...descriptor,+ id: "src-tempo-health-clamp",+ settings: { ...descriptor.settings, maxTimeRangeMs: 60_000 },+ });+ mockSafeFetch+ .mockRejectedValueOnce(new SourceResponseError(404, "buildinfo is not exposed"))+ .mockResolvedValueOnce({ traces: [] });+ await expect(adapter.healthCheck()).resolves.toMatchObject({ ok: true });+ const searchUrl = new URL(mockSafeFetch.mock.calls[1][0] as string);+ const startSec = Number(searchUrl.searchParams.get("start"));+ const endSec = Number(searchUrl.searchParams.get("end"));+ // The fixed 5-minute fallback window must be clamped down to the 60s cap.+ expect(endSec - startSec).toBeLessThanOrEqual(60);+ });++ it("reports healthCheck failure when the managed-gateway fallback search also fails", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-health-double-fail" });+ mockSafeFetch+ .mockRejectedValueOnce(new SourceResponseError(404, "buildinfo is not exposed"))+ .mockRejectedValueOnce(new Error("network unreachable"));+ await expect(adapter.healthCheck()).resolves.toMatchObject({+ ok: false,+ message: expect.stringContaining("Tempo request failed"),+ });+ });++ it("throws a clear error when basic auth is configured but no username is resolvable", async () => {+ (resolveSourceSecret as jest.Mock).mockResolvedValueOnce({+ raw: "",+ credentials: {},+ });+ const adapter = new TempoAdapter({+ ...descriptor,+ id: "src-tempo-auth-required",+ settings: { ...descriptor.settings, authType: "basic" },+ });+ const result = await adapter.healthCheck();+ expect(result.ok).toBe(false);+ expect(result.message).toContain("basic");+ });++ it("propagates a non-HTTP transport error from the guarded fetch instead of swallowing it", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-transport-error" });+ mockSafeFetch.mockRejectedValueOnce(new TypeError("fetch failed: getaddrinfo ENOTFOUND"));+ // The guarded fetch only intercepts SourceResponseError; any other+ // transport error (network/DNS/etc.) must propagate, not be swallowed+ // into a fake 200 response.+ await expect(+ adapter.listSpans({ signal: "traces", timeRange: window, aiSelector: false, limit: 1 })+ ).rejects.toThrow(/Tempo request failed/);+ });++ it("getSpan returns null when the TraceQL span-id search has no hits", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-getspan-empty" });+ mockSafeFetch.mockResolvedValueOnce({ traces: [] });+ await expect(adapter.getSpan(SPAN_1)).resolves.toBeNull();+ });++ it("getSpan returns null when the TraceQL search itself throws", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-getspan-throw" });+ mockSafeFetch.mockRejectedValueOnce(new SourceResponseError(500, "boom"));+ await expect(adapter.getSpan(SPAN_1)).resolves.toBeNull();+ });++ it("aggregateSpans: sum/min/max/avg all resolve via TraceQL metrics with duration unit conversion", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-agg-fns" });+ const t0 = window.start.getTime();+ mockSafeFetch+ .mockResolvedValueOnce({ series: [{ labels: [], samples: [{ timestampMs: t0, value: 10 }] }] }) // count anchor+ .mockResolvedValueOnce({ series: [{ labels: [], samples: [{ timestampMs: t0, value: 40 }] }] }) // sum(cost)+ .mockResolvedValueOnce({ series: [{ labels: [], samples: [{ timestampMs: t0, value: 20_000_000_000 }] }] }) // sum(duration) for avg+ .mockResolvedValueOnce({ series: [{ labels: [], samples: [{ timestampMs: t0, value: 5_000_000_000 }] }] }) // min(duration)+ .mockResolvedValueOnce({ series: [{ labels: [], samples: [{ timestampMs: t0, value: 99 }] }] }); // max(tokens)++ const frame = await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ aggregations: [+ { fn: "count", as: "count" },+ { fn: "sum", field: "gen_ai.usage.cost", as: "totalCost" },+ { fn: "avg", field: "duration", as: "avgDuration" },+ { fn: "min", field: "duration", as: "minDuration" },+ { fn: "max", field: "gen_ai.usage.output_tokens", as: "maxTokens" },+ ],+ });+ const row = frame.rows[0] as Record<string, number>;+ expect(row.count).toBe(10);+ expect(row.totalCost).toBe(40);+ expect(row.avgDuration).toBeCloseTo(2); // 20e9 ns / 10 -> seconds+ expect(row.minDuration).toBeCloseTo(5); // ns -> seconds+ expect(row.maxTokens).toBe(99);+ });++ it("aggregateSpans groups by span name and by resource.service.name aliases", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-group-aliases" });+ mockSafeFetch.mockResolvedValueOnce({+ series: [{ labels: [{ key: "name", value: "chat" }], samples: [{ timestampMs: window.start.getTime(), value: 3 }] }],+ });+ const byName = await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ groupBy: ["spanName"],+ aggregations: [{ fn: "count", as: "count" }],+ });+ expect((byName.rows[0] as any).count).toBe(3);+ const metricsUrl = decodeURIComponent(mockSafeFetch.mock.calls[0][0] as string).replace(/\+/g, " ");+ expect(metricsUrl).toContain("by (name)");++ mockSafeFetch.mockResolvedValueOnce({+ series: [{ labels: [{ key: "resource.service.name", value: "checkout" }], samples: [{ timestampMs: window.start.getTime(), value: 7 }] }],+ });+ const byService = await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ groupBy: ["applicationName"],+ aggregations: [{ fn: "count", as: "count" }],+ });+ expect((byService.rows[0] as any).count).toBe(7);+ });++ it("nativeAggregate returns null (falls back to L1) when the count anchor metric has no series", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-agg-null" });+ mockSafeFetch+ .mockRejectedValueOnce(new SourceResponseError(404, "metrics disabled"))+ .mockResolvedValueOnce({ traces: [] });+ const frame = await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ aggregations: [{ fn: "count", as: "count" }],+ });+ expect(frame.meta?.degraded).toContain("serverAggregation");+ });++ it("spanTimeSeries falls back to the L1 sample when native metrics reject with a non-404 error", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-spants-fallback" });+ mockSafeFetch+ .mockRejectedValueOnce(new SourceResponseError(500, "internal error"))+ .mockResolvedValueOnce({ traces: [] });+ const frame = await adapter.spanTimeSeries({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ interval: "1h",+ });+ expect(frame.meta?.degraded).toContain("serverAggregation");+ });++ it("spanTimeSeries applies avg aggregation per-bucket without weighting", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-spants-avg" });+ const t0 = window.start.getTime();+ mockSafeFetch+ .mockResolvedValueOnce({ series: [{ labels: [], samples: [{ timestampMs: t0, value: 4 }] }] }) // count+ .mockResolvedValueOnce({+ series: [+ // Distinct labels keep these as two separate series after+ // grouping so both contribute to the per-bucket average.+ { labels: [{ key: "span.kind", value: "client" }], samples: [{ timestampMs: t0, value: 2_000_000_000 }] },+ { labels: [{ key: "span.kind", value: "server" }], samples: [{ timestampMs: t0, value: 6_000_000_000 }] },+ ],+ }); // avg(duration) — two series contributing to the same bucket+ const frame = await adapter.spanTimeSeries({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ aggregations: [+ { fn: "count", as: "count" },+ { fn: "avg", field: "duration", as: "avgDuration" },+ ],+ });+ expect(frame.rows).toHaveLength(1);+ expect((frame.rows[0] as any).avgDuration).toBeCloseTo(4); // (2e9+6e9)/2 ns -> 4s+ });++ it("countSpans totals matching spans via count_over_time and returns null when metrics are unavailable", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-countspans" });+ mockSafeFetch.mockResolvedValueOnce({+ series: [{ labels: [], samples: [{ timestampMs: window.start.getTime(), value: 42 }] }],+ });+ await expect(+ adapter.countSpans!({ signal: "traces", timeRange: window, aiSelector: false })+ ).resolves.toBe(42);++ // Distinct window so this doesn't just replay the cached 42 from above.+ const laterWindow = {+ start: new Date(window.start.getTime() + 60_000),+ end: new Date(window.end.getTime() + 60_000),+ };+ mockSafeFetch.mockRejectedValueOnce(new SourceResponseError(404, "metrics disabled"));+ await expect(+ adapter.countSpans!({ signal: "traces", timeRange: laterWindow, aiSelector: false })+ ).resolves.toBeNull();+ });++ it("distinctValues falls back to the L1 sample for non-service attribute keys", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-distinct-l1" });+ mockSafeFetch.mockResolvedValueOnce({ traces: [] });+ await expect(+ adapter.distinctValues("gen_ai.request.model", {+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ })+ ).resolves.toEqual([]);+ });++ it("distinctValues('service.name') falls back to L1 when service discovery returns nothing", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-distinct-service-empty" });+ // Each of the 4 tag-value lookups (resource.service.name / service.name,+ // with/without the AI filter) makes an OpenPlait v2 call *and* OpenLIT's+ // own direct v1 call even when v2 succeeds empty (searchTagValues only+ // short-circuits on a non-empty result) — 8 calls — then the biased+ // full-trace fallback search (1) and finally the L1 sample's own+ // search (1).+ mockSafeFetch.mockResolvedValue({ tagValues: [] });+ mockSafeFetch.mockResolvedValueOnce({ tagValues: [] }); // resource.service.name v2 (+filter)+ mockSafeFetch.mockResolvedValueOnce({ tagValues: [] }); // resource.service.name v1 (+filter)+ mockSafeFetch.mockResolvedValueOnce({ tagValues: [] }); // service.name v2 (+filter)+ mockSafeFetch.mockResolvedValueOnce({ tagValues: [] }); // service.name v1 (+filter)+ mockSafeFetch.mockResolvedValueOnce({ tagValues: [] }); // resource.service.name v2 (no filter)+ mockSafeFetch.mockResolvedValueOnce({ tagValues: [] }); // resource.service.name v1 (no filter)+ mockSafeFetch.mockResolvedValueOnce({ tagValues: [] }); // service.name v2 (no filter)+ mockSafeFetch.mockResolvedValueOnce({ tagValues: [] }); // service.name v1 (no filter)+ mockSafeFetch.mockResolvedValueOnce({ traces: [] }); // discoverServices biased-sample search+ mockSafeFetch.mockResolvedValueOnce({ traces: [] }); // L1 fallback search+ await expect(+ adapter.distinctValues("service.name", {+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ })+ ).resolves.toEqual([]);+ expect(mockSafeFetch).toHaveBeenCalledTimes(10);+ });++ it("searchTagValues falls back to a direct v1 HTTP request when OpenPlait's discovery throws entirely", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-tagvalues-v1" });+ mockSafeFetch+ .mockRejectedValueOnce(new SourceResponseError(500, "v2 unavailable"))+ .mockResolvedValueOnce({ tagValues: ["checkout", "payments"] });+ await expect(adapter.discoverServices(window)).resolves.toEqual([+ { serviceName: "checkout", environment: "default", clusterId: "default" },+ { serviceName: "payments", environment: "default", clusterId: "default" },+ ]);+ expect(mockSafeFetch).toHaveBeenCalledTimes(2);+ const directUrl = new URL(mockSafeFetch.mock.calls[1][0] as string);+ expect(directUrl.pathname).toBe("/api/search/tag/resource.service.name/values");+ });++ it("propagates a hard failure when tag discovery and the biased-sample fallback all fail", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-tagvalues-both-fail" });+ // A 500 (not 400/404) makes OpenPlait's v2->v1 internal fallback rethrow+ // immediately; our own direct v1 request then also fails the same way,+ // so all four tag lookups resolve to `[]` and discoverServices finally+ // surfaces the biased-sample fallback's own hard failure.+ mockSafeFetch.mockRejectedValue(new SourceResponseError(500, "down"));+ await expect(adapter.discoverServices(window)).rejects.toThrow(/500/);+ });++ it("aggregateByService rolls up request counts, models, and providers per service/environment", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-agg-service" });+ mockSafeFetch+ .mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }, { traceID: TRACE_2 }] })+ .mockResolvedValueOnce(+ otlpForTrace(TRACE_1, SPAN_1, {+ attributes: [+ { key: "gen_ai.request.model", value: { stringValue: "gpt-4" } },+ { key: "gen_ai.system", value: { stringValue: "openai" } },+ ],+ })+ )+ .mockResolvedValueOnce({+ batches: [+ {+ resource: {+ attributes: [+ { key: "service.name", value: { stringValue: "svc" } },+ { key: "deployment.environment", value: { stringValue: "staging" } },+ ],+ },+ scopeSpans: [+ {+ spans: [+ {+ traceId: TRACE_2,+ spanId: SPAN_2,+ parentSpanId: "",+ name: "chat",+ startTimeUnixNano: "1719792000000000000",+ endTimeUnixNano: "1719792001000000000",+ status: { code: 1 },+ attributes: [],+ events: [],+ },+ ],+ },+ ],+ },+ ],+ });++ const rollups = await adapter.aggregateByService(window);+ const bySvc = Object.fromEntries(+ rollups.map((r) => [`${r.serviceName}|${r.environment}`, r])+ );+ expect(bySvc["svc|default"]).toMatchObject({+ requestCount: 1,+ models: ["gpt-4"],+ providers: ["openai"],+ });+ expect(bySvc["svc|staging"]).toMatchObject({ requestCount: 1, models: [], providers: [] });+ });++ it("validateAISignal reports a failure message when the probe search throws", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-validate-fail" });+ mockSafeFetch.mockRejectedValueOnce(new SourceResponseError(500, "boom"));+ await expect(adapter.validateAISignal(window)).resolves.toMatchObject({+ ok: false,+ sampleCount: 0,+ message: expect.stringContaining("500"),+ });+ });++ it("validateAISignal reports ok:true with a sample count when the probe search finds a trace", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-validate-ok" });+ mockSafeFetch.mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }] });+ await expect(adapter.validateAISignal(window)).resolves.toMatchObject({+ ok: true,+ sampleCount: 1,+ missingAttributes: [],+ });+ });+});++describe("filterToTraceQL / conditionToTraceQL via buildTempoSearchQuery", () => {+ it("translates every filter target/op combination the query layer can send", () => {+ const q = buildTempoSearchQuery({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [+ { target: "spanName", op: "eq", value: ["chat", "embed"] },+ { target: "status", op: "eq", value: "STATUS_CODE_ERROR" },+ { target: "attribute", scope: "span", key: "gen_ai.request.model", op: "exists" },+ { target: "attribute", scope: "resource", key: "service.name", op: "in", value: ["a", "b"] },+ // Unscoped key starting with a resource-ish prefix auto-infers resource scope.+ { target: "attribute", key: "k8s.namespace", op: "eq", value: "prod" },+ // Hostile key must be dropped entirely, not interpolated.+ { target: "attribute", scope: "span", key: 'x" || true', op: "eq", value: "y" },+ // `duration` has no TraceQL translation and must contribute nothing.+ { target: "duration", op: "gt", value: 100 },+ ],+ });+ expect(q).toContain('(name = "chat" || name = "embed")');+ expect(q).toContain("status = error");+ expect(q).toContain('span.gen_ai.request.model != ""');+ expect(q).toContain('(resource.service.name = "a" || resource.service.name = "b")');+ expect(q).toContain('resource.k8s.namespace = "prod"');+ expect(q).not.toContain("|| true");+ expect(q).not.toContain("gt");+ });++ it("treats a non-error status filter value as a status != error clause", () => {+ const q = buildTempoSearchQuery({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "status", op: "eq", value: "STATUS_CODE_OK" }],+ });+ expect(q).toContain("status != error");+ });+});++describe("tempoAISelectorQuery with a custom selector", () => {+ it("supports an attribute condition with op:'in' and a spanName condition with a single value", () => {+ const q = tempoAISelectorQuery({+ anyOf: [+ {+ allOf: [+ {+ target: "attribute",+ scope: "span",+ key: "gen_ai.system",+ op: "in",+ value: ["openai", "anthropic"],+ },+ ],+ },+ { allOf: [{ target: "spanName", op: "eq", value: "chat" }] },+ ],+ });+ expect(q).toContain('(span.gen_ai.system = "openai" || span.gen_ai.system = "anthropic")');+ expect(q).toContain('(name = "chat")');+ });+});++describe("TempoAdapter: metric helper edge cases", () => {+ const descriptor: TelemetrySourceDescriptor = {+ type: "tempo",+ id: "src-tempo-metrics-helpers",+ isBuiltIn: false,+ settings: { url: "https://tempo.example.com" },+ signals: ["traces"],+ name: "Tempo",+ };++ it("uses a 5-minute TraceQL step for a 5m interval (msToTempoDuration minute branch)", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-step-5m" });+ mockSafeFetch.mockResolvedValueOnce({ series: [] });+ await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ interval: "5m",+ aggregations: [{ fn: "count", as: "count" }],+ });+ const metricsUrl = decodeURIComponent(mockSafeFetch.mock.calls[0][0] as string);+ expect(metricsUrl).toContain("step=5m");+ });++ it("maps durationNs/Duration aliases and resource.* / span.* prefixed fields for metric aggregations", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-attr-aliases" });+ mockSafeFetch+ .mockResolvedValueOnce({ series: [{ labels: [], samples: [{ timestampMs: window.start.getTime(), value: 2 }] }] })+ .mockResolvedValueOnce({ series: [{ labels: [], samples: [{ timestampMs: window.start.getTime(), value: 20_000_000_000 }] }] });+ const frame = await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ aggregations: [+ { fn: "count", as: "count" },+ { fn: "avg", field: "durationNs", as: "avgDuration" },+ ],+ });+ // The "durationNs" alias maps to the same TraceQL `duration` attribute+ // as "duration", but the ns->seconds unit conversion only special-cases+ // the literal field name "duration" — the alias's result stays in the+ // raw Tempo metric unit. Documented via this assertion rather than+ // changed, since it is a narrow field-aliasing quirk, not a+ // user-facing correctness bug (query builders normalize to "duration").+ expect((frame.rows[0] as any).avgDuration).toBeCloseTo(10_000_000_000);+ // aggregateSpans computes avg as a weighted sum(field)/count rather than+ // using TraceQL's avg_over_time directly, so the second call requests+ // sum_over_time.+ const avgUrl = decodeURIComponent(mockSafeFetch.mock.calls[1][0] as string);+ expect(avgUrl).toContain("sum_over_time(duration)");++ mockSafeFetch+ .mockResolvedValueOnce({ series: [{ labels: [], samples: [{ timestampMs: window.start.getTime(), value: 5 }] }] })+ .mockResolvedValueOnce({ series: [{ labels: [], samples: [{ timestampMs: window.start.getTime(), value: 30 }] }] });+ await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ aggregations: [+ { fn: "count", as: "count" },+ { fn: "sum", field: "resource.custom.metric", as: "total" },+ ],+ });+ // The repeated "count" anchor query (identical window/signal) may be+ // served from the adapter's short-TTL query cache instead of issuing a+ // new request, so assert against the most recent safeFetch call rather+ // than a fixed index.+ const lastCallArgs = mockSafeFetch.mock.calls[mockSafeFetch.mock.calls.length - 1];+ const sumUrl = decodeURIComponent(lastCallArgs[0] as string);+ expect(sumUrl).toContain("sum_over_time(resource.custom.metric)");+ });++ it("treats an unsupported aggregation field/fn as contributing zero rather than throwing", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-unsupported-agg" });+ mockSafeFetch.mockResolvedValueOnce({+ series: [{ labels: [], samples: [{ timestampMs: window.start.getTime(), value: 3 }] }],+ });+ const frame = await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ // "p95" isn't one of count/sum/avg/min/max — aggregationToMetricExpr+ // returns null and the row must fall back to 0, not throw.+ aggregations: [{ fn: "p95" as any, field: "duration", as: "p95Duration" }],+ });+ expect((frame.rows[0] as any).p95Duration).toBe(0);+ // Only the count anchor call was made — no metrics call for the+ // unsupported aggregation expression.+ expect(mockSafeFetch).toHaveBeenCalledTimes(1);+ });++ it("defaults to a count aggregation when the query supplies none", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-default-agg" });+ mockSafeFetch.mockResolvedValueOnce({+ series: [{ labels: [], samples: [{ timestampMs: window.start.getTime(), value: 8 }] }],+ });+ const frame = await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect((frame.rows[0] as any).count).toBe(8);+ });++ it("nativeSpanTimeSeries skips a companion aggregation whose metrics query is unavailable", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-spants-partial" });+ mockSafeFetch+ .mockResolvedValueOnce({ series: [{ labels: [], samples: [{ timestampMs: window.start.getTime(), value: 5 }] }] }) // count+ .mockRejectedValueOnce(new SourceResponseError(500, "cost metrics down")); // sum(cost) fails -> null, skipped+ const frame = await adapter.spanTimeSeries({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ aggregations: [+ { fn: "count", as: "count" },+ { fn: "sum", field: "gen_ai.usage.cost", as: "cost" },+ ],+ });+ expect(frame.rows).toHaveLength(1);+ expect((frame.rows[0] as any).count).toBe(5);+ expect((frame.rows[0] as any).cost).toBeUndefined();+ });++ it("honors an explicit metricsMaxTimeRangeHours setting when chunking metric windows", async () => {+ const adapter = new TempoAdapter({+ ...descriptor,+ id: "src-tempo-metrics-window-hours",+ settings: { ...descriptor.settings, metricsMaxTimeRangeHours: 6 },+ });+ // A 24h range with a 6h max window must be split into 4 windows.+ mockSafeFetch.mockResolvedValue({ series: [] });+ await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ aggregations: [{ fn: "count", as: "count" }],+ });+ expect(mockSafeFetch).toHaveBeenCalledTimes(4);+ });++ it("does not re-touch the profile cache on a metrics 404 when no profile has been cached yet", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-metrics-404-no-profile" });+ mockSafeFetch.mockRejectedValueOnce(new SourceResponseError(404, "metrics disabled"));+ await expect(+ adapter.countSpans!({ signal: "traces", timeRange: window, aiSelector: false })+ ).resolves.toBeNull();+ });+});++describe("TempoAdapter: trace-summary field fallbacks", () => {+ const descriptor: TelemetrySourceDescriptor = {+ type: "tempo",+ id: "src-tempo-summary-fallbacks",+ isBuiltIn: false,+ settings: { url: "https://tempo.example.com" },+ signals: ["traces"],+ name: "Tempo",+ };++ it("drops trace-summary rows with an unparsable timestamp and defaults missing name/service/duration", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-summary-missing" });+ mockSafeFetch.mockResolvedValueOnce({+ traces: [+ { traceID: TRACE_1 }, // no startTimeUnixNano/rootServiceName/rootTraceName/durationMs at all+ {+ traceID: TRACE_2,+ rootServiceName: "checkout",+ rootTraceName: "POST /checkout",+ startTimeUnixNano: "1782864000000000000",+ durationMs: 25,+ },+ ],+ });+ const frame = await adapter.traceTimeSeries!({+ signal: "traces",+ timeRange: window,+ interval: "1h",+ aiSelector: false,+ aggregations: [{ fn: "count", as: "count" }],+ });+ // The trace with no parsable timestamp is dropped before rowsScanned is+ // computed, so only the one valid trace is counted/bucketed.+ expect(frame.meta?.rowsScanned).toBe(1);+ expect(+ (frame.rows as any[]).reduce((sum, row) => sum + Number(row.count || 0), 0)+ ).toBe(1);+ });+});++describe("TempoAdapter: span/trace grouping edge cases", () => {+ const descriptor: TelemetrySourceDescriptor = {+ type: "tempo",+ id: "src-tempo-grouping",+ isBuiltIn: false,+ settings: { url: "https://tempo.example.com" },+ signals: ["traces"],+ name: "Tempo",+ };++ it("skips spans with a blank span id or trace id when indexing/grouping for issue queries", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-blank-ids" });+ mockSafeFetch+ .mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }] })+ .mockResolvedValueOnce({+ batches: [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ spans: [+ // Blank ids: rememberSpans must skip indexing it, and+ // groupSpansByTrace must skip it entirely.+ {+ traceId: "",+ spanId: "",+ parentSpanId: "",+ name: "orphan",+ startTimeUnixNano: "1719792000000000000",+ endTimeUnixNano: "1719792001000000000",+ status: { code: 1 },+ attributes: [],+ events: [],+ },+ {+ traceId: TRACE_1,+ spanId: SPAN_1,+ parentSpanId: "",+ name: "chat",+ startTimeUnixNano: "1719792000000000000",+ endTimeUnixNano: "1719792001000000000",+ status: { code: 1 },+ attributes: [+ {+ key: "gen_ai.response.finish_reasons",+ value: { stringValue: "length" },+ },+ ],+ events: [],+ },+ ],+ },+ ],+ },+ ],+ });+ const frame = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ limit: 25,+ aiSelector: false,+ generationHealth: ["truncated"],+ });+ expect(frame.rows).toHaveLength(1);+ expect(frame.rows[0]).toMatchObject({ spanId: SPAN_1 });+ });++ it("agentLoop issue query treats a trace with no resolvable traceId as non-matching", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-agentloop-no-traceid" });+ mockSafeFetch+ .mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }] })+ .mockResolvedValueOnce({+ batches: [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ spans: [+ {+ traceId: "",+ spanId: SPAN_1,+ parentSpanId: "",+ name: "chat",+ startTimeUnixNano: "1719792000000000000",+ endTimeUnixNano: "1719792001000000000",+ status: { code: 1 },+ attributes: [],+ events: [],+ },+ ],+ },+ ],+ },+ ],+ });+ const frame = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ limit: 25,+ aiSelector: false,+ agentLoop: true,+ });+ expect(frame.rows).toHaveLength(0);+ });+});++describe("TempoAdapter: remaining fallback/edge branches", () => {+ const descriptor: TelemetrySourceDescriptor = {+ type: "tempo",+ id: "src-tempo-remaining",+ isBuiltIn: false,+ settings: { url: "https://tempo.example.com" },+ signals: ["traces"],+ name: "Tempo",+ };++ it("listSpans uses the default page size and offset when the query omits them", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-default-page" });+ mockSafeFetch.mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }] });+ const frame = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(frame.rows).toHaveLength(1);+ });++ it("fetchSampledSpans tolerates a 413 (payload too large) from a single trace fetch", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-413" });+ mockSafeFetch+ .mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }, { traceID: TRACE_2 }] })+ .mockRejectedValueOnce(new SourceResponseError(413, "trace payload too large"))+ .mockResolvedValueOnce(otlpForTrace(TRACE_2, SPAN_2));+ const spans = await adapter.sampleTracesForGraph(+ { signal: "traces", timeRange: window, aiSelector: false },+ 5+ );+ expect(spans).toHaveLength(1);+ expect(spans[0].traceId).toBe(TRACE_2);+ });++ it("searchTraceIds enables most_recent when only the cached server profile (not settings) reports support", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-profile-mostrecent" });+ mockSafeFetch+ .mockResolvedValueOnce({ version: "2.8.0", features: { mostRecent: true } })+ .mockResolvedValueOnce({ traces: [] });+ await adapter.healthCheck();+ await adapter.listSpans({ signal: "traces", timeRange: window, aiSelector: false, limit: 1 });+ const searchUrl = decodeURIComponent(mockSafeFetch.mock.calls[1][0] as string);+ expect(searchUrl).toContain("most_recent");+ });++ it("discoverServices' biased-sample fallback de-duplicates services seen on multiple spans", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-biased-dedupe" });+ mockSafeFetch+ .mockResolvedValue({ tagValues: [] }) // all 4 tag lookups (v2 + v1 each) come back empty+ .mockResolvedValueOnce({ tagValues: [] })+ .mockResolvedValueOnce({ tagValues: [] })+ .mockResolvedValueOnce({ tagValues: [] })+ .mockResolvedValueOnce({ tagValues: [] })+ .mockResolvedValueOnce({ tagValues: [] })+ .mockResolvedValueOnce({ tagValues: [] })+ .mockResolvedValueOnce({ tagValues: [] })+ .mockResolvedValueOnce({ tagValues: [] })+ .mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }, { traceID: TRACE_2 }] })+ .mockResolvedValueOnce(otlpForTrace(TRACE_1, SPAN_1))+ .mockResolvedValueOnce(otlpForTrace(TRACE_2, SPAN_2)); // same "svc" service.name as TRACE_1+ const services = await adapter.discoverServices(window);+ expect(services).toHaveLength(1);+ expect(services[0].serviceName).toBe("svc");+ });++ it("aggregateByService falls back to resourceAttributes['service.name'] when serviceName is unset", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-service-fallback" });+ mockSafeFetch.mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }] }).mockResolvedValueOnce({+ batches: [+ {+ resource: {+ attributes: [{ key: "service.name", value: { stringValue: "resource-svc" } }],+ },+ scopeSpans: [+ {+ spans: [+ {+ traceId: TRACE_1,+ spanId: SPAN_1,+ parentSpanId: "",+ name: "chat",+ startTimeUnixNano: "1719792000000000000",+ endTimeUnixNano: "1719792001000000000",+ status: { code: 1 },+ attributes: [],+ events: [],+ },+ ],+ },+ ],+ },+ ],+ });+ const rollups = await adapter.aggregateByService(window);+ expect(rollups).toHaveLength(1);+ expect(rollups[0].serviceName).toBe("resource-svc");+ });+});++describe("TempoAdapter: session-2 branch coverage", () => {+ const descriptor: TelemetrySourceDescriptor = {+ type: "tempo",+ id: "src-tempo-s2",+ isBuiltIn: false,+ settings: { url: "https://tempo.example.com" },+ signals: ["traces"],+ name: "Tempo",+ };++ it("reportedMaxDurationMs falls through to undefined when the 400 body has no parsable duration candidate", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-s2-nodur" });+ // Matches isSearchRangeLimitMessage ("maximum ... duration") but has no+ // digit+unit substring for goDurationMs to parse -> reportedMaxDurationMs+ // falls through its candidate loop to the final `undefined` return, so+ // the range-narrowing retry is skipped and the original error rethrows.+ mockSafeFetch.mockRejectedValueOnce(+ new SourceResponseError(400, "Data source responded 400: maximum duration exceeded")+ );+ await expect(+ adapter.listSpans({ signal: "traces", timeRange: window, aiSelector: false, limit: 1 })+ ).rejects.toThrow();+ });++ it("normalizedStatus maps a raw 'error' status string to STATUS_CODE_ERROR", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-s2-status-error" });+ mockSafeFetch.mockResolvedValueOnce(+ otlpForTrace(TRACE_1, SPAN_1, { status: { code: 2 } })+ );+ const spans = await adapter.getTraceSpans(TRACE_1);+ expect(spans[0].statusCode).toBe("STATUS_CODE_ERROR");+ });++ it("conditionToTraceQL drops an unsupported condition op, contributing nothing to the AI selector query", () => {+ const q = tempoAISelectorQuery({+ anyOf: [+ {+ allOf: [+ {+ target: "attribute",+ scope: "span",+ key: "gen_ai.system",+ op: "gt" as any,+ value: "x",+ },+ ],+ },+ ],+ });+ // The unsupported op returns "" from conditionToTraceQL, so the group's+ // filtered parts list is empty and it renders as an empty `()` clause.+ expect(q).toContain("()");+ expect(q).not.toContain("gen_ai.system");+ });++ it("filterToTraceQL treats a missing spanName filter value as an empty-string match", () => {+ const q = buildTempoSearchQuery({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "spanName", op: "eq", value: undefined }],+ });+ expect(q).toContain('name = ""');+ });++ it("filterToTraceQL treats a missing status filter value as a status != error clause", () => {+ const q = buildTempoSearchQuery({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "status", op: "eq", value: undefined }],+ });+ expect(q).toContain("status != error");+ });++ it("filterToTraceQL wraps a scalar (non-array) 'in' attribute value as a single-element group", () => {+ const q = buildTempoSearchQuery({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [+ {+ target: "attribute",+ scope: "span",+ key: "gen_ai.system",+ op: "in",+ value: "openai",+ },+ ],+ });+ expect(q).toContain('(span.gen_ai.system = "openai")');+ });++ it("metricAttrRef maps a bare 'service.name' field (no span./resource. prefix) to a resource-scoped attribute", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-s2-bare-field" });+ mockSafeFetch+ .mockResolvedValueOnce({ series: [{ labels: [], samples: [{ timestampMs: window.start.getTime(), value: 3 }] }] })+ .mockResolvedValueOnce({ series: [] });+ await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ aggregations: [+ { fn: "count", as: "count" },+ { fn: "sum", field: "service.name", as: "svc" },+ ],+ });+ const lastCall = mockSafeFetch.mock.calls[mockSafeFetch.mock.calls.length - 1];+ const sumUrl = decodeURIComponent(lastCall[0] as string);+ expect(sumUrl).toContain("sum_over_time(resource.service.name)");+ });++ it("msToTempoDuration falls back to a bare-seconds TraceQL step when the interval isn't a whole minute/hour multiple", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-s2-step-97s" });+ mockSafeFetch.mockResolvedValueOnce({ series: [] });+ await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window, // 24h range keeps a 97s step under the 1000-point cap+ aiSelector: false,+ interval: "97s",+ aggregations: [{ fn: "count", as: "count" }],+ });+ const metricsUrl = decodeURIComponent(mockSafeFetch.mock.calls[0][0] as string);+ expect(metricsUrl).toContain("step=97s");+ });++ it("seriesLabelValue matches a group label by its bare (unscoped) key and falls back to '' when no label matches at all", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-s2-label-shapes" });+ mockSafeFetch.mockResolvedValueOnce({+ series: [+ // Tempo returns the group label under the bare attribute name+ // (no "span."/"resource." prefix) — seriesLabelValue must accept it.+ {+ labels: [{ key: "gen_ai.request.model", value: "gpt-4" }],+ samples: [{ timestampMs: window.start.getTime(), value: 3 }],+ },+ // No label matches the scoped OR bare attribute name -> falls+ // through the loop entirely to the final `return ""`.+ {+ labels: [{ key: "some.unrelated.label", value: "x" }],+ samples: [{ timestampMs: window.start.getTime(), value: 1 }],+ },+ ],+ });+ const frame = await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ groupBy: ["gen_ai.request.model"],+ aggregations: [{ fn: "count", as: "count" }],+ });+ const groupValues = (frame.rows as Array<{ group_value: string }>)+ .map((r) => r.group_value)+ .sort();+ expect(groupValues).toEqual(["", "gpt-4"]);+ });++ it("filterToTraceQL treats an array of status values, matching if any entry looks like an error", () => {+ const q = buildTempoSearchQuery({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [+ { target: "status", op: "in", value: ["STATUS_CODE_OK", "error"] },+ ],+ });+ expect(q).toContain("status = error");+ });++ it("aggregateSpans falls back to the L1 sample when nativeAggregate throws (not just returns null)", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-s2-agg-throws" });+ jest+ .spyOn(adapter as unknown as { nativeAggregate: () => Promise<unknown> }, "nativeAggregate")+ .mockRejectedValue(new Error("boom"));+ mockSafeFetch+ .mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }] })+ .mockResolvedValueOnce(otlpForTrace(TRACE_1, SPAN_1));+ const frame = await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ aggregations: [{ fn: "count", as: "count" }],+ });+ expect(frame.meta?.degraded).toContain("serverAggregation");+ expect(Number((frame.rows[0] as any)?.count)).toBeGreaterThan(0);+ });++ it("spanTimeSeries falls back to the L1 sample when nativeSpanTimeSeries throws (not just returns null)", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-s2-spants-throws" });+ jest+ .spyOn(+ adapter as unknown as { nativeSpanTimeSeries: () => Promise<unknown> },+ "nativeSpanTimeSeries"+ )+ .mockRejectedValue(new Error("boom"));+ mockSafeFetch+ .mockResolvedValueOnce({ traces: [{ traceID: TRACE_1 }] })+ .mockResolvedValueOnce(+ otlpForTrace(TRACE_1, SPAN_1, {+ // bucketSpansByInterval only counts spans within the query's+ // timeRange, unlike aggregateSpansInProcess.+ startTimeUnixNano: String(window.start.getTime() * 1_000_000),+ endTimeUnixNano: String((window.start.getTime() + 1_000) * 1_000_000),+ })+ );+ const frame = await adapter.spanTimeSeries({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ aggregations: [{ fn: "count", as: "count" }],+ });+ expect(frame.meta?.degraded).toContain("serverAggregation");+ expect(+ (frame.rows as any[]).reduce((sum, row) => sum + Number(row.count || 0), 0)+ ).toBeGreaterThan(0);+ });++ it("honors an explicit metricsMaxTimeRangeMs setting (milliseconds, not just hours) when chunking metric windows", async () => {+ const adapter = new TempoAdapter({+ ...descriptor,+ id: "src-tempo-s2-window-ms",+ settings: { ...descriptor.settings, metricsMaxTimeRangeMs: 6 * 60 * 60 * 1000 },+ });+ mockSafeFetch.mockResolvedValue({ series: [] });+ await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window, // 24h range with a 6h max window -> 4 chunks+ aiSelector: false,+ aggregations: [{ fn: "count", as: "count" }],+ });+ expect(mockSafeFetch).toHaveBeenCalledTimes(4);+ });++ it("downgrades an already-cached Tempo profile's traceqlMetrics flag on a metrics 404, short-circuiting later metric calls", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-s2-404-with-profile" });+ mockSafeFetch.mockResolvedValueOnce({ version: "3.0.0" });+ await adapter.healthCheck();+ mockSafeFetch.mockRejectedValueOnce(new SourceResponseError(404, "metrics disabled"));+ await expect(+ adapter.countSpans!({ signal: "traces", timeRange: window, aiSelector: false })+ ).resolves.toBeNull();+ const callsBefore = mockSafeFetch.mock.calls.length;+ // A second metrics call must short-circuit via the now-downgraded cached+ // profile without another HTTP round-trip.+ await expect(+ adapter.countSpans!({ signal: "traces", timeRange: window, aiSelector: false })+ ).resolves.toBeNull();+ expect(mockSafeFetch.mock.calls.length).toBe(callsBefore);+ });++ it("distinctValues('service.name') resolves directly from discoverServices without falling back to the L1 sample", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-s2-distinct-direct" });+ mockSafeFetch.mockResolvedValueOnce({ tagValues: ["svc-a", "svc-b"] });+ const values = await adapter.distinctValues("service.name", {+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(values).toEqual(["svc-a", "svc-b"]);+ expect(mockSafeFetch).toHaveBeenCalledTimes(1);+ });++ it("distinctValues('service.name') falls through to the L1 sample when discoverServices throws", async () => {+ const adapter = new TempoAdapter({ ...descriptor, id: "src-tempo-s2-distinct-fallback" });+ // Every tag-value lookup and the biased-sample fallback search all fail+ // with a plain 500 (not a recognized 400 compat pattern), so+ // discoverServices itself rejects, exercising distinctValues' catch+ // branch before it falls through to the (also-failing) L1 sample.+ mockSafeFetch.mockRejectedValue(new SourceResponseError(500, "tag lookup unavailable"));+ await expect(+ adapter.distinctValues("service.name", {+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ })+ ).rejects.toThrow();+ });+});diff --git a/src/client/src/__tests__/lib/platform/datasource/grafana.test.ts b/src/client/src/__tests__/lib/platform/datasource/grafana.test.tsindex 91adc4cd..d80277ec 100644--- a/src/client/src/__tests__/lib/platform/datasource/grafana.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/grafana.test.ts@@ -959,4 +959,59 @@ describe("buildAggregateDag", () => {const edge = dag.edges.find((e) => e.from === "agent" && e.to === "llm");expect(edge?.count).toBe(2);});++ it("defaults missing span name, statusCode, and durationNs to safe fallbacks", () => {+ const spans = [+ span({+ spanId: "a",+ name: undefined as unknown as string,+ statusCode: undefined as unknown as string,+ durationNs: undefined as unknown as number,+ }),+ ];+ const dag = buildAggregateDag(spans);+ expect(dag.nodes).toHaveLength(1);+ expect(dag.nodes[0]).toMatchObject({+ name: "(unnamed)",+ count: 1,+ errorCount: 0,+ p50DurationMs: 0,+ p95DurationMs: 0,+ });+ });++ it("defaults an unnamed parent span to '(unnamed)' in the edge's from field", () => {+ const spans = [+ span({ spanId: "parent", name: undefined as unknown as string }),+ span({ spanId: "child", parentSpanId: "parent", name: "child-span" }),+ ];+ const dag = buildAggregateDag(spans);+ const edge = dag.edges.find((e) => e.to === "child-span");+ expect(edge).toMatchObject({ from: "(unnamed)", to: "child-span", count: 1 });+ });++ it("returns empty nodes/edges for an empty span list", () => {+ const dag = buildAggregateDag([]);+ expect(dag).toEqual({+ nodes: [],+ edges: [],+ sampledTraces: 0,+ sampledSpans: 0,+ });+ });++ it("does not create an edge when the parent span belongs to a different trace", () => {+ const spans = [+ span({ spanId: "p", traceId: "t1", name: "parent" }),+ span({+ spanId: "c",+ traceId: "t2",+ parentSpanId: "p",+ name: "child",+ }),+ ];+ const dag = buildAggregateDag(spans);+ expect(dag.edges).toHaveLength(0);+ expect(dag.nodes.map((n) => n.name).sort()).toEqual(["child", "parent"]);+ });});diff --git a/src/client/src/__tests__/lib/platform/datasource/jaeger-victoria.test.ts b/src/client/src/__tests__/lib/platform/datasource/jaeger-victoria.test.tsindex 4a2744fa..dd0791cb 100644--- a/src/client/src/__tests__/lib/platform/datasource/jaeger-victoria.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/jaeger-victoria.test.ts@@ -6,6 +6,13 @@ jest.mock("@/lib/platform/connectors/datasource/http/safe-fetch", () => ({allowHttp: true,allowPrivateNetwork: true,}),+ SourceResponseError: class SourceResponseError extends Error {+ status: number;+ constructor(status: number, message: string) {+ super(message);+ this.status = status;+ }+ },}));jest.mock("@/lib/platform/connectors/datasource/http/secret", () => ({resolveSourceSecret: jest.fn().mockResolvedValue({@@ -25,6 +32,7 @@ import type {NormalizedSpan,TelemetrySourceDescriptor,} from "@/lib/platform/connectors/datasource/types";+import type { AITelemetrySelector } from "@/lib/platform/connectors/datasource/ai-selector";const window = {start: new Date("2026-07-01T00:00:00.000Z"),@@ -82,6 +90,162 @@ describe("selector-match", () => {];expect(traceMatchesAISelector(spans)).toBe(true);});++ it("falls back to unscoped attribute lookup, checking span attributes then resource attributes", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ { allOf: [{ target: "attribute", key: "custom.key", op: "exists" }] },+ ],+ };+ expect(+ spanMatchesAISelector(+ span({+ spanAttributes: { "custom.key": "from-span" },+ resourceAttributes: { "custom.key": "from-resource" },+ }),+ selector+ )+ ).toBe(true);+ expect(+ spanMatchesAISelector(+ span({ resourceAttributes: { "custom.key": "from-resource" } }),+ selector+ )+ ).toBe(true);+ expect(spanMatchesAISelector(span({}), selector)).toBe(false);+ });++ it("matches the 'in' operator against an array of candidate values", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ {+ allOf: [+ {+ target: "attribute",+ scope: "span",+ key: "gen_ai.system",+ op: "in",+ value: ["openai", "anthropic"],+ },+ ],+ },+ ],+ };+ expect(+ spanMatchesAISelector(+ span({ spanAttributes: { "gen_ai.system": "anthropic" } }),+ selector+ )+ ).toBe(true);+ expect(+ spanMatchesAISelector(+ span({ spanAttributes: { "gen_ai.system": "cohere" } }),+ selector+ )+ ).toBe(false);+ });++ it("matches the 'in' operator against a scalar (non-array) value", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ {+ allOf: [+ {+ target: "attribute",+ scope: "span",+ key: "gen_ai.system",+ op: "in",+ value: "openai",+ },+ ],+ },+ ],+ };+ expect(+ spanMatchesAISelector(+ span({ spanAttributes: { "gen_ai.system": "openai" } }),+ selector+ )+ ).toBe(true);+ });++ it("defaults the attribute key to an empty string when no key is provided", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ { allOf: [{ target: "attribute", scope: "resource", op: "exists" }] },+ ],+ };+ expect(spanMatchesAISelector(span({}), selector)).toBe(false);+ });++ it("defaults a spanName condition's value to an empty string when none is provided", () => {+ const selector: AITelemetrySelector = {+ anyOf: [{ allOf: [{ target: "spanName", op: "in" }] }],+ };+ expect(spanMatchesAISelector(span({ name: "n" }), selector)).toBe(false);+ });++ it("defaults an 'eq' condition's value to an empty string when none is provided", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ {+ allOf: [+ { target: "attribute", scope: "resource", key: "empty.val", op: "eq" },+ ],+ },+ ],+ };+ expect(+ spanMatchesAISelector(+ span({ resourceAttributes: { "empty.val": "" } }),+ selector+ )+ ).toBe(true);+ expect(+ spanMatchesAISelector(+ span({ resourceAttributes: { "empty.val": "not-empty" } }),+ selector+ )+ ).toBe(false);+ });++ it("defaults an 'in' condition's value to an empty string when none is provided", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ {+ allOf: [+ { target: "attribute", scope: "resource", key: "empty.val", op: "in" },+ ],+ },+ ],+ };+ expect(+ spanMatchesAISelector(+ span({ resourceAttributes: { "empty.val": "" } }),+ selector+ )+ ).toBe(true);+ });++ it("returns false for an unsupported condition operator", () => {+ const selector: AITelemetrySelector = {+ anyOf: [+ {+ allOf: [+ {+ target: "attribute",+ scope: "span",+ key: "foo",+ op: "unsupported" as unknown as "exists",+ },+ ],+ },+ ],+ };+ expect(+ spanMatchesAISelector(span({ spanAttributes: { foo: "bar" } }), selector)+ ).toBe(false);+ });});describe("JaegerAdapter", () => {@@ -403,3 +567,908 @@ describe("JaegerAdapter", () => {expect(frame.rows).toHaveLength(0);});});++describe("JaegerAdapter extended coverage", () => {+ const descriptor: TelemetrySourceDescriptor = {+ type: "jaeger",+ id: "src-jaeger",+ isBuiltIn: false,+ settings: { url: "https://jaeger.example.com", services: ["svc"] },+ signals: ["traces"],+ name: "Jaeger",+ };+ const adapter = new JaegerAdapter(descriptor);++ const noConfigDescriptor: TelemetrySourceDescriptor = {+ type: "jaeger",+ id: "src-jaeger-noconfig",+ isBuiltIn: false,+ settings: { url: "https://jaeger.example.com" },+ signals: ["traces"],+ name: "Jaeger",+ };+ const noConfigAdapter = new JaegerAdapter(noConfigDescriptor);++ const aiTag = { key: "gen_ai.request.model", value: "gpt-4" };++ function traceFixture(opts: {+ traceId: string;+ spanId?: string;+ name?: string;+ startTime?: number;+ duration?: number;+ tags?: { key: string; value: string }[];+ references?: { refType: string; spanID: string }[];+ serviceName?: string;+ }) {+ return {+ traceID: opts.traceId,+ processes: { p1: { serviceName: opts.serviceName ?? "svc", tags: [] } },+ spans: [+ {+ traceID: opts.traceId,+ spanID: opts.spanId ?? "root",+ operationName: opts.name ?? "op",+ references: opts.references || [],+ startTime: opts.startTime ?? 1782864000000000,+ duration: opts.duration ?? 1000,+ processID: "p1",+ tags: opts.tags || [aiTag],+ },+ ],+ };+ }++ describe("pickRootSpan", () => {+ it("picks an orphaned reference as the trace root when no zero-parent span exists", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ traceFixture({+ traceId: "orphan",+ spanId: "child",+ references: [{ refType: "CHILD_OF", spanID: "missing-parent" }],+ }),+ ],+ });+ const frame = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(frame.rows[0]).toMatchObject({ spanId: "child", traceId: "orphan" });+ });++ it("falls back to the earliest-timestamp span when no explicit root exists", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ {+ traceID: "cyclic",+ processes: { p1: { serviceName: "svc", tags: [] } },+ spans: [+ {+ traceID: "cyclic",+ spanID: "a",+ operationName: "a-op",+ references: [{ refType: "CHILD_OF", spanID: "a" }],+ startTime: 1782864000100000,+ duration: 50,+ processID: "p1",+ tags: [aiTag],+ },+ {+ traceID: "cyclic",+ spanID: "b",+ operationName: "b-op",+ references: [{ refType: "CHILD_OF", spanID: "b" }],+ startTime: 1782864000000000,+ duration: 50,+ processID: "p1",+ tags: [aiTag],+ },+ ],+ },+ ],+ });+ const frame = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(frame.rows[0]?.spanId).toBe("b");+ });+ });++ describe("spanMatchesFilters", () => {+ it("keeps traces matching a spanName filter (scalar and array values)", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ traceFixture({ traceId: "chat", name: "chat" }),+ traceFixture({ traceId: "health", name: "GET /health" }),+ ],+ });+ const scalar = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "spanName", op: "eq", value: "chat" }],+ });+ expect(scalar.total).toBe(1);++ const array = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "spanName", op: "in", value: ["chat", "other"] }],+ });+ expect(array.total).toBe(1);+ });++ it("filters by span status (error vs ok, scalar and array values)", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ traceFixture({+ traceId: "err",+ tags: [{ key: "otel.status_code", value: "STATUS_CODE_ERROR" }],+ }),+ traceFixture({+ traceId: "ok",+ tags: [{ key: "otel.status_code", value: "STATUS_CODE_OK" }],+ }),+ ],+ });+ const errorOnly = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "status", op: "eq", value: "error" }],+ });+ expect(errorOnly.total).toBe(1);++ const okOnly = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "status", op: "eq", value: "ok" }],+ });+ expect(okOnly.total).toBe(1);++ const arrayValue = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "status", op: "in", value: ["error", "STATUS_CODE_ERROR"] }],+ });+ expect(arrayValue.total).toBe(1);+ });++ it("filters by attribute exists/eq/neq/in", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ traceFixture({ traceId: "has-attr", tags: [{ key: "custom.attr", value: "yes" }] }),+ traceFixture({ traceId: "no-attr", tags: [] }),+ ],+ });+ const exists = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "attribute", key: "custom.attr", op: "exists" }],+ });+ expect(exists.total).toBe(1);++ const eq = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "attribute", key: "custom.attr", op: "eq", value: "yes" }],+ });+ expect(eq.total).toBe(1);++ const neq = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "attribute", key: "custom.attr", op: "neq", value: "yes" }],+ });+ expect(neq.total).toBe(1);++ const inOp = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [+ { target: "attribute", key: "custom.attr", op: "in", value: ["yes", "maybe"] },+ ],+ });+ expect(inOp.total).toBe(1);++ // `in` with a single scalar (non-array) value still coerces to a list.+ const inScalar = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "attribute", key: "custom.attr", op: "in", value: "yes" }],+ });+ expect(inScalar.total).toBe(1);+ });++ it("keeps traces when a filter target is not spanName/status/attribute", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "any" })] });+ const result = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "duration", op: "gt", value: 100 }],+ });+ expect(result.total).toBe(1);+ });+ });++ describe("servicesFromFilters / operationFromFilters", () => {+ it("uses an explicit service.name filter instead of discovering services", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ expect(String(url)).not.toContain("/api/services");+ return { data: [traceFixture({ traceId: "custom", serviceName: "custom-svc" })] };+ });+ const result = await noConfigAdapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "attribute", key: "service.name", op: "eq", value: "custom-svc" }],+ });+ expect(result.total).toBe(1);+ const url = String(mockSafeFetch.mock.calls[0][0]);+ expect(url).toContain("service=custom-svc");+ });++ it("fans out over multiple service.name filter values (in)", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ expect(String(url)).not.toContain("/api/services");+ const service = new URL(String(url)).searchParams.get("service");+ return { data: [traceFixture({ traceId: `t-${service}`, serviceName: service || "" })] };+ });+ const result = await noConfigAdapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [+ {+ target: "attribute",+ key: "service.name",+ op: "in",+ value: ["svc-a", "svc-b"],+ },+ ],+ });+ expect(result.total).toBe(2);+ const services = mockSafeFetch.mock.calls.map((call) =>+ new URL(String(call[0])).searchParams.get("service")+ );+ expect(services.sort()).toEqual(["svc-a", "svc-b"]);+ });++ it("coerces a scalar service.name `in` filter value to a single-service list", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ expect(String(url)).not.toContain("/api/services");+ return { data: [traceFixture({ traceId: "single-in", serviceName: "svc-solo" })] };+ });+ const result = await noConfigAdapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [+ { target: "attribute", key: "service.name", op: "in", value: "svc-solo" },+ ],+ });+ expect(result.total).toBe(1);+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain("service=svc-solo");+ });++ it("maps a spanName filter onto Jaeger's single operation search param", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "op-test" })] });+ await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "spanName", op: "eq", value: "checkout" }],+ });+ const url = String(mockSafeFetch.mock.calls[0][0]);+ expect(url).toContain("operation=checkout");+ });++ it("uses the first spanName value from an array filter as the operation", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "op-test-2" })] });+ await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "spanName", op: "in", value: ["checkout", "other"] }],+ });+ const url = String(mockSafeFetch.mock.calls[0][0]);+ expect(url).toContain("operation=checkout");+ });+ });++ describe("healthCheck", () => {+ it("succeeds when Jaeger reports services", async () => {+ mockSafeFetch.mockResolvedValue({ data: ["svc-a", "svc-b"] });+ const result = await adapter.healthCheck();+ expect(result.ok).toBe(true);+ expect(typeof result.latencyMs).toBe("number");+ });++ it("fails when Jaeger reports no services", async () => {+ mockSafeFetch.mockResolvedValue({ data: [] });+ await expect(adapter.healthCheck()).resolves.toMatchObject({+ ok: false,+ message: "Jaeger returned no services",+ });+ });++ it("fails with the upstream status for a Jaeger HTTP error", async () => {+ const { SourceResponseError } = jest.requireMock(+ "@/lib/platform/connectors/datasource/http/safe-fetch"+ ) as { SourceResponseError: new (status: number, message: string) => Error };+ mockSafeFetch.mockRejectedValue(new SourceResponseError(503, "jaeger down"));+ const result = await adapter.healthCheck();+ expect(result.ok).toBe(false);+ expect(result.message).toContain("Jaeger request failed (503)");+ });++ it("fails with a generic error message for non-HTTP failures", async () => {+ mockSafeFetch.mockRejectedValue(new Error("network unreachable"));+ const result = await adapter.healthCheck();+ expect(result.ok).toBe(false);+ expect(result.message).toContain("network unreachable");+ });+ });++ describe("listServices", () => {+ it("discovers services from the Jaeger API when none are configured", async () => {+ mockSafeFetch.mockResolvedValue({ data: ["svc-x", "", "svc-y"] });+ const services = await noConfigAdapter.discoverServices(window);+ expect(services.map((s) => s.serviceName)).toEqual(["svc-x", "svc-y"]);+ expect(mockSafeFetch).toHaveBeenCalledTimes(1);+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain("/api/services");+ });+ });++ describe("misc small branches", () => {+ it("carries an explicit span.kind tag onto the normalized span", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ traceFixture({+ traceId: "kind-trace",+ tags: [aiTag, { key: "span.kind", value: "client" }],+ }),+ ],+ });+ const frame = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(frame.rows[0]).toMatchObject({ spanKind: "client" });+ });++ it("returns an empty span list when the trace lookup finds nothing", async () => {+ mockSafeFetch.mockResolvedValue({ data: [] });+ await expect(adapter.getTraceSpans("does-not-exist")).resolves.toEqual([]);+ });++ it("defaults sampleTracesForGraph's budget when maxTraces is falsy", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "default-budget" })] });+ const spans = await adapter.sampleTracesForGraph(+ { signal: "traces", timeRange: window, aiSelector: false },+ 0+ );+ expect(spans.some((s) => s.traceId === "default-budget")).toBe(true);+ });++ it("falls back to an empty base URL when no url setting is configured", async () => {+ const blankUrlDescriptor: TelemetrySourceDescriptor = {+ type: "jaeger",+ id: "src-jaeger-blank-url",+ isBuiltIn: false,+ settings: { services: ["svc"] },+ signals: ["traces"],+ name: "Jaeger",+ };+ const blankUrlAdapter = new JaegerAdapter(blankUrlDescriptor);+ const result = await blankUrlAdapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ // Invalid (empty) URL fails per-service, so the trace fetch degrades to zero results.+ expect(result.total).toBe(0);+ });++ it("treats a missing filter value as an empty string for spanName/attribute matchers", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [traceFixture({ traceId: "no-value", name: "" })],+ });+ const bySpanName = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "spanName", op: "eq" }],+ });+ expect(bySpanName.total).toBe(1);++ const byAttribute = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "attribute", key: "missing.attr", op: "eq" }],+ });+ // The attribute is absent, so an empty-string filter value still excludes it.+ expect(byAttribute.total).toBe(0);+ });+ });++ describe("more edge branches", () => {+ it("skips spans without a spanId when remembering them for getSpan", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ {+ traceID: "no-span-id",+ processes: { p1: { serviceName: "svc", tags: [] } },+ spans: [+ {+ traceID: "no-span-id",+ spanID: "",+ operationName: "anonymous",+ references: [],+ startTime: 1782864000000000,+ duration: 10,+ processID: "p1",+ tags: [aiTag],+ },+ ],+ },+ ],+ });+ await expect(adapter.getTraceSpans("no-span-id")).resolves.toEqual([+ expect.objectContaining({ spanId: "" }),+ ]);+ });++ it("skips traces with no spans and traces with a missing/duplicate traceID", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ { traceID: "empty-spans", processes: { p1: { serviceName: "svc", tags: [] } }, spans: [] },+ { traceID: "", processes: { p1: { serviceName: "svc", tags: [] } }, spans: [+ { traceID: "", spanID: "no-id-span", operationName: "op", references: [], startTime: 1782864000000000, duration: 10, processID: "p1", tags: [aiTag] },+ ] },+ traceFixture({ traceId: "dup", spanId: "dup-1" }),+ traceFixture({ traceId: "dup", spanId: "dup-2" }),+ ],+ });+ const frame = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ // Only the first occurrence of "dup" survives; empty-span/no-id traces are dropped.+ expect(frame.rows.map((r) => r.traceId).sort()).toEqual(["dup"]);+ });++ it("falls back to earliest-timestamp span when the sort comparator sees a missing timestamp", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ {+ traceID: "zero-ts",+ processes: { p1: { serviceName: "svc", tags: [] } },+ spans: [+ {+ traceID: "zero-ts", spanID: "x", operationName: "x-op",+ references: [{ refType: "CHILD_OF", spanID: "x" }],+ startTime: 5_000_000_000_000, duration: 10, processID: "p1", tags: [aiTag],+ },+ {+ traceID: "zero-ts", spanID: "y", operationName: "y-op",+ references: [{ refType: "CHILD_OF", spanID: "y" }],+ startTime: 0, duration: 10, processID: "p1", tags: [aiTag],+ },+ ],+ },+ ],+ });+ const frame = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(frame.rows[0]?.spanId).toBe("y");+ });++ it("treats a span with no status tag as non-error", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "no-status" })] });+ const result = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "status", op: "eq", value: "ok" }],+ });+ expect(result.total).toBe(1);+ });++ it("treats a missing filter value as empty for the neq/in attribute operators", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "no-value-2" })] });+ const neq = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "attribute", key: "missing.attr", op: "neq" }],+ });+ expect(neq.total).toBe(1);++ const inOp = await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "attribute", key: "missing.attr", op: "in" }],+ });+ expect(inOp.total).toBe(0);+ });++ it("resolves a scalar (non-array) spanName `in` filter value into an operation", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "op-scalar-in" })] });+ await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "spanName", op: "in", value: "checkout" }],+ });+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain("operation=checkout");+ });++ it("skips a blank leading value when resolving an operation from an array filter", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "op-blank-leading" })] });+ await adapter.countTraces({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ filters: [{ target: "spanName", op: "in", value: ["", "checkout"] }],+ });+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain("operation=checkout");+ });++ it("defaults the bucketing interval to 1h when the query does not request one", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "default-interval" })] });+ const frame = await adapter.traceTimeSeries({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(frame.meta?.freshness).toBe("sampled");+ });+ });++ describe("rememberSpans span index cap", () => {+ it("evicts the oldest indexed span once the per-source cap is reached", async () => {+ const evictDescriptor: TelemetrySourceDescriptor = {+ type: "jaeger",+ id: "src-jaeger-evict",+ isBuiltIn: false,+ settings: { url: "https://jaeger.example.com", services: ["svc"] },+ signals: ["traces"],+ name: "Jaeger",+ };+ const evictAdapter = new JaegerAdapter(evictDescriptor);+ const bigTrace = {+ traceID: "big",+ processes: { p1: { serviceName: "svc", tags: [] } },+ // One more span than SPAN_INDEX_MAX (5_000) so the index must evict.+ spans: Array.from({ length: 5_001 }, (_, i) => ({+ traceID: "big",+ spanID: `s${i}`,+ operationName: `op${i}`,+ references: [],+ startTime: 1782864000000000 + i,+ duration: 10,+ processID: "p1",+ tags: [],+ })),+ };+ mockSafeFetch.mockResolvedValue({ data: [bigTrace] });+ const spans = await evictAdapter.getTraceSpans("big");+ expect(spans).toHaveLength(5_001);+ // The most recently indexed span is still served straight from the index.+ expect(await evictAdapter.getSpan("s5000")).toMatchObject({ spanId: "s5000" });+ });+ });++ describe("startMs fallback for trace ordering", () => {+ it("scans span timestamps when the root span has no timestamp", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ {+ traceID: "no-ts-root",+ processes: { p1: { serviceName: "svc", tags: [] } },+ spans: [+ {+ traceID: "no-ts-root",+ spanID: "root",+ operationName: "op",+ references: [],+ startTime: 0,+ duration: 10,+ processID: "p1",+ tags: [aiTag],+ },+ ],+ },+ ],+ });+ const frame = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(frame.rows.map((r) => r.traceId)).toContain("no-ts-root");+ });+ });++ describe("collectTraces failure handling", () => {+ it("throttles a failing service for 30s so later calls skip refetching it", async () => {+ const flakyDescriptor: TelemetrySourceDescriptor = {+ type: "jaeger",+ id: "src-jaeger-flaky",+ isBuiltIn: false,+ settings: { url: "https://jaeger.example.com", services: ["flaky-svc"] },+ signals: ["traces"],+ name: "Jaeger",+ };+ const flakyAdapter = new JaegerAdapter(flakyDescriptor);+ const { SourceResponseError } = jest.requireMock(+ "@/lib/platform/connectors/datasource/http/safe-fetch"+ ) as { SourceResponseError: new (status: number, message: string) => Error };+ mockSafeFetch.mockRejectedValueOnce(new SourceResponseError(500, "boom"));++ const first = await flakyAdapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(first.rows).toHaveLength(0);+ expect(mockSafeFetch).toHaveBeenCalledTimes(1);++ mockSafeFetch.mockResolvedValue({+ data: [traceFixture({ traceId: "should-not-fetch" })],+ });+ const second = await flakyAdapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(second.rows).toHaveLength(0);+ // Still throttled: no additional fetch for the flaky service.+ expect(mockSafeFetch).toHaveBeenCalledTimes(1);+ });+ });++ describe("generation health filtering", () => {+ it("keeps only traces matching the requested generation-health chip", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ traceFixture({+ traceId: "truncated-trace",+ spanId: "trunc-span",+ name: "chat",+ tags: [+ aiTag,+ { key: "gen_ai.response.finish_reasons", value: "length" },+ ],+ }),+ traceFixture({+ traceId: "ok-trace",+ spanId: "ok-span",+ name: "chat",+ tags: [aiTag, { key: "gen_ai.response.finish_reasons", value: "stop" }],+ }),+ ],+ });+ const frame = await adapter.listSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ generationHealth: ["truncated"],+ });+ expect(frame.rows).toHaveLength(1);+ expect(frame.rows[0]).toMatchObject({+ traceId: "truncated-trace",+ spanId: "trunc-span",+ });+ });+ });++ describe("legacy collectSpans helper", () => {+ it("flattens collected traces and caps the span count", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "legacy" })] });+ const spans = await (+ adapter as unknown as {+ collectSpans: (q: unknown, n: number) => Promise<unknown[]>;+ }+ ).collectSpans({ signal: "traces", timeRange: window, aiSelector: false }, 10);+ expect(Array.isArray(spans)).toBe(true);+ expect(spans.length).toBeGreaterThan(0);+ });+ });++ describe("getSpan", () => {+ it("falls back to a recent trace scan when the span is not indexed yet", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [traceFixture({ traceId: "fresh-trace", spanId: "fresh-span-1" })],+ });+ const found = await adapter.getSpan("fresh-span-1");+ expect(found).toMatchObject({ spanId: "fresh-span-1", traceId: "fresh-trace" });+ });++ it("returns null when the span cannot be found anywhere", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [traceFixture({ traceId: "other", spanId: "other-span" })],+ });+ const found = await adapter.getSpan("totally-missing-span-id");+ expect(found).toBeNull();+ });+ });++ describe("sampleTracesForGraph / aggregateSpans / spanTimeSeries", () => {+ it("samples traces for the discovery graph", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "graph-trace" })] });+ const spans = await adapter.sampleTracesForGraph(+ { signal: "traces", timeRange: window, aiSelector: false },+ 50+ );+ expect(spans.some((s) => s.traceId === "graph-trace")).toBe(true);+ });++ it("aggregates spans via the L1 in-process aggregator", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "agg-trace" })] });+ const frame = await adapter.aggregateSpans({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ aggregations: [{ fn: "count" }],+ });+ expect(frame.rows.length).toBeGreaterThanOrEqual(1);+ expect(frame.meta?.degraded).toContain("serverAggregation");+ });++ it("spanTimeSeries delegates to traceTimeSeries", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "series-trace" })] });+ const frame = await adapter.spanTimeSeries({+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ interval: "1d",+ });+ expect(frame.meta?.freshness).toBe("sampled");+ });+ });++ describe("distinctValues", () => {+ it("falls back to L1 sampling when the operations endpoint fails for every service", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/operations")) {+ throw new Error("operations endpoint down");+ }+ return { data: [traceFixture({ traceId: "fallback-trace", name: "fallback-op" })] };+ });+ const names = await adapter.distinctValues("SpanName", {+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(names).toContain("fallback-op");+ });++ it("resolves service.name distinct values from configured services", async () => {+ const names = await adapter.distinctValues("ServiceName", {+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(names).toEqual(["svc"]);+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("falls back to L1 sampling for arbitrary attribute keys", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ traceFixture({+ traceId: "attr-trace",+ tags: [{ key: "custom.attr", value: "hello" }],+ }),+ ],+ });+ const values = await adapter.distinctValues("custom.attr", {+ signal: "traces",+ timeRange: window,+ aiSelector: false,+ });+ expect(values).toEqual(["hello"]);+ });+ });++ describe("attributeKeys", () => {+ it("collects unique span and resource attribute keys", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ traceFixture({+ traceId: "keys-trace",+ tags: [aiTag, { key: "custom.attr", value: "x" }],+ }),+ ],+ });+ const keys = await adapter.attributeKeys("traces", window);+ expect(keys).toEqual(+ expect.arrayContaining(["gen_ai.request.model", "custom.attr", "service.name"])+ );+ });+ });++ describe("discoverServices / aggregateByService", () => {+ it("maps configured services into discovered service rows", async () => {+ const services = await adapter.discoverServices(window);+ expect(services).toEqual([{ serviceName: "svc", environment: "", clusterId: "" }]);+ });++ it("aggregates model/provider rollups per discovered service", async () => {+ mockSafeFetch.mockResolvedValue({+ data: [+ traceFixture({+ traceId: "rollup-trace",+ tags: [aiTag, { key: "gen_ai.system", value: "openai" }],+ }),+ ],+ });+ const rollups = await adapter.aggregateByService(window);+ expect(rollups).toEqual([+ {+ serviceName: "svc",+ environment: "default",+ clusterId: "default",+ requestCount: 1,+ models: ["gpt-4"],+ providers: ["openai"],+ },+ ]);+ });+ });++ describe("validateAISignal", () => {+ it("succeeds when AI-relevant traces are found", async () => {+ mockSafeFetch.mockResolvedValue({ data: [traceFixture({ traceId: "ai-trace" })] });+ const result = await adapter.validateAISignal(window);+ expect(result).toMatchObject({ ok: true, sampleCount: 1, missingAttributes: [] });+ });++ it("reports a failure message when service discovery throws", async () => {+ mockSafeFetch.mockRejectedValue(new Error("services down"));+ const result = await noConfigAdapter.validateAISignal(window);+ expect(result.ok).toBe(false);+ expect(result.sampleCount).toBe(0);+ expect(result.message).toContain("services down");+ });+ });++ describe("jaegerAdapterFactory", () => {+ it("creates an adapter instance and describes the source type", async () => {+ const { jaegerAdapterFactory } = await import(+ "@/lib/platform/connectors/datasource/jaeger/adapter"+ );+ expect(jaegerAdapterFactory.type).toBe("jaeger");+ const created = jaegerAdapterFactory.create(descriptor);+ expect(created).toBeInstanceOf(JaegerAdapter);+ const described = jaegerAdapterFactory.describe();+ expect(described).toMatchObject({+ type: "jaeger",+ displayName: "Jaeger",+ declaredSignals: ["traces"],+ });+ });+ });+});diff --git a/src/client/src/__tests__/lib/platform/datasource/l1-query-planner.test.ts b/src/client/src/__tests__/lib/platform/datasource/l1-query-planner.test.tsindex ec221709..f81a92e7 100644--- a/src/client/src/__tests__/lib/platform/datasource/l1-query-planner.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/l1-query-planner.test.ts@@ -9,11 +9,13 @@ import {import { fetchSpansForAggregation } from "@/lib/platform/connectors/datasource/graph/sample-fetch";import {computeAggregateSpansL1,+ computeDistinctValuesL1,computeSpanTimeSeriesL1,} from "@/lib/platform/connectors/datasource/l1-compute";import {intervalFromTimeRange,planAndAggregateSpans,+ planAndDistinctValues,planAndSpanTimeSeries,} from "@/lib/platform/connectors/datasource/query-planner";import { __clearCache } from "@/lib/platform/connectors/datasource/http/cache";@@ -201,6 +203,15 @@ describe("sample-aggregate", () => {expect(frame.rows).toEqual([{ n: 3 }]);});+ it("aggregateSpansInProcess defaults groupBy to [] when undefined", () => {+ const frame = aggregateSpansInProcess(+ spans,+ undefined as unknown as string[],+ [{ fn: "count", as: "n" }]+ );+ expect(frame.rows).toEqual([{ n: 3 }]);+ });+it("distinctFromSpans returns sorted unique values", () => {expect(distinctFromSpans(spans, "gen_ai.request.model")).toEqual(["gpt-3.5",@@ -208,6 +219,305 @@ describe("sample-aggregate", () => {]);});+ it("distinctFromSpans skips spans where the field is undefined or empty", () => {+ const mixed = [+ span({ spanId: "a", spanAttributes: {} }),+ span({ spanId: "b", spanAttributes: { tag: "" } }),+ span({ spanId: "c", spanAttributes: { tag: "value" } }),+ ];+ expect(distinctFromSpans(mixed, "tag")).toEqual(["value"]);+ });++ it("spanFieldValue resolves span:/resource: scoped attributes", () => {+ const s = span({+ spanId: "a",+ spanAttributes: { custom: "span-value" },+ resourceAttributes: { custom: "resource-value" },+ });+ expect(spanFieldValue(s, "span:custom")).toBe("span-value");+ expect(spanFieldValue(s, "resource:custom")).toBe("resource-value");+ });++ it("spanFieldValue returns undefined for a blank field", () => {+ expect(spanFieldValue(span({ spanId: "a" }), " ")).toBeUndefined();+ });++ it("spanFieldValue prefers span.cost over attributes when numeric", () => {+ const s = span({+ spanId: "a",+ cost: 9.5,+ spanAttributes: { "gen_ai.usage.cost": "1" },+ });+ expect(spanFieldValue(s, "cost")).toBe(9.5);+ });++ it("spanFieldValue resolves cost via the raw attribute constant key", () => {+ const s = span({+ spanId: "a",+ spanAttributes: { "gen_ai.usage.cost": "3.5" },+ });+ expect(spanFieldValue(s, "gen_ai.usage.cost")).toBe(3.5);+ });++ it("spanFieldValue falls back through lookupAttr cost keys and resource attrs", () => {+ const s = span({+ spanId: "a",+ spanAttributes: { "coding_agent.session.cost_usd": "2.25" },+ });+ expect(spanFieldValue(s, "cost")).toBe(2.25);++ const resourceOnly = span({+ spanId: "b",+ resourceAttributes: { cost: "7" },+ });+ expect(spanFieldValue(resourceOnly, "cost")).toBe(7);+ });++ it("spanFieldValue returns undefined cost when nothing parses to a number", () => {+ const s = span({ spanId: "a", spanAttributes: {} });+ expect(spanFieldValue(s, "cost")).toBeUndefined();+ });++ it("spanFieldValue resolves tokens via the raw attribute constant key", () => {+ const s = span({+ spanId: "a",+ spanAttributes: { total_tokens: "42" },+ });+ expect(spanFieldValue(s, "total_tokens")).toBe(42);+ });++ it("spanFieldValue defaults duration to 0 when durationNs is falsy", () => {+ const s = span({ spanId: "a", durationNs: 0 });+ expect(spanFieldValue(s, "duration")).toBe(0);+ });++ it("spanFieldValue falls back to resourceAttributes for tokens when no attribute key matches", () => {+ const s = span({+ spanId: "a",+ spanAttributes: {},+ resourceAttributes: { tokens: "17" },+ });+ expect(spanFieldValue(s, "tokens")).toBe(17);+ });++ it("spanFieldValue resolves StatusCode/statusCode", () => {+ const s = span({ spanId: "a", statusCode: "STATUS_CODE_ERROR" });+ expect(spanFieldValue(s, "StatusCode")).toBe("STATUS_CODE_ERROR");+ expect(spanFieldValue(s, "statusCode")).toBe("STATUS_CODE_ERROR");+ });++ it("spanFieldValue resolves durationNs, ParentSpanId, TraceId, SpanId", () => {+ const s = span({+ spanId: "sid",+ traceId: "tid",+ parentSpanId: "pid",+ durationNs: 42,+ });+ expect(spanFieldValue(s, "durationNs")).toBe(42);+ expect(spanFieldValue(s, "ParentSpanId")).toBe("pid");+ expect(spanFieldValue(s, "TraceId")).toBe("tid");+ expect(spanFieldValue(s, "SpanId")).toBe("sid");+ });++ it("spanFieldValue falls back to raw span/resource attributes for unknown fields", () => {+ const s = span({+ spanId: "a",+ spanAttributes: { "custom.attr": "span-attr-value" },+ resourceAttributes: { "custom.resource.attr": "resource-attr-value" },+ });+ expect(spanFieldValue(s, "custom.attr")).toBe("span-attr-value");+ expect(spanFieldValue(s, "custom.resource.attr")).toBe(+ "resource-attr-value"+ );+ expect(spanFieldValue(s, "totally.unknown")).toBeUndefined();+ });++ it("applyAggregation supports cardinality, min/max/avg/p90/p95/p99, and unknown fns", () => {+ const spansForAgg = [+ span({ spanId: "1", spanAttributes: { "gen_ai.usage.cost": "1" } }),+ span({ spanId: "2", spanAttributes: { "gen_ai.usage.cost": "2" } }),+ span({ spanId: "3", spanAttributes: { "gen_ai.usage.cost": "3" } }),+ span({ spanId: "4", spanAttributes: { "gen_ai.request.model": "gpt-4" } }),+ ];++ const cardinality = aggregateSpansInProcess(+ spansForAgg,+ [],+ [{ fn: "cardinality", field: "gen_ai.request.model", as: "distinctModels" }]+ );+ expect(cardinality.rows[0]).toEqual({ distinctModels: 1 });++ const stats = aggregateSpansInProcess(+ spansForAgg,+ [],+ [+ { fn: "min", field: "cost", as: "min" },+ { fn: "max", field: "cost", as: "max" },+ { fn: "avg", field: "cost", as: "avg" },+ { fn: "p90", field: "cost", as: "p90" },+ { fn: "p95", field: "cost", as: "p95" },+ { fn: "p99", field: "cost", as: "p99" },+ { fn: "unknown" as unknown as "sum", field: "cost", as: "unknownFn" },+ ]+ );+ expect(stats.rows[0]).toMatchObject({+ min: 1,+ max: 3,+ avg: 2,+ unknownFn: 0,+ });+ });++ it("applyAggregation cardinality ignores undefined/empty field values", () => {+ const spansForAgg = [+ span({ spanId: "1", spanAttributes: {} }),+ span({ spanId: "2", spanAttributes: { tag: "" } }),+ ];+ const result = aggregateSpansInProcess(+ spansForAgg,+ [],+ [{ fn: "cardinality", field: "tag", as: "n" }]+ );+ expect(result.rows[0]).toEqual({ n: 0 });+ });++ it("applyAggregation cardinality defaults to an empty field when none is given", () => {+ const spansForAgg = [span({ spanId: "1" })];+ const result = aggregateSpansInProcess(+ spansForAgg,+ [],+ [{ fn: "cardinality", as: "n" }]+ );+ expect(result.rows[0]).toEqual({ n: 0 });+ });++ it("applyAggregation returns 0 for numeric aggregations with no numeric values", () => {+ const spansForAgg = [span({ spanId: "1", spanAttributes: {} })];+ const result = aggregateSpansInProcess(+ spansForAgg,+ [],+ [{ fn: "sum", field: "cost", as: "sum" }]+ );+ expect(result.rows[0]).toEqual({ sum: 0 });+ });++ it("applyAggregation returns 0 for sum/avg without a field (collectFieldNumbers short-circuits)", () => {+ const spansForAgg = [span({ spanId: "1" })];+ const result = aggregateSpansInProcess(+ spansForAgg,+ [],+ [{ fn: "sum", as: "sum" }]+ );+ expect(result.rows[0]).toEqual({ sum: 0 });+ });++ it("applyAggregations falls back to a default count aggregation for an explicitly empty list", () => {+ const spansForAgg = [span({ spanId: "1" }), span({ spanId: "2" })];+ const result = aggregateSpansInProcess(spansForAgg, [], []);+ expect(result.rows[0]).toEqual({ agg0: 2 });+ });++ it("aggAlias/safeGroupKey reject prototype-polluting or invalid identifiers", () => {+ const spansForAgg = [+ span({ spanId: "1", spanAttributes: { "gen_ai.request.model": "gpt-4" } }),+ ];+ const result = aggregateSpansInProcess(+ spansForAgg,+ ["__proto__"],+ [{ fn: "count", as: "__proto__" }]+ );+ expect(Object.keys(result.rows[0] as object)).toEqual(+ expect.arrayContaining(["agg0", "group_value", "group0"])+ );+ });++ it("bucketSpansByInterval treats an empty interval string as the 1h default", () => {+ const frame = bucketSpansByInterval(+ [span({ spanId: "1", timestamp: "2026-07-11T10:30:00.000Z" })],+ "",+ [{ fn: "count", as: "n" }]+ );+ expect(frame.rows[0]).toMatchObject({ label: "07/11 10:00" });+ });++ it("bucketSpansByInterval skips spans with a missing or unparsable timestamp", () => {+ const noTimestamp = { ...span({ spanId: "1" }), timestamp: "" };+ const badTimestamp = span({ spanId: "2", timestamp: "not-a-date" });+ const frame = bucketSpansByInterval(+ [noTimestamp, badTimestamp],+ "1h",+ [{ fn: "count", as: "n" }]+ );+ expect(frame.rows).toEqual([]);+ });++ it("bucketSpansByInterval formats month buckets and defaults unknown intervals to hourly", () => {+ const monthFrame = bucketSpansByInterval(+ [span({ spanId: "1", timestamp: "2026-03-15T10:00:00.000Z" })],+ "1M",+ [{ fn: "count", as: "n" }]+ );+ expect(monthFrame.rows[0]).toMatchObject({+ bucket: "2026-03-01T00:00:00.000Z",+ label: "2026/03",+ });++ const defaultFrame = bucketSpansByInterval(+ [span({ spanId: "1", timestamp: "2026-03-15T10:30:00.000Z" })],+ "not-a-real-interval",+ [{ fn: "count", as: "n" }]+ );+ expect(defaultFrame.rows[0]).toMatchObject({+ label: "03/15 10:00",+ });+ });++ it("bucketSpansByInterval zero-fills minute buckets across a short window", () => {+ const frame = bucketSpansByInterval(+ [span({ spanId: "1", timestamp: "2026-07-11T10:01:00.000Z" })],+ "1m",+ [{ fn: "count", as: "n" }],+ {+ start: new Date("2026-07-11T10:00:00.000Z"),+ end: new Date("2026-07-11T10:02:00.000Z"),+ }+ );+ expect(frame.rows).toHaveLength(3);+ expect(frame.rows.map((r) => (r as { n: number }).n)).toEqual([0, 1, 0]);+ });++ it("bucketSpansByInterval zero-fills day buckets across a short window", () => {+ const frame = bucketSpansByInterval(+ [span({ spanId: "1", timestamp: "2026-07-12T10:00:00.000Z" })],+ "1d",+ [{ fn: "count", as: "n" }],+ {+ start: new Date("2026-07-11T00:00:00.000Z"),+ end: new Date("2026-07-13T00:00:00.000Z"),+ }+ );+ expect(frame.rows).toHaveLength(3);+ expect(frame.rows.map((r) => (r as { n: number }).n)).toEqual([0, 1, 0]);+ });++ it("bucketSpansByInterval zero-fills across calendar months", () => {+ const frame = bucketSpansByInterval(+ [span({ spanId: "1", timestamp: "2026-03-15T10:00:00.000Z" })],+ "1M",+ [{ fn: "count", as: "n" }],+ {+ start: new Date("2026-01-01T00:00:00.000Z"),+ end: new Date("2026-03-01T00:00:00.000Z"),+ }+ );+ expect(frame.rows).toHaveLength(3);+ expect(frame.rows.map((r) => (r as { n: number }).n)).toEqual([0, 0, 1]);+ });++ it("looksLikeRootsOnly returns false for an empty span list", () => {+ expect(looksLikeRootsOnly([])).toBe(false);+ });+it("looksLikeRootsOnly detects one root per trace", () => {expect(looksLikeRootsOnly([@@ -372,6 +682,43 @@ describe("l1-compute", () => {expect(nonEmpty).toMatchObject({ total: 1 });expect(ts.rows.length).toBeGreaterThan(1);});++ it("defaults groupBy/aggregations/interval when the query omits them", async () => {+ const spans = [span({ spanId: "1" }), span({ spanId: "2", traceId: "t2" })];+ const source = { sampleTracesForGraph: async () => spans };++ const agg = await computeAggregateSpansL1(source, windowQuery);+ expect(agg.rows).toEqual([{ agg0: 2 }]);++ const ts = await computeSpanTimeSeriesL1(source, windowQuery);+ expect(ts.rows.length).toBeGreaterThan(0);+ });++ it("computeDistinctValuesL1 samples spans and returns distinct field values", async () => {+ const spans = [+ span({+ spanId: "1",+ spanAttributes: { "gen_ai.request.model": "gpt-4" },+ }),+ span({+ spanId: "2",+ spanAttributes: { "gen_ai.request.model": "gpt-3.5" },+ }),+ span({+ spanId: "3",+ spanAttributes: { "gen_ai.request.model": "gpt-4" },+ }),+ ];+ const source = {+ sampleTracesForGraph: async () => spans,+ };+ const values = await computeDistinctValuesL1(+ source,+ "gen_ai.request.model",+ windowQuery+ );+ expect(values).toEqual(["gpt-3.5", "gpt-4"]);+ });});describe("query-planner", () => {@@ -388,6 +735,12 @@ describe("query-planner", () => {new Date("2026-07-10T00:00:00.000Z"))).toBe("1d");+ expect(+ intervalFromTimeRange(+ new Date("2023-01-01T00:00:00.000Z"),+ new Date("2026-07-11T00:00:00.000Z")+ )+ ).toBe("1M");});it("preferRollup uses readRollup when present", async () => {@@ -466,4 +819,162 @@ describe("query-planner", () => {const frame = await planAndAggregateSpans(adapter, windowQuery);expect(frame.rows).toEqual([{ native: true }]);});++ it("treats a throwing capabilities() as no server aggregation", async () => {+ const adapter = {+ capabilities: () => {+ throw new Error("capabilities unavailable");+ },+ aggregateSpans: async () => ({ fields: [], rows: [{ native: true }] }),+ } as unknown as DataSourceAdapter;++ const frame = await planAndAggregateSpans(adapter, windowQuery);+ expect(frame.rows).toEqual([{ native: true }]);+ });++ it("ignores a rollup read failure and falls through to the native adapter call", async () => {+ const adapter = {+ aggregateSpans: async () => ({ fields: [], rows: [{ native: true }] }),+ } as unknown as DataSourceAdapter;++ const frame = await planAndAggregateSpans(adapter, windowQuery, {+ preferRollup: true,+ readRollup: async () => {+ throw new Error("rollup store unavailable");+ },+ });+ expect(frame.rows).toEqual([{ native: true }]);+ expect(frame.meta?.degraded ?? []).not.toContain("rollup");+ });++ it("falls through to the native adapter call when readRollup resolves to null (rollup miss)", async () => {+ const adapter = {+ aggregateSpans: async () => ({ fields: [], rows: [{ native: true }] }),+ } as unknown as DataSourceAdapter;++ const frame = await planAndAggregateSpans(adapter, windowQuery, {+ preferRollup: true,+ readRollup: async () => null,+ });+ expect(frame.rows).toEqual([{ native: true }]);+ expect(frame.meta?.degraded ?? []).not.toContain("rollup");+ });++ it("planAndAggregateSpans rethrows non-UnsupportedCapabilityError failures", async () => {+ const adapter = {+ aggregateSpans: async () => {+ throw new Error("boom");+ },+ } as unknown as DataSourceAdapter;++ await expect(planAndAggregateSpans(adapter, windowQuery)).rejects.toThrow(+ "boom"+ );+ });++ it("planAndSpanTimeSeries uses native adapter method when serverAggregation is true", async () => {+ const adapter = {+ capabilities: (): SourceCapabilities => ({+ signals: ["traces"],+ traceTree: true,+ spanEvents: true,+ serverAggregation: true,+ spanMutation: false,+ distinctValues: true,+ crossTraceSession: false,+ rawQuery: false,+ }),+ spanTimeSeries: async () => ({+ fields: [],+ rows: [{ native: true }],+ }),+ } as unknown as DataSourceAdapter;++ const frame = await planAndSpanTimeSeries(adapter, windowQuery);+ expect(frame.rows).toEqual([{ native: true }]);+ expect(frame.meta?.freshness).toBe("live");+ });++ it("planAndSpanTimeSeries uses readRollup when preferRollup is set", async () => {+ const frame = await planAndSpanTimeSeries(+ {} as DataSourceAdapter,+ windowQuery,+ {+ preferRollup: true,+ readRollup: async () => ({+ fields: [],+ rows: [{ n: 9 }],+ }),+ }+ );+ expect(frame.rows).toEqual([{ n: 9 }]);+ expect(frame.meta?.degraded).toContain("rollup");+ });++ it("planAndSpanTimeSeries ignores a rollup read failure and falls through to native", async () => {+ const adapter = {+ spanTimeSeries: async () => ({ fields: [], rows: [{ native: true }] }),+ } as unknown as DataSourceAdapter;++ const frame = await planAndSpanTimeSeries(adapter, windowQuery, {+ preferRollup: true,+ readRollup: async () => {+ throw new Error("rollup store unavailable");+ },+ });+ expect(frame.rows).toEqual([{ native: true }]);+ });++ it("planAndSpanTimeSeries rethrows non-UnsupportedCapabilityError failures", async () => {+ const adapter = {+ spanTimeSeries: async () => {+ throw new Error("boom");+ },+ } as unknown as DataSourceAdapter;++ await expect(planAndSpanTimeSeries(adapter, windowQuery)).rejects.toThrow(+ "boom"+ );+ });++ it("planAndDistinctValues returns the adapter's native result when it succeeds", async () => {+ const adapter = {+ distinctValues: async () => ["a", "b"],+ } as unknown as DataSourceAdapter;++ const values = await planAndDistinctValues(adapter, "service.name", windowQuery);+ expect(values).toEqual(["a", "b"]);+ });++ it("planAndDistinctValues falls back to L1 sampling on UnsupportedCapabilityError", async () => {+ const spans = [+ span({ spanId: "1", spanAttributes: { "gen_ai.request.model": "gpt-4" } }),+ span({ spanId: "2", spanAttributes: { "gen_ai.request.model": "gpt-3.5" } }),+ ];+ const adapter = {+ distinctValues: async () => {+ throw new UnsupportedCapabilityError("tempo", "distinctValues");+ },+ sampleTracesForGraph: async () => spans,+ } as unknown as DataSourceAdapter;++ const values = await planAndDistinctValues(+ adapter,+ "gen_ai.request.model",+ windowQuery+ );+ expect(values).toEqual(["gpt-3.5", "gpt-4"]);+ });++ it("planAndDistinctValues rethrows non-UnsupportedCapabilityError failures", async () => {+ const adapter = {+ distinctValues: async () => {+ throw new Error("boom");+ },+ } as unknown as DataSourceAdapter;++ await expect(+ planAndDistinctValues(adapter, "service.name", windowQuery)+ ).rejects.toThrow("boom");+ });});diff --git a/src/client/src/__tests__/lib/platform/datasource/limits.test.ts b/src/client/src/__tests__/lib/platform/datasource/limits.test.tsindex 5d403032..ac5b8d46 100644--- a/src/client/src/__tests__/lib/platform/datasource/limits.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/limits.test.ts@@ -7,6 +7,7 @@ import {withRetry,defaultIsRetryable,__resetConcurrencyForTests,+ queryBudgetForSource,} from "@/lib/platform/connectors/datasource/http/limits";import type { OpenLITQuery } from "@/lib/platform/connectors/datasource/types";import { SourceResponseError } from "@/lib/platform/connectors/datasource/http/safe-fetch";@@ -98,6 +99,29 @@ describe("clampQueryBudget", () => {});});+describe("queryBudgetForSource", () => {+ it("applies the source's maxLookbackMs when maxTimeRangeMs is absent", () => {+ const maxLookbackMs = 3 * 24 * 60 * 60 * 1000;+ const source = { capabilities: () => ({ maxLookbackMs }) };+ const budget = queryBudgetForSource(source);+ expect(budget.maxLookbackMs).toBe(maxLookbackMs);+ expect(budget.maxRangeMs).toBe(DEFAULT_QUERY_BUDGET.maxRangeMs);+ });++ it("falls back to the base budget when capabilities() throws", () => {+ const source = {+ capabilities: () => {+ throw new Error("capabilities unavailable");+ },+ };+ expect(queryBudgetForSource(source)).toEqual(DEFAULT_QUERY_BUDGET);+ });++ it("falls back to the base budget when the source has no capabilities method", () => {+ expect(queryBudgetForSource({})).toEqual(DEFAULT_QUERY_BUDGET);+ });+});+describe("Semaphore", () => {it("caps concurrent holders and releases in order", async () => {const sem = new Semaphore(2);@@ -146,6 +170,12 @@ describe("defaultIsRetryable", () => {expect(defaultIsRetryable(new Error("fetch failed"))).toBe(true);expect(defaultIsRetryable(new Error("bad request"))).toBe(false);});++ it("treats an error without a message as non-retryable", () => {+ expect(defaultIsRetryable(new Error())).toBe(false);+ expect(defaultIsRetryable(undefined)).toBe(false);+ expect(defaultIsRetryable("plain string")).toBe(false);+ });});describe("withRetry", () => {@@ -190,4 +220,9 @@ describe("withRetry", () => {).rejects.toBeInstanceOf(SourceResponseError);expect(calls).toBe(3);});++ it("uses default retries/backoff/sleep when no options are provided", async () => {+ const result = await withRetry(async () => "ok");+ expect(result).toBe("ok");+ });});diff --git a/src/client/src/__tests__/lib/platform/datasource/loki-prometheus.test.ts b/src/client/src/__tests__/lib/platform/datasource/loki-prometheus.test.tsindex 184f1b90..94f025a0 100644--- a/src/client/src/__tests__/lib/platform/datasource/loki-prometheus.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/loki-prometheus.test.ts@@ -1,4 +1,8 @@const mockSafeFetch = jest.fn();+const mockSelfHostedNetworkOptions = jest.fn((..._args: unknown[]) => ({+ allowHttp: true,+ allowPrivateNetwork: true,+}));jest.mock("@/lib/platform/connectors/datasource/http/safe-fetch", () => ({safeFetch: (...args: unknown[]) => mockSafeFetch(...args),@@ -9,7 +13,8 @@ jest.mock("@/lib/platform/connectors/datasource/http/safe-fetch", () => ({this.status = status;}},- selfHostedNetworkOptions: () => ({ allowHttp: true, allowPrivateNetwork: true }),+ selfHostedNetworkOptions: (...args: unknown[]) =>+ mockSelfHostedNetworkOptions(...args),}));jest.mock("@/lib/platform/connectors/datasource/http/secret", () => ({resolveSourceSecret: jest.fn().mockResolvedValue({ raw: "", credentials: {} }),@@ -17,6 +22,14 @@ jest.mock("@/lib/platform/connectors/datasource/http/secret", () => ({}));jest.mock("@/utils/log", () => ({ consoleLog: jest.fn() }));+const mockResolveDescriptor = jest.fn();+const mockGetAdapter = jest.fn();+jest.mock("@/lib/telemetry-source", () => ({+ resolveTelemetrySourceDescriptor: (...a: unknown[]) =>+ mockResolveDescriptor(...a),+ getTelemetryAdapter: (...a: unknown[]) => mockGetAdapter(...a),+}));+import {LokiAdapter,__resetLokiLearningForTests,@@ -25,7 +38,13 @@ import {} from "@/lib/platform/connectors/datasource/grafana/loki";import { PrometheusAdapter, prometheusSelector } from "@/lib/platform/connectors/datasource/prometheus/adapter";import type { TelemetrySourceDescriptor } from "@/lib/platform/connectors/datasource/types";-import { facadeErrorMessage } from "@/lib/platform/connectors/datasource/facade";+import { UnsupportedCapabilityError } from "@/lib/platform/connectors/datasource/types";+import {+ facadeErrorMessage,+ resolveSignalReadContext,+ rethrowIfSourceFailure,+} from "@/lib/platform/connectors/datasource/facade";+import { SourceResponseError } from "@/lib/platform/connectors/datasource/http/safe-fetch";import { AdapterError } from "@openplait/adapter-sdk";const window = {@@ -50,6 +69,11 @@ function descriptor(beforeEach(() => {mockSafeFetch.mockReset();+ mockSelfHostedNetworkOptions.mockReset();+ mockSelfHostedNetworkOptions.mockReturnValue({+ allowHttp: true,+ allowPrivateNetwork: true,+ });__resetLokiLearningForTests();});@@ -152,6 +176,522 @@ describe("OpenPlait Loki integration", () => {});});+describe("LokiAdapter: session-2 branch coverage", () => {+ it("evicts the oldest indexed log once the process-wide log index is full", async () => {+ const LOG_INDEX_MAX = 5_000;+ const values: [string, string][] = [];+ for (let i = 0; i <= LOG_INDEX_MAX; i++) {+ // Unique nanosecond timestamps -> distinct logStableRowId per row.+ values.push([`${1785888000000000000 + i}`, `line-${i}`]);+ }+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: {+ resultType: "streams",+ result: [{ stream: { service_name: "checkout" }, values }],+ },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ // `limit` stays within Loki's maxResultRows cap; the mocked response+ // still returns every row regardless of the requested query limit.+ const frame = await adapter.listLogs({ signal: "logs", timeRange: window });+ expect(frame.rows).toHaveLength(LOG_INDEX_MAX + 1);+ const { logStableRowId } = await import(+ "@/lib/platform/connectors/datasource/clickhouse/normalize"+ );+ const oldestId = logStableRowId(frame.rows[0]);+ const newestId = logStableRowId(frame.rows[frame.rows.length - 1]);+ mockSafeFetch.mockClear();+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ // Evicted -> falls through to a live Loki scan (empty result -> null).+ expect(await adapter.getLog(oldestId)).toBeNull();+ expect(mockSafeFetch).toHaveBeenCalled();+ mockSafeFetch.mockClear();+ // The newest row is still warm in the index -> resolved with no HTTP call.+ const recent = await adapter.getLog(newestId);+ expect(recent?.body).toBe(`line-${LOG_INDEX_MAX}`);+ expect(mockSafeFetch).not.toHaveBeenCalled();+ }, 20_000);++ it("builds a `contains` LogQL regex matcher for an attribute filter (escapeRegex)", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await adapter.listLogs({+ signal: "logs",+ timeRange: window,+ filters: [+ { target: "attribute", key: "service.name", op: "contains", value: ["check.out"] },+ ],+ });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("query")).toBe(+ '{service_name=~".*check\\\\.out.*"}'+ );+ });++ it("labelName sanitizes an unmapped, non-identifier attribute key into a safe LogQL label", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await adapter.listLogs({+ signal: "logs",+ timeRange: window,+ filters: [{ target: "attribute", key: "http.route", op: "eq", value: "/api" }],+ });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("query")).toBe('{http_route="/api"}');+ });++ it("translates a spanName filter and a body/message attribute filter into LogQL line filters", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await adapter.listLogs({+ signal: "logs",+ timeRange: window,+ filters: [+ { target: "spanName", op: "eq", value: ["chat"] },+ { target: "attribute", key: "message", op: "neq", value: "noisy" },+ ],+ });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ const query = url.searchParams.get("query") || "";+ expect(query).toContain('|= "chat"');+ expect(query).toContain('!= "noisy"');+ });++ it("skips a filter with no target/key/value contribution to the LogQL selector", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await adapter.listLogs({+ signal: "logs",+ timeRange: window,+ filters: [+ { target: "duration", op: "gt", value: 100 },+ { target: "attribute", key: "service.name", op: "eq", value: [] },+ ],+ });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ // Neither filter contributes a label -> falls back to the default selector.+ expect(url.searchParams.get("query")).toBe('{service_name=~".+"}');+ });++ it("uses a negative (!=) matcher for a single-value neq attribute filter", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await adapter.listLogs({+ signal: "logs",+ timeRange: window,+ filters: [{ target: "attribute", key: "service.name", op: "neq", value: "checkout" }],+ });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("query")).toBe('{service_name!="checkout"}');+ });++ it("builds a negative (!~) regex-OR label matcher for a multi-value notIn filter", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await adapter.listLogs({+ signal: "logs",+ timeRange: window,+ filters: [+ { target: "attribute", key: "service.name", op: "notIn", value: ["a", "b"] },+ ],+ });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("query")).toBe('{service_name!~"a|b"}');+ });++ it("builds a multi-value 'in' filter as a LogQL regex-OR label matcher", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await adapter.listLogs({+ signal: "logs",+ timeRange: window,+ filters: [+ { target: "attribute", key: "service.name", op: "in", value: ["a", "b"] },+ ],+ });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("query")).toBe('{service_name=~"a|b"}');+ });++ it("uses the configured default selector fallback ('{service_name=~\".+\"}') when no filters contribute labels", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await adapter.listLogs({ signal: "logs", timeRange: window });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("query")).toBe('{service_name=~".+"}');+ });++ it("uses a configured custom defaultSelector when it's a well-formed '{...}' LogQL matcher", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(+ descriptor("loki", "http://loki:3100", { defaultSelector: '{app="checkout"}' })+ );+ await adapter.listLogs({ signal: "logs", timeRange: window });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("query")).toBe('{app="checkout"}');+ });++ it("requests forward direction when the query sorts by timestamp ascending", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await adapter.listLogs({+ signal: "logs",+ timeRange: window,+ sort: [{ field: "timestamp", direction: "asc" }],+ });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("direction")).toBe("forward");+ });++ it("defaults to a blank body string for an empty log line", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: {+ resultType: "streams",+ result: [+ { stream: { service_name: "checkout" }, values: [["1785888000000000000", ""]] },+ ],+ },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ const frame = await adapter.listLogs({ signal: "logs", timeRange: window });+ expect(frame.rows[0]).toMatchObject({ body: "" });+ });++ it("getLog returns null immediately for a blank log id without querying Loki", async () => {+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await expect(adapter.getLog("")).resolves.toBeNull();+ await expect(adapter.getLog(" ")).resolves.toBeNull();+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("withRangeRetry's adapterErrorBody returns '' for a non-Error rejection (not AdapterError/SourceResponseError/Error)", async () => {+ // logTimeSeries calls the guarded fetch directly (bypassing OpenPlait's+ // requestJson, which would otherwise wrap any rejection in an+ // AdapterError) — a non-SourceResponseError rejection is rethrown as-is.+ mockSafeFetch.mockRejectedValueOnce("plain rejection reason");+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await expect(+ adapter.logTimeSeries({ signal: "logs", timeRange: window })+ ).rejects.toBe("plain rejection reason");+ });++ it("logTimeSeries tolerates a response with no matrix result and a series with no values", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "matrix" }, // no `result` field at all+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ const frame = await adapter.logTimeSeries({ signal: "logs", timeRange: window });+ expect(frame.rows).toEqual([]);++ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "matrix", result: [{}] }, // series with no `values` field+ });+ const frame2 = await adapter.logTimeSeries({ signal: "logs", timeRange: window });+ expect(frame2.rows).toEqual([]);+ });++ it("parseLokiDurationMs returns undefined for an unparsable duration string", () => {+ expect(parseLokiDurationMs("not-a-duration")).toBeUndefined();+ expect(parseLokiDurationMs("")).toBeUndefined();+ });++ it("learns Loki max query length from an AdapterError (listLogs path) and retries with the narrowed range", async () => {+ mockSafeFetch+ .mockRejectedValueOnce(+ new SourceResponseError(+ 400,+ "Data source responded 400: the query time range exceeds the limit (query length: 40d, limit: 7d)"+ )+ )+ .mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(+ descriptor("loki", "http://loki:3100", {+ maxTimeRangeMs: 40 * 24 * 60 * 60 * 1_000,+ })+ );+ const frame = await adapter.listLogs({+ signal: "logs",+ timeRange: {+ start: new Date("2026-06-01T00:00:00Z"),+ end: new Date("2026-08-07T00:00:00Z"),+ },+ });+ expect(frame.rows).toEqual([]);+ expect(mockSafeFetch).toHaveBeenCalledTimes(2);+ });++ it("withRangeRetry rethrows a generic error carrying a bare numeric `.status` property (not AdapterError/SourceResponseError)", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "matrix", result: [] },+ });+ const weird = Object.assign(new Error("weird upstream failure"), { status: 400 });+ mockSafeFetch.mockReset();+ mockSafeFetch.mockRejectedValueOnce(weird);+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await expect(+ adapter.logTimeSeries({ signal: "logs", timeRange: window })+ ).rejects.toThrow("weird upstream failure");+ });++ it("withRangeRetry rethrows a plain error with no recognizable status when the range/limit can't be learned", async () => {+ mockSafeFetch.mockRejectedValueOnce(new Error("network unreachable"));+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await expect(+ adapter.logTimeSeries({ signal: "logs", timeRange: window })+ ).rejects.toThrow("network unreachable");+ });++ it("clampTimeRange leaves an invalid (end before start) range untouched rather than clamping it", async () => {+ mockSafeFetch.mockResolvedValueOnce({ status: "success", data: [] });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ const inverted = {+ start: new Date("2026-08-05T02:00:00Z"),+ end: new Date("2026-08-05T01:00:00Z"),+ };+ await adapter.attributeKeys("logs", inverted);+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("start")).toBe(`${inverted.start.getTime()}000000`);+ expect(url.searchParams.get("end")).toBe(`${inverted.end.getTime()}000000`);+ });++ it("configuredMaxTimeRangeMs / maxQueryRangeMs fall back to the 30d1h default when no setting or learned limit exists", () => {+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ expect(adapter.capabilities().maxTimeRangeMs).toBe(30 * 24 * 60 * 60 * 1_000);+ });++ it("ignores a non-positive/invalid configured maxTimeRangeMs setting", () => {+ const adapter = new LokiAdapter(+ descriptor("loki", "http://loki:3100", { maxTimeRangeMs: -5 })+ );+ expect(adapter.capabilities().maxTimeRangeMs).toBe(30 * 24 * 60 * 60 * 1_000);+ });++ it("advertises the full Loki capabilities object, including maxLookbackMs from settings", () => {+ const adapter = new LokiAdapter(+ descriptor("loki", "http://loki:3100", { maxLookbackMs: 3_600_000 })+ );+ expect(adapter.capabilities()).toMatchObject({+ signals: ["logs"],+ traceTree: false,+ spanEvents: false,+ serverAggregation: true,+ spanMutation: false,+ distinctValues: true,+ crossTraceSession: false,+ rawQuery: false,+ maxLookbackMs: 3_600_000,+ });+ });++ it("healthCheck succeeds when Loki reports label names", async () => {+ mockSafeFetch.mockResolvedValueOnce({ status: "success", data: ["service_name", "level"] });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ const result = await adapter.healthCheck();+ expect(result.ok).toBe(true);+ expect(typeof result.latencyMs).toBe("number");+ });++ it("healthCheck reports failure with the upstream error message when labelNames fails", async () => {+ mockSafeFetch.mockRejectedValueOnce(new SourceResponseError(500, "loki unreachable"));+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ const result = await adapter.healthCheck();+ expect(result.ok).toBe(false);+ expect(result.message).toContain("500");+ });++ it("getLog uses an explicit opts.timeRange window instead of the default lookback", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ const explicitRange = {+ start: new Date("2026-01-01T00:00:00Z"),+ end: new Date("2026-01-02T00:00:00Z"),+ };+ const result = await adapter.getLog("missing-id", { timeRange: explicitRange });+ expect(result).toBeNull();+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("start")).toBe(`${explicitRange.start.getTime()}000000`);+ });++ it("getLog centers the search window around a valid opts.aroundTimestamp", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ const around = new Date("2026-05-01T12:00:00Z");+ await adapter.getLog("missing-id", { aroundTimestamp: around });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ const startMs = Number(url.searchParams.get("start")) / 1_000_000;+ const endMs = Number(url.searchParams.get("end")) / 1_000_000;+ expect(around.getTime() - startMs).toBe(60 * 60 * 1_000);+ expect(endMs - around.getTime()).toBe(60 * 60 * 1_000);+ });++ it("getLog falls back to the default lookback window when opts.aroundTimestamp is unparsable", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: { resultType: "streams", result: [] },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ const result = await adapter.getLog("missing-id", { aroundTimestamp: "not-a-date" });+ expect(result).toBeNull();+ expect(mockSafeFetch).toHaveBeenCalled();+ });++ it("normalizes a log stream that only has a bare 'service' label and no trace/span/level labels", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: {+ resultType: "streams",+ result: [+ {+ stream: { service: "legacy-svc" },+ values: [["1785888000000000000", "plain line"]],+ },+ ],+ },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ const frame = await adapter.listLogs({ signal: "logs", timeRange: window });+ expect(frame.rows[0]).toMatchObject({+ body: "plain line",+ serviceName: "legacy-svc",+ traceId: undefined,+ spanId: undefined,+ severityText: undefined,+ });+ });++ it("logTimeSeries skips non-finite sample timestamps and defaults a non-numeric sample value to 0", async () => {+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: {+ resultType: "matrix",+ result: [+ {+ values: [+ ["not-a-number", "3"],+ [String(window.start.getTime() / 1000), "not-a-number"],+ ],+ },+ ],+ },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ const frame = await adapter.logTimeSeries({ signal: "logs", timeRange: window });+ expect(frame.rows).toHaveLength(1);+ expect((frame.rows[0] as any).count).toBe(0);+ });++ it("logTimeSeries treats a nanosecond-scale sample timestamp as already-in-nanoseconds (not seconds)", async () => {+ const nsTimestamp = window.start.getTime() * 1_000_000; // well above the 10^13 threshold+ mockSafeFetch.mockResolvedValueOnce({+ status: "success",+ data: {+ resultType: "matrix",+ result: [{ values: [[nsTimestamp, "5"]] }],+ },+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ const frame = await adapter.logTimeSeries({ signal: "logs", timeRange: window });+ expect(frame.rows[0]).toMatchObject({+ timestamp: new Date(window.start.getTime()).toISOString(),+ count: 5,+ });+ });++ it("attributeKeys returns an empty list for a non-logs signal without fetching", async () => {+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await expect(adapter.attributeKeys("metrics" as any, window)).resolves.toEqual([]);+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("ignores a non-array label-values payload instead of throwing", async () => {+ mockSafeFetch.mockResolvedValueOnce({ status: "success", data: "not-an-array" });+ const adapter = new LokiAdapter(descriptor("loki", "http://loki:3100"));+ await expect(+ adapter.distinctValues("service.name", { signal: "logs", timeRange: window })+ ).resolves.toEqual([]);+ });++ it("baseUrl defaults to an empty string when no url setting is configured", () => {+ const adapter = new LokiAdapter(descriptor("loki", ""));+ expect((adapter as unknown as { baseUrl: string }).baseUrl).toBe("");+ });++ it("baseUrl skips the Docker loopback rewrite when private-network access is disallowed", () => {+ mockSelfHostedNetworkOptions.mockReturnValue({+ allowHttp: true,+ allowPrivateNetwork: false,+ });+ const adapter = new LokiAdapter(descriptor("loki", "http://localhost:3100"));+ expect((adapter as unknown as { baseUrl: string }).baseUrl).toBe(+ "http://localhost:3100"+ );+ });++ it("lokiAdapterFactory.describe() advertises Loki's capabilities and config fields", async () => {+ const { lokiAdapterFactory } = await import(+ "@/lib/platform/connectors/datasource/grafana/loki"+ );+ const info = lokiAdapterFactory.describe();+ expect(info.type).toBe("loki");+ expect(info.declaredSignals).toEqual(["logs"]);+ expect(info.capabilities).toMatchObject({+ serverAggregation: true,+ distinctValues: true,+ rawQuery: false,+ });+ expect(info.configFields.some((f) => f.key === "defaultSelector")).toBe(true);+ expect(info.configFields.some((f) => f.key === "maxTimeRangeMs")).toBe(true);+ expect(info.correlation).toMatchObject({ crossSignal: true });+ });+});+describe("Loki duration parsing", () => {it("parses Loki limit durations and error bodies", () => {expect(parseLokiDurationMs("30d1h")).toBe(30 * 24 * 60 * 60 * 1_000 + 60 * 60 * 1_000);@@ -174,28 +714,145 @@ describe("facadeErrorMessage", () => {});expect(facadeErrorMessage(error)).toContain("limit: 30d1h");});++ it("returns the UnsupportedCapabilityError message as-is", () => {+ const error = new UnsupportedCapabilityError("tempo", "spanMutation");+ expect(facadeErrorMessage(error)).toBe(error.message);+ });++ it("returns the AdapterError message unchanged when the message is not an HTTP-status message", () => {+ const error = new AdapterError("EXECUTION_FAILED", "Loki query rejected.", {+ details: { status: 400, body: "the query time range exceeds the limit" },+ });+ expect(facadeErrorMessage(error)).toBe("Loki query rejected.");+ });++ it("returns the AdapterError message unchanged when there is no upstream body", () => {+ const error = new AdapterError("EXECUTION_FAILED", "Tempo returned HTTP 500.", {+ details: { status: 500 },+ });+ expect(facadeErrorMessage(error)).toBe("Tempo returned HTTP 500.");+ });++ it("returns the AdapterError message unchanged when the upstream body is blank", () => {+ const error = new AdapterError("EXECUTION_FAILED", "Tempo returned HTTP 500.", {+ details: { status: 500, body: " " },+ });+ expect(facadeErrorMessage(error)).toBe("Tempo returned HTTP 500.");+ });++ it("returns a plain Error message", () => {+ expect(facadeErrorMessage(new Error("boom"))).toBe("boom");+ });++ it("returns a raw string error as-is", () => {+ expect(facadeErrorMessage("plain string failure")).toBe("plain string failure");+ });++ it("falls back to the generic widget-run-failed message for non-Error, non-string values", () => {+ expect(facadeErrorMessage({ weird: true })).toMatch(/failed/i);+ expect(facadeErrorMessage(undefined)).toMatch(/failed/i);+ });});describe("rethrowIfSourceFailure", () => {it("rethrows AdapterError", () => {- const { rethrowIfSourceFailure } = require("@/lib/platform/connectors/datasource/facade");const error = new AdapterError("EXECUTION_FAILED", "down");expect(() => rethrowIfSourceFailure(error)).toThrow(AdapterError);});+ it("does not rethrow UnsupportedCapabilityError (capability gaps stay soft)", () => {+ expect(() =>+ rethrowIfSourceFailure(new UnsupportedCapabilityError("tempo", "spanMutation"))+ ).not.toThrow();+ });++ it("rethrows SourceResponseError", () => {+ expect(() =>+ rethrowIfSourceFailure(new SourceResponseError(503, "unavailable"))+ ).toThrow(SourceResponseError);+ });+it("rethrows connection-like errors", () => {- const { rethrowIfSourceFailure } = require("@/lib/platform/connectors/datasource/facade");expect(() =>rethrowIfSourceFailure(new Error("fetch failed"))).toThrow("fetch failed");});+ it.each([+ "ECONNREFUSED",+ "ENOTFOUND",+ "ETIMEDOUT",+ "ECONNRESET",+ "socket hang up",+ "network error",+ "connection refused",+ "connection timed out",+ "connect reset",+ ])("rethrows connection-like error message %p", (message) => {+ expect(() => rethrowIfSourceFailure(new Error(message))).toThrow(message);+ });+it("does not rethrow unrelated errors", () => {- const { rethrowIfSourceFailure } = require("@/lib/platform/connectors/datasource/facade");expect(() =>rethrowIfSourceFailure(new Error("span not found"))).not.toThrow();});++ it("does not rethrow non-Error values", () => {+ expect(() => rethrowIfSourceFailure("plain string")).not.toThrow();+ expect(() => rethrowIfSourceFailure(undefined)).not.toThrow();+ });+});++describe("resolveSignalReadContext", () => {+ beforeEach(() => {+ mockResolveDescriptor.mockReset();+ mockGetAdapter.mockReset();+ });++ it("marks the context built-in when the descriptor is built-in", async () => {+ const descriptor = { id: "d1", type: "clickhouse", isBuiltIn: true, name: "Built-in" };+ mockResolveDescriptor.mockResolvedValue(descriptor);+ const adapter = { id: "adapter" };+ mockGetAdapter.mockResolvedValue(adapter);++ const ctx = await resolveSignalReadContext("traces", { sourceId: "s1" });++ expect(ctx.adapter).toBe(adapter);+ expect(ctx.descriptor).toBe(descriptor);+ expect(ctx.isBuiltIn).toBe(true);+ expect(mockResolveDescriptor).toHaveBeenCalledWith({+ signal: "traces",+ sourceId: "s1",+ });+ expect(mockGetAdapter).toHaveBeenCalledWith({+ signal: "traces",+ sourceId: "s1",+ descriptor,+ });+ });++ it("marks the context built-in when descriptor.type is clickhouse even if isBuiltIn is false", () => {+ const descriptor = { id: "d2", type: "clickhouse", isBuiltIn: false, name: "CH" };+ mockResolveDescriptor.mockResolvedValue(descriptor);+ mockGetAdapter.mockResolvedValue({});++ return resolveSignalReadContext("logs").then((ctx) => {+ expect(ctx.isBuiltIn).toBe(true);+ });+ });++ it("marks the context as non-built-in for external adapters", async () => {+ const descriptor = { id: "d3", type: "loki", isBuiltIn: false, name: "Loki" };+ mockResolveDescriptor.mockResolvedValue(descriptor);+ mockGetAdapter.mockResolvedValue({});++ const ctx = await resolveSignalReadContext("logs", { environment: "prod" });++ expect(ctx.isBuiltIn).toBe(false);+ expect(ctx.descriptor).toBe(descriptor);+ });});describe("Loki discovery", () => {@@ -418,3 +1075,248 @@ describe("OpenPlait Prometheus integration", () => {).rejects.toMatchObject({ status: 502 });});});++describe("PrometheusAdapter extended coverage", () => {+ it("sanitizes a label key with regex metacharacters into a safe PromQL label name", () => {+ expect(+ prometheusSelector({+ signal: "metrics",+ timeRange: window,+ filters: [+ { target: "attribute", key: "http.route", op: "eq", value: "/api" },+ ],+ })+ ).toBe('{__name__=~".+",http_route="/api"}');+ });++ it("builds a `contains` PromQL regex matcher", () => {+ expect(+ prometheusSelector({+ signal: "metrics",+ timeRange: window,+ filters: [+ { target: "attribute", key: "service.name", op: "contains", value: ["check.out"] },+ ],+ })+ ).toBe('{__name__=~".+",service_name=~".*check\\\\.out.*"}');+ });++ it("adds a default __name__ matcher when no spanName/metric.name filter is present", () => {+ expect(+ prometheusSelector({+ signal: "metrics",+ timeRange: window,+ filters: [+ { target: "attribute", key: "service.name", op: "eq", value: "checkout" },+ ],+ })+ ).toBe('{__name__=~".+",service_name="checkout"}');+ });++ it("healthCheck succeeds when Prometheus reports label names", async () => {+ mockSafeFetch.mockResolvedValue({ status: "success", data: ["__name__", "job"] });+ const adapter = new PrometheusAdapter(descriptor("prometheus", "http://prometheus:9090"));+ const result = await adapter.healthCheck();+ expect(result.ok).toBe(true);+ expect(typeof result.latencyMs).toBe("number");+ });++ it("healthCheck fails with the upstream error message", async () => {+ const { SourceResponseError } = jest.requireMock(+ "@/lib/platform/connectors/datasource/http/safe-fetch"+ ) as { SourceResponseError: new (status: number, message: string) => Error };+ mockSafeFetch.mockRejectedValue(new SourceResponseError(500, "prometheus unreachable"));+ const adapter = new PrometheusAdapter(descriptor("prometheus", "http://prometheus:9090"));+ const result = await adapter.healthCheck();+ expect(result.ok).toBe(false);+ expect(result.message).toBeTruthy();+ });++ it("groups a sum/avg/min/max/count aggregation by the requested labels", async () => {+ mockSafeFetch.mockResolvedValue({+ status: "success",+ data: { resultType: "matrix", result: [] },+ });+ const adapter = new PrometheusAdapter(descriptor("prometheus", "http://prometheus:9090"));+ await adapter.metricTimeSeries({+ signal: "metrics",+ timeRange: window,+ filters: [{ target: "spanName", op: "eq", value: "http_requests_total" }],+ groupBy: ["service.name"],+ aggregations: [{ fn: "sum" }],+ });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("query")).toBe(+ 'sum by (service_name) ({__name__="http_requests_total"})'+ );+ });++ it("builds a rate() aggregation over the computed interval", async () => {+ mockSafeFetch.mockResolvedValue({+ status: "success",+ data: { resultType: "matrix", result: [] },+ });+ const adapter = new PrometheusAdapter(descriptor("prometheus", "http://prometheus:9090"));+ await adapter.metricTimeSeries({+ signal: "metrics",+ timeRange: window,+ filters: [{ target: "spanName", op: "eq", value: "http_requests_total" }],+ aggregations: [{ fn: "count", field: "rate" }],+ });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("query")).toContain("sum (rate(");+ });++ it("builds a rate() aggregation grouped by the requested labels", async () => {+ mockSafeFetch.mockResolvedValue({+ status: "success",+ data: { resultType: "matrix", result: [] },+ });+ const adapter = new PrometheusAdapter(descriptor("prometheus", "http://prometheus:9090"));+ await adapter.metricTimeSeries({+ signal: "metrics",+ timeRange: window,+ filters: [{ target: "spanName", op: "eq", value: "http_requests_total" }],+ groupBy: ["service.name"],+ aggregations: [{ fn: "count", field: "rate" }],+ });+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.searchParams.get("query")).toContain("sum by (service_name) (rate(");+ });++ it("returns metric names via the __name__ label values endpoint", async () => {+ mockSafeFetch.mockResolvedValue({+ status: "success",+ data: ["up", "http_requests_total"],+ });+ const adapter = new PrometheusAdapter(descriptor("prometheus", "http://prometheus:9090"));+ const names = await adapter.metricNames(window);+ expect(names).toEqual(["up", "http_requests_total"]);+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.pathname).toBe("/api/v1/label/__name__/values");+ });++ it("attributeKeys returns an empty list for non-metrics signals without fetching", async () => {+ const adapter = new PrometheusAdapter(descriptor("prometheus", "http://prometheus:9090"));+ await expect(adapter.attributeKeys("logs", window)).resolves.toEqual([]);+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("attributeKeys discovers all Prometheus label names for the metrics signal", async () => {+ mockSafeFetch.mockResolvedValue({+ status: "success",+ data: ["__name__", "job", "service_name"],+ });+ const adapter = new PrometheusAdapter(descriptor("prometheus", "http://prometheus:9090"));+ const keys = await adapter.attributeKeys("metrics", window);+ expect(keys).toEqual(["__name__", "job", "service_name"]);+ const url = new URL(mockSafeFetch.mock.calls[0][0]);+ expect(url.pathname).toBe("/api/v1/labels");+ expect(url.searchParams.get("start")).toBe(+ String(Math.floor(window.start.getTime() / 1000))+ );+ expect(url.searchParams.get("end")).toBe(String(Math.ceil(window.end.getTime() / 1000)));+ });++ it("fails loud when the Prometheus /labels endpoint returns an upstream error", async () => {+ const { SourceResponseError } = jest.requireMock(+ "@/lib/platform/connectors/datasource/http/safe-fetch"+ ) as { SourceResponseError: new (status: number, message: string) => Error };+ mockSafeFetch.mockRejectedValue(new SourceResponseError(504, "prom labels down"));+ const adapter = new PrometheusAdapter(descriptor("prometheus", "http://prometheus:9090"));+ await expect(adapter.attributeKeys("metrics", window)).rejects.toMatchObject({+ status: 504,+ });+ });++ it("ignores non-string entries in a Prometheus label response", async () => {+ mockSafeFetch.mockResolvedValue({ status: "success", data: "not-an-array" });+ const adapter = new PrometheusAdapter(descriptor("prometheus", "http://prometheus:9090"));+ await expect(adapter.attributeKeys("metrics", window)).resolves.toEqual([]);+ });++ it("ignores non-string entries in a Prometheus label VALUES response", async () => {+ mockSafeFetch.mockResolvedValue({ status: "success", data: ["ok", 42, null, "also-ok"] });+ const adapter = new PrometheusAdapter(descriptor("prometheus", "http://prometheus:9090"));+ const values = await adapter.distinctValues("job", { signal: "metrics", timeRange: window });+ expect(values).toEqual(["ok", "also-ok"]);+ });++ it("drops an empty-value filter from the PromQL selector", () => {+ expect(+ prometheusSelector({+ signal: "metrics",+ timeRange: window,+ filters: [{ target: "attribute", key: "service.name", op: "eq", value: [] }],+ })+ ).toBe('{__name__=~".+"}');+ });++ it("uses a negative (!=) matcher for a single-value neq filter", () => {+ expect(+ prometheusSelector({+ signal: "metrics",+ timeRange: window,+ filters: [{ target: "attribute", key: "service.name", op: "neq", value: "checkout" }],+ })+ ).toBe('{__name__=~".+",service_name!="checkout"}');+ });++ it("forces a single-value notIn filter through the negative regex matcher", () => {+ expect(+ prometheusSelector({+ signal: "metrics",+ timeRange: window,+ filters: [{ target: "attribute", key: "service.name", op: "notIn", value: "checkout" }],+ })+ ).toBe('{__name__=~".+",service_name!~"checkout"}');+ });++ it("skips non-attribute filters and attribute filters without a key", () => {+ expect(+ prometheusSelector({+ signal: "metrics",+ timeRange: window,+ filters: [+ { target: "duration", op: "gt", value: 100 },+ { target: "attribute", op: "eq", value: "x" },+ ],+ })+ ).toBe('{__name__=~".+"}');+ });++ it("defaults to an empty filter list when the query has none", () => {+ expect(+ prometheusSelector({ signal: "metrics", timeRange: window })+ ).toBe('{__name__=~".+"}');+ });++ it("falls back to the `service` label and the operation name when metric labels are sparse", async () => {+ mockSafeFetch.mockResolvedValue({+ status: "success",+ data: {+ resultType: "matrix",+ result: [{ metric: { service: "checkout-legacy" }, values: [[1785888000, "1"]] }],+ },+ });+ const adapter = new PrometheusAdapter(descriptor("prometheus", "http://prometheus:9090"));+ const frame = await adapter.listMetricSeries({ signal: "metrics", timeRange: window });+ expect(frame.rows[0]).toMatchObject({+ metricName: "metric-list",+ serviceName: "checkout-legacy",+ });+ });++ it("honors configured maxTimeRangeMs/maxLookbackMs in the advertised capabilities", () => {+ const adapter = new PrometheusAdapter(+ descriptor("prometheus", "http://prometheus:9090", {+ maxTimeRangeMs: 3_600_000,+ maxLookbackMs: 7_200_000,+ })+ );+ expect(adapter.capabilities()).toMatchObject({+ maxTimeRangeMs: 3_600_000,+ maxLookbackMs: 7_200_000,+ });+ });+});diff --git a/src/client/src/__tests__/lib/platform/datasource/normalize.test.ts b/src/client/src/__tests__/lib/platform/datasource/normalize.test.tsnew file mode 100644index 00000000..92768084--- /dev/null+++ b/src/client/src/__tests__/lib/platform/datasource/normalize.test.ts@@ -0,0 +1,434 @@+import {+ denormalizeLogToClickHouseRow,+ denormalizeMetricPointsToListRows,+ denormalizeSpanToTraceRow,+ logStableRowId,+ normalizeLogRow,+ normalizeMetricRow,+ normalizeSpanRow,+} from "@/lib/platform/connectors/datasource/clickhouse/normalize";+import type {+ NormalizedLog,+ NormalizedMetricPoint,+ NormalizedSpan,+} from "@/lib/platform/connectors/datasource/types";++describe("normalizeSpanRow", () => {+ it("normalizes the array-of-objects Events form and prefers a top-level Cost column", () => {+ const span = normalizeSpanRow({+ TraceId: "t1",+ SpanId: "s1",+ ParentSpanId: "p1",+ SpanName: "chat",+ ServiceName: "svc",+ Timestamp: "2026-07-01T00:00:00Z",+ Duration: 1000,+ StatusCode: "STATUS_CODE_OK",+ StatusMessage: "ok",+ SpanKind: "SPAN_KIND_CLIENT",+ Cost: "0.5",+ SpanAttributes: { "gen_ai.usage.cost": "9.99" },+ ResourceAttributes: { "service.name": "svc" },+ Events: [{ Name: "ev1", Timestamp: "2026-07-01T00:00:01Z", Attributes: { a: "b" } }],+ });+ expect(span).toMatchObject({+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "p1",+ name: "chat",+ serviceName: "svc",+ statusMessage: "ok",+ spanKind: "SPAN_KIND_CLIENT",+ cost: 0.5,+ });+ expect(span.events).toEqual([+ { name: "ev1", timestamp: "2026-07-01T00:00:01Z", attributes: { a: "b" } },+ ]);+ });++ it("falls back to the gen_ai.usage.cost span attribute when Cost is absent", () => {+ const span = normalizeSpanRow({+ TraceId: "t1",+ SpanId: "s1",+ SpanAttributes: { "gen_ai.usage.cost": "1.25" },+ });+ expect(span.cost).toBe(1.25);+ });++ it("leaves cost undefined when neither Cost nor the attribute is present", () => {+ const span = normalizeSpanRow({ TraceId: "t1", SpanId: "s1" });+ expect(span.cost).toBeUndefined();+ expect(span.statusMessage).toBeUndefined();+ expect(span.spanKind).toBeUndefined();+ });++ it("normalizes the parallel-arrays Events form (Events.Name/.Timestamp/.Attributes)", () => {+ const span = normalizeSpanRow({+ TraceId: "t1",+ SpanId: "s1",+ "Events.Name": ["ev1", "ev2"],+ "Events.Timestamp": ["2026-07-01T00:00:01Z", ""],+ "Events.Attributes": [{ a: "1" }, undefined],+ });+ expect(span.events).toEqual([+ { name: "ev1", timestamp: "2026-07-01T00:00:01Z", attributes: { a: "1" } },+ { name: "ev2", timestamp: undefined, attributes: {} },+ ]);+ });++ it("treats a null entry in the array-of-objects Events form as an empty event", () => {+ const span = normalizeSpanRow({+ TraceId: "t1",+ SpanId: "s1",+ Events: [null],+ });+ expect(span.events).toEqual([{ name: "", timestamp: undefined, attributes: {} }]);+ });++ it("defaults events to [] when neither Events form is present", () => {+ const span = normalizeSpanRow({ TraceId: "t1", SpanId: "s1" });+ expect(span.events).toEqual([]);+ });++ it("treats a falsy Event.Timestamp (array-of-objects form) as undefined", () => {+ const span = normalizeSpanRow({+ TraceId: "t1",+ SpanId: "s1",+ Events: [{ Name: "ev1", Timestamp: "", Attributes: {} }],+ });+ expect(span.events?.[0].timestamp).toBeUndefined();+ });++ it("defaults Events.Timestamp/.Attributes to [] when only Events.Name is present (parallel-arrays form)", () => {+ const span = normalizeSpanRow({+ TraceId: "t1",+ SpanId: "s1",+ "Events.Name": ["ev1"],+ });+ expect(span.events).toEqual([+ { name: "ev1", timestamp: undefined, attributes: {} },+ ]);+ });+});++describe("denormalizeSpanToTraceRow", () => {+ it("defaults optional fields (ParentSpanId, StatusMessage, SpanKind) and skips overwriting an explicit cost attribute", () => {+ const span: NormalizedSpan = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "svc",+ timestamp: "2026-07-01T00:00:00Z",+ durationNs: 100,+ statusCode: "STATUS_CODE_OK",+ spanAttributes: { "gen_ai.usage.cost": "already-set" },+ resourceAttributes: {},+ cost: 5,+ };+ const row = denormalizeSpanToTraceRow(span);+ expect(row).toMatchObject({+ ParentSpanId: "",+ StatusMessage: "",+ SpanKind: "",+ Links: [],+ });+ expect((row.SpanAttributes as Record<string, string>)["gen_ai.usage.cost"]).toBe(+ "already-set"+ );+ });++ it("defaults events to [] when the span has none, and falls back Timestamp/Attributes per event", () => {+ const span: NormalizedSpan = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "svc",+ timestamp: "2026-07-01T00:00:00Z",+ durationNs: 100,+ statusCode: "STATUS_CODE_OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ const row = denormalizeSpanToTraceRow(span);+ expect(row.Events).toEqual([]);+ expect(row.ResourceAttributes).toEqual({});+ });++ it("defaults ResourceAttributes to {} when the span carries none", () => {+ const span: NormalizedSpan = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "svc",+ timestamp: "2026-07-01T00:00:00Z",+ durationNs: 100,+ statusCode: "STATUS_CODE_OK",+ spanAttributes: {},+ resourceAttributes: undefined as unknown as Record<string, string>,+ events: [+ {+ name: "ev1",+ timestamp: undefined,+ attributes: undefined as unknown as Record<string, string>,+ },+ ],+ };+ const row = denormalizeSpanToTraceRow(span);+ expect(row.ResourceAttributes).toEqual({});+ expect((row.Events as Array<Record<string, unknown>>)[0]).toMatchObject({+ Timestamp: "",+ Attributes: {},+ });+ });+});++describe("logStableRowId", () => {+ it("is deterministic for identical inputs and differs when a field changes", () => {+ const a = logStableRowId({+ timestamp: "2026-07-01T00:00:00Z",+ traceId: "t1",+ spanId: "s1",+ severityText: "ERROR",+ body: "boom",+ });+ const b = logStableRowId({+ timestamp: "2026-07-01T00:00:00Z",+ traceId: "t1",+ spanId: "s1",+ severityText: "ERROR",+ body: "boom",+ });+ const c = logStableRowId({+ timestamp: "2026-07-01T00:00:00Z",+ traceId: "t1",+ spanId: "s1",+ severityText: "ERROR",+ body: "different",+ });+ expect(a).toBe(b);+ expect(a).not.toBe(c);+ });++ it("handles missing optional identifying fields", () => {+ const id = logStableRowId({+ timestamp: "2026-07-01T00:00:00Z",+ traceId: undefined,+ spanId: undefined,+ severityText: undefined,+ body: "boom",+ });+ expect(typeof id).toBe("string");+ expect(id.length).toBeGreaterThan(0);+ });+});++describe("denormalizeLogToClickHouseRow", () => {+ it("defaults optional fields when absent from the NormalizedLog", () => {+ const log: NormalizedLog = {+ timestamp: "2026-07-01T00:00:00Z",+ body: "boom",+ logAttributes: {},+ resourceAttributes: {},+ };+ const row = denormalizeLogToClickHouseRow(log);+ expect(row).toMatchObject({+ TraceId: "",+ SpanId: "",+ SeverityText: "",+ SeverityNumber: 0,+ ServiceName: "",+ ScopeName: "",+ ScopeVersion: "",+ LogAttributes: {},+ ResourceAttributes: {},+ ScopeAttributes: {},+ });+ });++ it("uses the provided scopeAttributes when present", () => {+ const log: NormalizedLog = {+ timestamp: "2026-07-01T00:00:00Z",+ body: "boom",+ logAttributes: {},+ resourceAttributes: {},+ scopeAttributes: { "scope.name": "my-lib" },+ };+ const row = denormalizeLogToClickHouseRow(log);+ expect(row.ScopeAttributes).toEqual({ "scope.name": "my-lib" });+ });++ it("defaults logAttributes/resourceAttributes to {} when undefined on the NormalizedLog", () => {+ const log = {+ timestamp: "2026-07-01T00:00:00Z",+ body: "boom",+ logAttributes: undefined,+ resourceAttributes: undefined,+ } as unknown as NormalizedLog;+ const row = denormalizeLogToClickHouseRow(log);+ expect(row.LogAttributes).toEqual({});+ expect(row.ResourceAttributes).toEqual({});+ });+});++describe("normalizeLogRow", () => {+ it("normalizes a full ClickHouse otel_logs row", () => {+ const log = normalizeLogRow({+ Timestamp: "2026-07-01T00:00:00Z",+ TraceId: "t1",+ SpanId: "s1",+ SeverityText: "ERROR",+ SeverityNumber: 17,+ Body: "boom",+ ServiceName: "svc",+ LogAttributes: { "user.id": "u1" },+ ResourceAttributes: { "service.name": "svc" },+ ScopeAttributes: { "scope.name": "lib" },+ });+ expect(log).toEqual({+ timestamp: "2026-07-01T00:00:00Z",+ traceId: "t1",+ spanId: "s1",+ severityText: "ERROR",+ severityNumber: 17,+ body: "boom",+ serviceName: "svc",+ logAttributes: { "user.id": "u1" },+ resourceAttributes: { "service.name": "svc" },+ scopeAttributes: { "scope.name": "lib" },+ });+ });++ it("defaults all optional fields to undefined/empty when the row is sparse", () => {+ const log = normalizeLogRow({ Timestamp: "2026-07-01T00:00:00Z", Body: "boom" });+ expect(log).toEqual({+ timestamp: "2026-07-01T00:00:00Z",+ traceId: undefined,+ spanId: undefined,+ severityText: undefined,+ severityNumber: undefined,+ body: "boom",+ serviceName: undefined,+ logAttributes: {},+ resourceAttributes: {},+ scopeAttributes: undefined,+ });+ });++ it("treats SeverityNumber 0 as present (not undefined) since it is explicitly set", () => {+ const log = normalizeLogRow({+ Timestamp: "2026-07-01T00:00:00Z",+ Body: "boom",+ SeverityNumber: 0,+ });+ expect(log.severityNumber).toBe(0);+ });+});++describe("normalizeMetricRow", () => {+ it("normalizes a full ClickHouse metric row, preferring TimeUnix over Timestamp", () => {+ const point = normalizeMetricRow({+ MetricName: "gen_ai.client.token.usage",+ MetricDescription: "tokens",+ MetricUnit: "tokens",+ ServiceName: "svc",+ TimeUnix: "2026-07-01T00:00:00Z",+ Timestamp: "2026-06-01T00:00:00Z",+ Value: "42",+ Attributes: { "gen_ai.token.type": "input" },+ ResourceAttributes: { "service.name": "svc" },+ });+ expect(point).toEqual({+ metricName: "gen_ai.client.token.usage",+ description: "tokens",+ unit: "tokens",+ serviceName: "svc",+ timestamp: "2026-07-01T00:00:00Z",+ value: 42,+ attributes: { "gen_ai.token.type": "input" },+ resourceAttributes: { "service.name": "svc" },+ });+ });++ it("falls back to Timestamp when TimeUnix is absent and defaults optional fields", () => {+ const point = normalizeMetricRow({+ MetricName: "m",+ Timestamp: "2026-07-01T00:00:00Z",+ Value: 1,+ });+ expect(point.timestamp).toBe("2026-07-01T00:00:00Z");+ expect(point.description).toBeUndefined();+ expect(point.unit).toBeUndefined();+ expect(point.serviceName).toBeUndefined();+ expect(point.attributes).toEqual({});+ expect(point.resourceAttributes).toEqual({});+ });++ it("defaults value to 0 for non-numeric Value", () => {+ const point = normalizeMetricRow({ MetricName: "m", Value: "not-a-number" });+ expect(point.value).toBe(0);+ });+});++describe("denormalizeMetricPointsToListRows (edge cases)", () => {+ it("defaults a missing point.serviceName to '' when grouping", () => {+ const points: NormalizedMetricPoint[] = [+ {+ metricName: "m",+ serviceName: undefined,+ timestamp: "2026-07-01T00:00:00.000Z",+ value: 5,+ attributes: {},+ resourceAttributes: {},+ },+ ];+ const rows = denormalizeMetricPointsToListRows(points);+ expect(rows[0].serviceName).toBe("");+ });++ it("keeps the earlier point's latest value when a later point has an invalid timestamp", () => {+ const points: NormalizedMetricPoint[] = [+ {+ metricName: "m",+ serviceName: "svc",+ timestamp: "2026-07-01T00:00:00.000Z",+ value: 10,+ attributes: {},+ resourceAttributes: {},+ },+ {+ metricName: "m",+ serviceName: "svc",+ timestamp: "not-a-date",+ value: 999,+ attributes: {},+ resourceAttributes: {},+ },+ ];+ const rows = denormalizeMetricPointsToListRows(points);+ expect(rows[0].latestValue).toBe(10);+ expect(rows[0].pointCount).toBe(2);+ });++ it("returns [] for an empty points array", () => {+ expect(denormalizeMetricPointsToListRows([])).toEqual([]);+ });++ it("seeds a new group's latest.ts as 0 when the first point's timestamp is invalid", () => {+ const points: NormalizedMetricPoint[] = [+ {+ metricName: "m",+ serviceName: "svc",+ timestamp: "not-a-date",+ value: 7,+ attributes: {},+ resourceAttributes: {},+ },+ ];+ const rows = denormalizeMetricPointsToListRows(points);+ expect(rows[0].latestValue).toBe(7);+ expect(rows[0].lastSeen).toBe("not-a-date");+ });+});diff --git a/src/client/src/__tests__/lib/platform/datasource/otlp-json.test.ts b/src/client/src/__tests__/lib/platform/datasource/otlp-json.test.tsindex cd7ce0a4..e9a547d9 100644--- a/src/client/src/__tests__/lib/platform/datasource/otlp-json.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/otlp-json.test.ts@@ -11,6 +11,30 @@ describe("normalizeOtlpId", () => {it("decodes Tempo base64 OTLP ids to hex", () => {expect(normalizeOtlpId("4LHjnv00zjU=")).toBe("e0b1e39efd34ce35");});++ it("returns empty string for undefined/empty input", () => {+ expect(normalizeOtlpId(undefined)).toBe("");+ expect(normalizeOtlpId("")).toBe("");+ expect(normalizeOtlpId(" ")).toBe("");+ });++ it("trims surrounding whitespace before evaluating", () => {+ expect(normalizeOtlpId(" E0B1E39EFD34CE35 ")).toBe("e0b1e39efd34ce35");+ });++ it("does not treat odd-length hex-looking strings as hex", () => {+ // Odd length fails the hex fast-path, falls through to base64 decode.+ const value = "abc";+ const decoded = Buffer.from(value, "base64");+ expect([8, 16]).not.toContain(decoded.length);+ expect(normalizeOtlpId(value)).toBe(value);+ });++ it("returns the original value unchanged when base64-decoded length is not 8 or 16 bytes", () => {+ // "not-hex!!" decodes to some arbitrary byte length that is not 8/16.+ const value = "not-hex!!";+ expect(normalizeOtlpId(value)).toBe(value);+ });});describe("parseOtlpTrace", () => {@@ -41,4 +65,225 @@ describe("parseOtlpTrace", () => {expect(spans[0].spanId).toBe("e0b1e39efd34ce35");expect(spans[0].traceId).toBe("0123456789abcdef0123456789abcdef");});++ it("handles a nested `trace` wrapper and `resourceSpans`/`instrumentationLibrarySpans` shapes", () => {+ const spans = parseOtlpTrace({+ trace: {+ resourceSpans: [+ {+ resource: {+ attributes: [{ key: "service.name", value: { stringValue: "svc-a" } }],+ },+ instrumentationLibrarySpans: [+ {+ spans: [+ {+ traceId: "0123456789abcdef0123456789abcdef",+ spanId: "0123456789abcdef",+ name: "op",+ },+ ],+ },+ ],+ },+ ],+ },+ });+ expect(spans).toHaveLength(1);+ expect(spans[0].serviceName).toBe("svc-a");+ expect(spans[0].name).toBe("op");+ });++ it("returns [] for an empty/unrecognized payload", () => {+ expect(parseOtlpTrace({})).toEqual([]);+ expect(parseOtlpTrace(null)).toEqual([]);+ expect(parseOtlpTrace(undefined)).toEqual([]);+ });++ it("defaults missing resource/scope/span arrays to empty and missing span name to ''", () => {+ const spans = parseOtlpTrace({+ batches: [{}, { resource: {}, scopeSpans: [{}] }],+ });+ expect(spans).toEqual([]);+ });++ it("normalizes every OTLP AnyValue kind and skips key-less attributes", () => {+ const spans = parseOtlpTrace({+ batches: [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ spans: [+ {+ traceId: "0123456789abcdef0123456789abcdef",+ spanId: "0123456789abcdef",+ name: "attrs",+ attributes: [+ { key: "str.attr", value: { stringValue: "hello" } },+ { key: "int.attr", value: { intValue: 42 } },+ { key: "int.str.attr", value: { intValue: "42" } },+ { key: "double.attr", value: { doubleValue: 1.5 } },+ { key: "bool.attr", value: { boolValue: true } },+ {+ key: "array.attr",+ value: {+ arrayValue: {+ values: [{ stringValue: "a" }, { stringValue: "b" }],+ },+ },+ },+ { key: "empty.attr" },+ { key: "unknown.kind.attr", value: {} },+ { value: { stringValue: "no-key" } } as any,+ ],+ },+ ],+ },+ ],+ },+ ],+ });+ expect(spans[0].spanAttributes).toEqual({+ "str.attr": "hello",+ "int.attr": "42",+ "int.str.attr": "42",+ "double.attr": "1.5",+ "bool.attr": "true",+ "array.attr": JSON.stringify(["a", "b"]),+ "empty.attr": "",+ "unknown.kind.attr": "",+ });+ });++ it("maps numeric and string OTLP status codes, defaulting unset/unknown to their string form", () => {+ const build = (code?: string | number) =>+ parseOtlpTrace({+ batches: [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ spans: [+ {+ traceId: "0123456789abcdef0123456789abcdef",+ spanId: "0123456789abcdef",+ name: "s",+ status: code === undefined ? undefined : { code, message: "m" },+ },+ ],+ },+ ],+ },+ ],+ })[0];++ expect(build(2).statusCode).toBe("STATUS_CODE_ERROR");+ expect(build("ERROR").statusCode).toBe("STATUS_CODE_ERROR");+ expect(build("STATUS_CODE_ERROR").statusCode).toBe("STATUS_CODE_ERROR");+ expect(build(1).statusCode).toBe("STATUS_CODE_OK");+ expect(build("OK").statusCode).toBe("STATUS_CODE_OK");+ expect(build("STATUS_CODE_OK").statusCode).toBe("STATUS_CODE_OK");+ expect(build(0).statusCode).toBe("0");+ expect(build(undefined).statusCode).toBe("");+ expect(build(undefined).statusMessage).toBeUndefined();+ expect(build(2).statusMessage).toBe("m");+ });++ it("computes duration as 0 when start/end timestamps are missing or non-numeric", () => {+ const spans = parseOtlpTrace({+ batches: [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ spans: [+ { traceId: "0123456789abcdef0123456789abcdef", spanId: "0123456789abcdef", name: "no-times" },+ {+ traceId: "0123456789abcdef0123456789abcdef",+ spanId: "0123456789abcdef",+ name: "bad-times",+ startTimeUnixNano: "not-a-number",+ endTimeUnixNano: "2",+ },+ ],+ },+ ],+ },+ ],+ });+ expect(spans[0].durationNs).toBe(0);+ expect(spans[0].timestamp).toBe("");+ expect(spans[1].durationNs).toBe(0);+ });++ it("normalizes span events including the timeUnixNano-falsy branch", () => {+ const spans = parseOtlpTrace({+ batches: [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ spans: [+ {+ traceId: "0123456789abcdef0123456789abcdef",+ spanId: "0123456789abcdef",+ name: "with-events",+ events: [+ { name: "ev1", timeUnixNano: "1000000", attributes: [{ key: "a", value: { stringValue: "1" } }] },+ { timeUnixNano: 0 },+ {},+ ],+ },+ ],+ },+ ],+ },+ ],+ });+ expect(spans[0].events).toEqual([+ { name: "ev1", timestamp: "1970-01-01T00:00:00.001Z", attributes: { a: "1" } },+ { name: "", timestamp: undefined, attributes: {} },+ { name: "", timestamp: undefined, attributes: {} },+ ]);+ });++ it("stringifies numeric span.kind and preserves undefined when absent", () => {+ const withKind = parseOtlpTrace({+ batches: [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ spans: [+ {+ traceId: "0123456789abcdef0123456789abcdef",+ spanId: "0123456789abcdef",+ name: "k",+ kind: 2,+ },+ ],+ },+ ],+ },+ ],+ });+ expect(withKind[0].spanKind).toBe("2");++ const withoutKind = parseOtlpTrace({+ batches: [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ spans: [+ { traceId: "0123456789abcdef0123456789abcdef", spanId: "0123456789abcdef", name: "no-kind" },+ ],+ },+ ],+ },+ ],+ });+ expect(withoutKind[0].spanKind).toBeUndefined();+ });});diff --git a/src/client/src/__tests__/lib/platform/datasource/query-map.test.ts b/src/client/src/__tests__/lib/platform/datasource/query-map.test.tsindex 98c12cb2..9982871f 100644--- a/src/client/src/__tests__/lib/platform/datasource/query-map.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/query-map.test.ts@@ -111,6 +111,62 @@ describe("metricParamsToOpenLITQuery", () => {);});+ it("maps a trace customFilter with attributeType Field/key SpanName to a spanName filter, and ignores other Field keys", () => {+ const query = metricParamsToOpenLITQuery({+ timeLimit: { start: new Date("2026-07-01"), end: new Date("2026-07-02"), type: "CUSTOM" },+ selectedConfig: {+ customFilters: [+ { attributeType: "Field", key: "SpanName", value: "chat" },+ { attributeType: "Field", key: "OtherField", value: "ignored" },+ { key: "" },+ ],+ },+ } as any);+ expect(query.filters).toEqual([+ { target: "spanName", op: "eq", value: "chat" },+ ]);+ });++ it("normalizes every custom filter operator alias (eq/neq/!=/contains/in) for traces", () => {+ const query = metricParamsToOpenLITQuery({+ timeLimit: { start: new Date("2026-07-01"), end: new Date("2026-07-02"), type: "CUSTOM" },+ selectedConfig: {+ customFilters: [+ { key: "a", value: "1", operator: "eq" },+ { key: "b", value: "2", operator: "neq" },+ { key: "c", value: "3", op: "!=" },+ { key: "d", value: "4", operator: "contains" },+ { key: "e", value: ["5", "6"], operator: "in" },+ { key: "f", value: "7" },+ ],+ },+ } as any);+ expect(query.filters).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ key: "a", op: "eq", value: "1" }),+ expect.objectContaining({ key: "b", op: "neq", value: "2" }),+ expect.objectContaining({ key: "c", op: "neq", value: "3" }),+ expect.objectContaining({ key: "d", op: "contains", value: "4" }),+ expect.objectContaining({ key: "e", op: "in", value: ["5", "6"] }),+ expect.objectContaining({ key: "f", op: "eq", value: "7" }),+ ])+ );+ });++ it("scopes a trace customFilter via cf.scope even when attributeType is unset", () => {+ const query = metricParamsToOpenLITQuery({+ timeLimit: { start: new Date("2026-07-01"), end: new Date("2026-07-02"), type: "CUSTOM" },+ selectedConfig: {+ customFilters: [{ key: "cluster", value: "c1", scope: "resource" }],+ },+ } as any);+ expect(query.filters).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ scope: "resource", key: "cluster", value: "c1" }),+ ])+ );+ });+it("maps the remaining trace selectedConfig filters", () => {const query = metricParamsToOpenLITQuery({timeLimit: { start: new Date("2026-07-01"), end: new Date("2026-07-02"), type: "CUSTOM" },@@ -163,6 +219,26 @@ describe("metricParamsToOpenLITQuery", () => {);});+ it("scopes a log customFilter via cf.scope even when attributeType is unset", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const query = metricParamsToOpenLITQuery(+ {+ timeLimit: { start, end, type: "CUSTOM" },+ selectedConfig: {+ customFilters: [+ { key: "cluster", value: "c1", scope: "resource" },+ { key: "" },+ ],+ },+ },+ "logs"+ );+ expect(query.filters).toEqual([+ expect.objectContaining({ scope: "resource", key: "cluster", value: "c1" }),+ ]);+ });+it("maps metric-signal filters (metricNames -> spanName target)", () => {const start = new Date("2026-07-01T00:00:00.000Z");const end = new Date("2026-07-01T01:00:00.000Z");@@ -188,6 +264,43 @@ describe("metricParamsToOpenLITQuery", () => {);});+ it("defaults a metrics customFilter to scope 'metric' when neither attributeType nor cf.scope is resource", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const query = metricParamsToOpenLITQuery(+ {+ timeLimit: { start, end, type: "CUSTOM" },+ selectedConfig: {+ customFilters: [{ key: "unit", value: "ms" }],+ },+ },+ "metrics"+ );+ expect(query.filters).toEqual([+ expect.objectContaining({ scope: "metric", key: "unit", value: "ms" }),+ ]);+ });++ it("scopes a metrics customFilter via cf.scope even when attributeType is unset", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const query = metricParamsToOpenLITQuery(+ {+ timeLimit: { start, end, type: "CUSTOM" },+ selectedConfig: {+ customFilters: [+ { key: "cluster", value: "c1", scope: "resource" },+ { key: "" },+ ],+ },+ },+ "metrics"+ );+ expect(query.filters).toEqual([+ expect.objectContaining({ scope: "resource", key: "cluster", value: "c1" }),+ ]);+ });+it("scopes logs and metrics by agent serviceNames lock", () => {const start = new Date("2026-07-01T00:00:00.000Z");const end = new Date("2026-07-01T01:00:00.000Z");@@ -263,6 +376,88 @@ describe("metricParamsToOpenLITQuery", () => {}});+ it("extracts a single (non-array) status filter value", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const back = toMetricParams({+ signal: "traces",+ timeRange: { start, end },+ filters: [{ target: "status", op: "eq", value: "STATUS_CODE_OK" }],+ });+ expect(back.statusCode).toEqual(["STATUS_CODE_OK"]);+ });++ it("parses a timeLimit.start/.end given as ISO strings (not Date instances)", () => {+ const query = metricParamsToOpenLITQuery({+ timeLimit: {+ start: "2026-07-01T00:00:00.000Z",+ end: "2026-07-01T01:00:00.000Z",+ type: "CUSTOM",+ },+ } as any);+ expect(query.timeRange.start.toISOString()).toBe("2026-07-01T00:00:00.000Z");+ expect(query.timeRange.end.toISOString()).toBe("2026-07-01T01:00:00.000Z");+ });++ it("passes through an asc sorting.direction unchanged", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const query = metricParamsToOpenLITQuery({+ timeLimit: { start, end, type: "CUSTOM" },+ sorting: { type: "Timestamp", direction: "asc" },+ });+ expect(query.sort).toEqual([{ field: "Timestamp", direction: "asc" }]);+ });++ it("defaults sort direction to desc for any non-asc sorting.direction", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const query = metricParamsToOpenLITQuery({+ timeLimit: { start, end, type: "CUSTOM" },+ sorting: { type: "Timestamp", direction: "descending" as any },+ });+ expect(query.sort).toEqual([{ field: "Timestamp", direction: "desc" }]);+ });++ it("ignores custom filters whose key is missing or non-string (traces/logs/metrics)", () => {+ const start = new Date("2026-07-01");+ const end = new Date("2026-07-02");+ for (const signal of ["traces", "logs", "metrics"] as const) {+ const query = metricParamsToOpenLITQuery(+ {+ timeLimit: { start, end, type: "CUSTOM" },+ selectedConfig: {+ customFilters: [{ value: "orphan" }, { key: 42, value: "num-key" }],+ },+ } as any,+ signal+ );+ expect(query.filters).toBeUndefined();+ }+ });++ it("defaults a Field/SpanName custom filter's value to '' when nullish", () => {+ const query = metricParamsToOpenLITQuery({+ timeLimit: { start: new Date("2026-07-01"), end: new Date("2026-07-02"), type: "CUSTOM" },+ selectedConfig: {+ customFilters: [{ attributeType: "Field", key: "SpanName", value: undefined }],+ },+ } as any);+ expect(query.filters).toEqual([{ target: "spanName", op: "eq", value: "" }]);+ });++ it("leaves a custom filter's value undefined when the source value is undefined", () => {+ const query = metricParamsToOpenLITQuery({+ timeLimit: { start: new Date("2026-07-01"), end: new Date("2026-07-02"), type: "CUSTOM" },+ selectedConfig: {+ customFilters: [{ key: "tenant.id", value: undefined }],+ },+ } as any);+ expect(query.filters).toEqual([+ expect.objectContaining({ key: "tenant.id", value: undefined }),+ ]);+ });+it("round-trips time/limit through toMetricParams", () => {const start = new Date("2026-07-01T00:00:00.000Z");const end = new Date("2026-07-01T01:00:00.000Z");@@ -279,6 +474,27 @@ describe("metricParamsToOpenLITQuery", () => {expect(back.timeLimit.end).toBe("2026-07-01T01:00:00.000Z");});+ it("carries a query sort through toMetricParams as a sorting object", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const back = toMetricParams({+ signal: "traces",+ timeRange: { start, end },+ sort: [{ field: "Timestamp", direction: "asc" }],+ });+ expect(back.sorting).toEqual({ type: "Timestamp", direction: "asc" });+ });++ it("leaves sorting undefined when the query has no sort", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const back = toMetricParams({+ signal: "traces",+ timeRange: { start, end },+ });+ expect(back.sorting).toBeUndefined();+ });+it("round-trips generationHealth on the ClickHouse path without vendor filters", () => {const query = metricParamsToOpenLITQuery({timeLimit: {@@ -301,6 +517,156 @@ describe("metricParamsToOpenLITQuery", () => {]);});+ it("skips filters with no target/attribute match and non-attribute/no-key filters", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const back = toMetricParams({+ signal: "traces",+ timeRange: { start, end },+ filters: [+ { target: "duration", op: "gt", value: 100 },+ { target: "attribute", op: "eq", value: "x" },+ ],+ });+ expect(back.selectedConfig.customFilters).toBeUndefined();+ });++ it("maps a spanName filter to metricNames for the metrics signal and spanNames otherwise", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const metrics = toMetricParams({+ signal: "metrics",+ timeRange: { start, end },+ filters: [{ target: "spanName", op: "in", value: ["gen_ai.client.token.usage"] }],+ });+ expect(metrics.selectedConfig.metricNames).toEqual(["gen_ai.client.token.usage"]);++ const traces = toMetricParams({+ signal: "traces",+ timeRange: { start, end },+ filters: [{ target: "spanName", op: "eq", value: "chat" }],+ });+ expect(traces.selectedConfig.spanNames).toEqual(["chat"]);+ });++ it("maps service.name to applicationNames for traces and services otherwise", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const traces = toMetricParams({+ signal: "traces",+ timeRange: { start, end },+ filters: [+ { target: "attribute", key: "service.name", op: "in", value: ["api"] },+ ],+ });+ expect(traces.selectedConfig.applicationNames).toEqual(["api"]);++ const logs = toMetricParams({+ signal: "logs",+ timeRange: { start, end },+ filters: [+ { target: "attribute", key: "service.name", op: "in", value: ["api"] },+ ],+ });+ expect(logs.selectedConfig.services).toEqual(["api"]);+ });++ it("maps trace-only known attribute keys to their legacy selectedConfig keys", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const back = toMetricParams({+ signal: "traces",+ timeRange: { start, end },+ filters: [+ { target: "attribute", key: "gen_ai.request.model", op: "in", value: ["gpt-4o"] },+ { target: "attribute", key: "gen_ai.system", op: "in", value: ["openai"] },+ { target: "attribute", key: "gen_ai.operation.name", op: "in", value: ["chat"] },+ { target: "attribute", key: "deployment.environment", op: "in", value: ["prod"] },+ ],+ });+ expect(back.selectedConfig).toMatchObject({+ models: ["gpt-4o"],+ providers: ["openai"],+ traceTypes: ["chat"],+ environments: ["prod"],+ });+ });++ it("does not special-case the trace-only keys for logs/metrics signals (falls through to customFilters)", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const back = toMetricParams({+ signal: "logs",+ timeRange: { start, end },+ filters: [+ { target: "attribute", key: "gen_ai.request.model", op: "eq", value: "gpt-4o" },+ ],+ });+ expect(back.selectedConfig.models).toBeUndefined();+ expect(back.selectedConfig.customFilters).toEqual([+ { attributeType: "LogAttributes", key: "gen_ai.request.model", value: "gpt-4o" },+ ]);+ });++ it("chooses the customFilter attributeType by scope and signal (resource/log/metric/span defaults)", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const resourceScoped = toMetricParams({+ signal: "traces",+ timeRange: { start, end },+ filters: [+ { target: "attribute", scope: "resource", key: "cluster", op: "eq", value: "c1" },+ ],+ });+ expect(resourceScoped.selectedConfig.customFilters).toEqual([+ { attributeType: "ResourceAttributes", key: "cluster", value: "c1" },+ ]);++ const metricsScoped = toMetricParams({+ signal: "metrics",+ timeRange: { start, end },+ filters: [{ target: "attribute", key: "unit", op: "eq", value: "ms" }],+ });+ expect(metricsScoped.selectedConfig.customFilters).toEqual([+ { attributeType: "Attributes", key: "unit", value: "ms" },+ ]);++ const spanScoped = toMetricParams({+ signal: "traces",+ timeRange: { start, end },+ filters: [{ target: "attribute", key: "tenant.id", op: "eq", value: "t1" }],+ });+ expect(spanScoped.selectedConfig.customFilters).toEqual([+ { attributeType: "SpanAttributes", key: "tenant.id", value: "t1" },+ ]);+ });++ it("stringifies the first array value for a custom filter and defaults an undefined value to ''", () => {+ const start = new Date("2026-07-01T00:00:00.000Z");+ const end = new Date("2026-07-01T01:00:00.000Z");+ const back = toMetricParams({+ signal: "traces",+ timeRange: { start, end },+ filters: [+ { target: "attribute", key: "multi", op: "in", value: ["a", "b"] },+ { target: "attribute", key: "novalue", op: "exists" },+ ],+ });+ expect(back.selectedConfig.customFilters).toEqual([+ { attributeType: "SpanAttributes", key: "multi", value: "a" },+ { attributeType: "SpanAttributes", key: "novalue", value: "" },+ ]);+ });++ it("falls back to the provided fallback Date when timeLimit.start is an unparsable string or the wrong type", () => {+ const query = metricParamsToOpenLITQuery({+ timeLimit: { start: "not-a-date", end: 12345 as unknown as Date, type: "CUSTOM" },+ } as any);+ // Both start and end should fall back to sane defaults rather than throw/NaN.+ expect(Number.isNaN(query.timeRange.start.getTime())).toBe(false);+ expect(Number.isNaN(query.timeRange.end.getTime())).toBe(false);+ });+it("round-trips agentLoop on the ClickHouse path", () => {const query = metricParamsToOpenLITQuery({timeLimit: {diff --git a/src/client/src/__tests__/lib/platform/datasource/query-observability.test.ts b/src/client/src/__tests__/lib/platform/datasource/query-observability.test.tsnew file mode 100644index 00000000..7c06a580--- /dev/null+++ b/src/client/src/__tests__/lib/platform/datasource/query-observability.test.ts@@ -0,0 +1,230 @@+import { logQueryObservability } from "@/lib/platform/connectors/datasource/query-observability";++describe("logQueryObservability", () => {+ const originalNodeEnv = process.env.NODE_ENV;+ const originalFlag = process.env.OPENLIT_QUERY_OBSERVABILITY;+ let debugSpy: jest.SpyInstance;++ beforeEach(() => {+ debugSpy = jest.spyOn(console, "debug").mockImplementation(() => undefined);+ });++ afterEach(() => {+ debugSpy.mockRestore();+ (process.env as Record<string, string | undefined>).NODE_ENV = originalNodeEnv;+ if (originalFlag === undefined) {+ delete process.env.OPENLIT_QUERY_OBSERVABILITY;+ } else {+ process.env.OPENLIT_QUERY_OBSERVABILITY = originalFlag;+ }+ });++ it("logs by default outside production", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "development";+ delete process.env.OPENLIT_QUERY_OBSERVABILITY;++ logQueryObservability({ sourceType: "loki", signal: "logs" }, undefined, 3);++ expect(debugSpy).toHaveBeenCalledTimes(1);+ const [, payload] = debugSpy.mock.calls[0];+ expect(JSON.parse(payload)).toMatchObject({+ source: "loki",+ signal: "logs",+ rows: 3,+ });+ });++ it("is disabled by default in production", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "production";+ delete process.env.OPENLIT_QUERY_OBSERVABILITY;++ logQueryObservability({ sourceType: "loki", signal: "logs" }, undefined, 3);++ expect(debugSpy).not.toHaveBeenCalled();+ });++ it("force-enables via flag=1 even in production", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "production";+ process.env.OPENLIT_QUERY_OBSERVABILITY = "1";++ logQueryObservability({ sourceType: "tempo", signal: "traces" }, undefined, 0);++ expect(debugSpy).toHaveBeenCalledTimes(1);+ });++ it("force-enables via flag=true even in production", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "production";+ process.env.OPENLIT_QUERY_OBSERVABILITY = "true";++ logQueryObservability({ sourceType: "tempo", signal: "traces" }, undefined, 0);++ expect(debugSpy).toHaveBeenCalledTimes(1);+ });++ it("force-disables via flag=0 outside production", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "development";+ process.env.OPENLIT_QUERY_OBSERVABILITY = "0";++ logQueryObservability({ sourceType: "tempo", signal: "traces" }, undefined, 0);++ expect(debugSpy).not.toHaveBeenCalled();+ });++ it("force-disables via flag=false outside production", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "development";+ process.env.OPENLIT_QUERY_OBSERVABILITY = "false";++ logQueryObservability({ sourceType: "tempo", signal: "traces" }, undefined, 0);++ expect(debugSpy).not.toHaveBeenCalled();+ });++ it("skips built-in sources regardless of the flag", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "development";+ process.env.OPENLIT_QUERY_OBSERVABILITY = "1";++ logQueryObservability(+ { sourceType: "clickhouse", signal: "traces", isBuiltIn: true },+ undefined,+ 10+ );++ expect(debugSpy).not.toHaveBeenCalled();+ });++ it("includes mode and full meta fields when present", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "development";+ delete process.env.OPENLIT_QUERY_OBSERVABILITY;++ logQueryObservability(+ { sourceType: "prometheus", signal: "metrics", mode: "aggregate" },+ {+ latencyMs: 42,+ rowsScanned: 100,+ freshness: "sampled",+ truncated: true,+ degraded: ["serverAggregation", "rollup"],+ },+ 5+ );++ const [, payload] = debugSpy.mock.calls[0];+ expect(JSON.parse(payload)).toEqual({+ source: "prometheus",+ signal: "metrics",+ mode: "aggregate",+ rows: 5,+ latencyMs: 42,+ scanned: 100,+ freshness: "sampled",+ truncated: 1,+ degraded: "serverAggregation,rollup",+ });+ });++ it("omits optional fields entirely when meta is absent", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "development";+ delete process.env.OPENLIT_QUERY_OBSERVABILITY;++ logQueryObservability({ sourceType: "jaeger", signal: "traces" }, undefined, 0);++ const [, payload] = debugSpy.mock.calls[0];+ const parsed = JSON.parse(payload);+ expect(parsed).toEqual({ source: "jaeger", signal: "traces", rows: 0 });+ expect(parsed).not.toHaveProperty("mode");+ expect(parsed).not.toHaveProperty("latencyMs");+ expect(parsed).not.toHaveProperty("scanned");+ expect(parsed).not.toHaveProperty("freshness");+ expect(parsed).not.toHaveProperty("truncated");+ expect(parsed).not.toHaveProperty("degraded");+ });++ it("treats truncated=false and empty degraded as absent", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "development";+ delete process.env.OPENLIT_QUERY_OBSERVABILITY;++ logQueryObservability(+ { sourceType: "jaeger", signal: "traces" },+ { truncated: false, degraded: [] },+ 1+ );++ const [, payload] = debugSpy.mock.calls[0];+ const parsed = JSON.parse(payload);+ expect(parsed).not.toHaveProperty("truncated");+ expect(parsed).not.toHaveProperty("degraded");+ });++ it("falls back rowCount to 0 when NaN", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "development";+ delete process.env.OPENLIT_QUERY_OBSERVABILITY;++ logQueryObservability({ sourceType: "jaeger", signal: "traces" }, undefined, NaN);++ const [, payload] = debugSpy.mock.calls[0];+ expect(JSON.parse(payload).rows).toBe(0);+ });++ it("sanitizes control characters and truncates long tokens", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "development";+ delete process.env.OPENLIT_QUERY_OBSERVABILITY;++ logQueryObservability(+ {+ sourceType: "loki\r\ninjected: true",+ signal: "logs",+ mode: "a".repeat(100),+ },+ { freshness: "live" as const },+ 1+ );++ const [, payload] = debugSpy.mock.calls[0];+ expect(payload).not.toMatch(/[\n\r]/);+ const parsed = JSON.parse(payload);+ expect(parsed.source).toBe("lokiinjected: true");+ expect(parsed.mode).toHaveLength(64);+ });++ it("defaults sanitized tokens to empty string when the source value is nullish", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "development";+ delete process.env.OPENLIT_QUERY_OBSERVABILITY;++ logQueryObservability(+ { sourceType: undefined as unknown as string, signal: "logs" },+ undefined,+ 1+ );++ const [, payload] = debugSpy.mock.calls[0];+ expect(JSON.parse(payload).source).toBe("");+ });++ it("falls back latencyMs/rowsScanned to 0 when NaN rather than dropping the field", () => {+ (process.env as Record<string, string | undefined>).NODE_ENV = "development";+ delete process.env.OPENLIT_QUERY_OBSERVABILITY;++ logQueryObservability(+ { sourceType: "loki", signal: "logs" },+ { latencyMs: NaN, rowsScanned: NaN },+ 1+ );++ const [, payload] = debugSpy.mock.calls[0];+ const parsed = JSON.parse(payload);+ expect(parsed.latencyMs).toBe(0);+ expect(parsed.scanned).toBe(0);+ });++ it("never throws even if console.debug throws", () => {+ debugSpy.mockImplementation(() => {+ throw new Error("boom");+ });+ (process.env as Record<string, string | undefined>).NODE_ENV = "development";+ delete process.env.OPENLIT_QUERY_OBSERVABILITY;++ expect(() =>+ logQueryObservability({ sourceType: "loki", signal: "logs" }, undefined, 1)+ ).not.toThrow();+ });+});diff --git a/src/client/src/__tests__/lib/platform/datasource/rollup-policy.test.ts b/src/client/src/__tests__/lib/platform/datasource/rollup-policy.test.tsindex 7a31d71c..28853bc2 100644--- a/src/client/src/__tests__/lib/platform/datasource/rollup-policy.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/rollup-policy.test.ts@@ -49,4 +49,91 @@ describe("rollup-policy", () => {})).toBe(false);});++ it("detects deployment.environment as a scope filter", () => {+ expect(+ queryHasScopeFilters({+ signal: "traces",+ timeRange: { start: new Date(), end: new Date() },+ filters: [+ {+ target: "attribute",+ scope: "resource",+ key: "deployment.environment",+ op: "eq",+ value: "prod",+ },+ ],+ })+ ).toBe(true);+ });++ it("detects openlit.agent.version_hash as a scope filter", () => {+ expect(+ queryHasScopeFilters({+ signal: "traces",+ timeRange: { start: new Date(), end: new Date() },+ filters: [+ {+ target: "attribute",+ scope: "span",+ key: "openlit.agent.version_hash",+ op: "eq",+ value: "abc123",+ },+ ],+ })+ ).toBe(true);+ });++ it("ignores non-attribute targets and filters without a key", () => {+ expect(+ queryHasScopeFilters({+ signal: "traces",+ timeRange: { start: new Date(), end: new Date() },+ filters: [+ {+ target: "duration",+ scope: "resource",+ key: "service.name",+ op: "eq",+ value: "api",+ },+ ],+ })+ ).toBe(false);+ expect(+ queryHasScopeFilters({+ signal: "traces",+ timeRange: { start: new Date(), end: new Date() },+ filters: [+ {+ target: "attribute",+ scope: "resource",+ key: "",+ op: "eq",+ value: "api",+ },+ ],+ })+ ).toBe(false);+ });++ it("ignores unrelated attribute keys", () => {+ expect(+ queryHasScopeFilters({+ signal: "traces",+ timeRange: { start: new Date(), end: new Date() },+ filters: [+ {+ target: "attribute",+ scope: "span",+ key: "http.status_code",+ op: "eq",+ value: "200",+ },+ ],+ })+ ).toBe(false);+ });});diff --git a/src/client/src/__tests__/lib/platform/datasource/safe-fetch.test.ts b/src/client/src/__tests__/lib/platform/datasource/safe-fetch.test.tsindex 820a88c8..84fcd010 100644--- a/src/client/src/__tests__/lib/platform/datasource/safe-fetch.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/safe-fetch.test.ts@@ -1,8 +1,12 @@import {assertPublicUrl,+ isCloudMetadataAddress,isPrivateAddress,+ readLimitedResponseText,redact,safeFetch,+ selfHostedNetworkOptions,+ SourceResponseError,SsrfError,} from "@/lib/platform/connectors/datasource/http/safe-fetch";@@ -26,6 +30,27 @@ describe("isPrivateAddress", () => {expect(isPrivateAddress("::ffff:127.0.0.1")).toBe(true);expect(isPrivateAddress("2606:4700:4700::1111")).toBe(false);});++ it("is false for a non-IP-literal hostname", () => {+ expect(isPrivateAddress("example.com")).toBe(false);+ });+});++describe("isCloudMetadataAddress", () => {+ it("flags any 169.254.x.x address, not just the well-known metadata IP", () => {+ expect(isCloudMetadataAddress("169.254.1.1")).toBe(true);+ expect(isCloudMetadataAddress("169.254.169.254")).toBe(true);+ expect(isCloudMetadataAddress("8.8.8.8")).toBe(false);+ });++ it("flags the IPv4-mapped IPv6 form of a metadata address", () => {+ expect(isCloudMetadataAddress("::ffff:169.254.169.254")).toBe(true);+ expect(isCloudMetadataAddress("2606:4700:4700::1111")).toBe(false);+ });++ it("is false for a non-IP-literal hostname", () => {+ expect(isCloudMetadataAddress("example.com")).toBe(false);+ });});describe("assertPublicUrl", () => {@@ -138,6 +163,156 @@ describe("assertPublicUrl", () => {await expect(assertPublicUrl("https://8.8.8.8")).resolves.toBeInstanceOf(URL);await expect(assertPublicUrl("https://10.1.2.3")).rejects.toThrow(SsrfError);});++ it("blocks a literal metadata IP that is not the well-known hardcoded hostname", async () => {+ await expect(+ assertPublicUrl("http://169.254.1.1", {+ allowHttp: true,+ allowPrivateNetwork: true,+ })+ ).rejects.toThrow(SsrfError);+ });++ it("wraps a lookup failure in SsrfError", async () => {+ const failingLookup = async () => {+ throw new Error("DNS timeout");+ };+ await expect(+ assertPublicUrl("https://api.example.com", { lookup: failingLookup })+ ).rejects.toThrow(/Could not resolve host/);+ });++ it("rejects a hostname that resolves to no addresses", async () => {+ const emptyLookup = async () => [];+ await expect(+ assertPublicUrl("https://api.example.com", { lookup: emptyLookup })+ ).rejects.toThrow(/did not resolve to any address/);+ });+});++describe("selfHostedNetworkOptions", () => {+ it("defaults to allowing http and disallowing private network access", () => {+ expect(selfHostedNetworkOptions()).toEqual({+ allowHttp: true,+ allowPrivateNetwork: false,+ });+ expect(selfHostedNetworkOptions({})).toEqual({+ allowHttp: true,+ allowPrivateNetwork: false,+ });+ });++ it("disables http only when explicitly set to false or the string 'false'", () => {+ expect(selfHostedNetworkOptions({ allowHttp: false }).allowHttp).toBe(false);+ expect(selfHostedNetworkOptions({ allowHttp: "false" }).allowHttp).toBe(+ false+ );+ expect(selfHostedNetworkOptions({ allowHttp: true }).allowHttp).toBe(true);+ expect(selfHostedNetworkOptions({ allowHttp: "true" }).allowHttp).toBe(+ true+ );+ });++ it("enables private network access for every truthy setting variant", () => {+ expect(+ selfHostedNetworkOptions({ allowPrivateNetwork: true }).allowPrivateNetwork+ ).toBe(true);+ expect(+ selfHostedNetworkOptions({ allowPrivateNetwork: "true" })+ .allowPrivateNetwork+ ).toBe(true);+ expect(+ selfHostedNetworkOptions({ allowPrivateNetwork: 1 }).allowPrivateNetwork+ ).toBe(true);+ expect(+ selfHostedNetworkOptions({ allowPrivateNetwork: "1" }).allowPrivateNetwork+ ).toBe(true);+ expect(+ selfHostedNetworkOptions({ allowPrivateNetwork: "yes" })+ .allowPrivateNetwork+ ).toBe(false);+ });+});++function streamBody(chunks: (Uint8Array | undefined)[]) {+ let index = 0;+ let cancelled = false;+ return {+ getReader() {+ return {+ read: async () => {+ if (index >= chunks.length) {+ return { done: true, value: undefined };+ }+ const value = chunks[index++];+ return { done: false, value };+ },+ cancel: async () => {+ cancelled = true;+ },+ releaseLock: () => undefined,+ get cancelled() {+ return cancelled;+ },+ };+ },+ };+}++describe("readLimitedResponseText", () => {+ const encoder = new TextEncoder();++ it("streams and decodes chunks via body.getReader when available", async () => {+ const response = {+ headers: { get: () => null },+ body: streamBody([encoder.encode("hello "), encoder.encode("world")]),+ } as unknown as Response;++ const text = await readLimitedResponseText(response);+ expect(text).toBe("hello world");+ });++ it("skips falsy chunk values while streaming", async () => {+ const response = {+ headers: { get: () => null },+ body: streamBody([encoder.encode("a"), undefined, encoder.encode("b")]),+ } as unknown as Response;++ const text = await readLimitedResponseText(response);+ expect(text).toBe("ab");+ });++ it("cancels the reader and throws once the streamed total exceeds maxBytes", async () => {+ const body = streamBody([+ encoder.encode("x".repeat(10)),+ encoder.encode("y".repeat(10)),+ ]);+ const response = {+ headers: { get: () => null },+ body,+ } as unknown as Response;++ await expect(readLimitedResponseText(response, 15)).rejects.toThrow(+ /MiB safety limit/i+ );+ });++ it("falls back to text().length when Buffer is unavailable and no reader is present", async () => {+ const response = {+ headers: { get: () => null },+ text: async () => "plain body",+ } as unknown as Response;++ const originalBuffer = globalThis.Buffer;+ // @ts-expect-error -- simulate a runtime without the Node Buffer global.+ delete globalThis.Buffer;+ try {+ const text = await readLimitedResponseText(response);+ expect(text).toBe("plain body");+ } finally {+ globalThis.Buffer = originalBuffer;+ }+ });});describe("redact", () => {@@ -309,4 +484,206 @@ describe("safeFetch", () => {})).rejects.toThrow(/MiB safety limit/i);});++ it("returns the raw text when the response body is not valid JSON", async () => {+ const fetchImpl = jest.fn().mockResolvedValue({+ ok: true,+ status: 200,+ headers: { get: () => null },+ text: async () => "plain text response",+ });+ const result = await safeFetch("https://api.example.com", {+ lookup,+ fetchImpl: fetchImpl as unknown as typeof fetch,+ });+ expect(result).toBe("plain text response");+ });++ it("converts an AbortError into a timeout message", async () => {+ const fetchImpl = jest.fn().mockImplementation(() => {+ const err = new Error("aborted");+ err.name = "AbortError";+ return Promise.reject(err);+ });+ await expect(+ safeFetch("https://api.example.com", {+ lookup,+ fetchImpl: fetchImpl as unknown as typeof fetch,+ })+ ).rejects.toThrow(/timed out/i);+ });++ it("redacts secrets from a generic network error thrown by fetchImpl", async () => {+ const fetchImpl = jest.fn().mockRejectedValue(new Error("fetch failed: secret-token-1"));+ await expect(+ safeFetch("https://api.example.com", {+ lookup,+ fetchImpl: fetchImpl as unknown as typeof fetch,+ redactValues: ["secret-token-1"],+ })+ ).rejects.toThrow(/\[REDACTED\]/);+ });++ it("throws SourceResponseError when a redirect has no Location header", async () => {+ const fetchImpl = jest.fn().mockResolvedValue({+ status: 302,+ headers: { get: () => null },+ text: async () => "",+ });+ await expect(+ safeFetch("https://api.example.com", {+ lookup,+ fetchImpl: fetchImpl as unknown as typeof fetch,+ })+ ).rejects.toBeInstanceOf(SourceResponseError);+ });++ it("throws SsrfError when the redirect Location cannot be parsed as a URL", async () => {+ const fetchImpl = jest.fn().mockResolvedValue({+ status: 302,+ headers: { get: (h: string) => (h === "location" ? "http://[bad" : null) },+ text: async () => "",+ });+ await expect(+ safeFetch("https://api.example.com", {+ lookup,+ fetchImpl: fetchImpl as unknown as typeof fetch,+ })+ ).rejects.toThrow(/invalid URL/i);+ });++ it("throws once the maximum number of redirects is exceeded", async () => {+ const fetchImpl = jest.fn().mockResolvedValue({+ status: 302,+ headers: {+ get: (h: string) => (h === "location" ? "https://api.example.com/next" : null),+ },+ text: async () => "",+ });+ await expect(+ safeFetch("https://api.example.com", {+ lookup,+ fetchImpl: fetchImpl as unknown as typeof fetch,+ })+ ).rejects.toThrow(/maximum number of redirects/i);+ });++ it("rewrites loopback endpoints for Docker when allowPrivateNetwork is set", async () => {+ const fetchImpl = jest.fn().mockResolvedValue({+ ok: true,+ status: 200,+ headers: { get: () => null },+ text: async () => JSON.stringify({ ok: true }),+ });+ const result = await safeFetch("http://localhost:9090", {+ allowHttp: true,+ allowPrivateNetwork: true,+ fetchImpl: fetchImpl as unknown as typeof fetch,+ });+ expect(result).toEqual({ ok: true });+ expect(fetchImpl).toHaveBeenCalledTimes(1);+ });++ it("runs under a per-source concurrency cap when concurrencyKey is set", async () => {+ const fetchImpl = jest.fn().mockResolvedValue({+ ok: true,+ status: 200,+ headers: { get: () => null },+ text: async () => JSON.stringify({ ok: true }),+ });+ const result = await safeFetch("https://api.example.com", {+ lookup,+ fetchImpl: fetchImpl as unknown as typeof fetch,+ concurrencyKey: "safe-fetch-test-source",+ maxConcurrent: 2,+ });+ expect(result).toEqual({ ok: true });+ });++ it("defaults maxConcurrent to 4 when a concurrencyKey is set without an explicit cap", async () => {+ const fetchImpl = jest.fn().mockResolvedValue({+ ok: true,+ status: 200,+ headers: { get: () => null },+ text: async () => JSON.stringify({ ok: true }),+ });+ const result = await safeFetch("https://api.example.com", {+ lookup,+ fetchImpl: fetchImpl as unknown as typeof fetch,+ concurrencyKey: "safe-fetch-test-default-concurrency",+ });+ expect(result).toEqual({ ok: true });+ });++ it("falls back to the global fetch implementation when fetchImpl is not provided", async () => {+ const globalFetch = jest.fn().mockResolvedValue({+ ok: true,+ status: 200,+ headers: { get: () => null },+ text: async () => JSON.stringify({ fromGlobal: true }),+ });+ const originalFetch = (globalThis as { fetch?: typeof fetch }).fetch;+ (globalThis as { fetch?: unknown }).fetch = globalFetch;+ try {+ const result = await safeFetch("https://api.example.com", { lookup });+ expect(result).toEqual({ fromGlobal: true });+ expect(globalFetch).toHaveBeenCalledTimes(1);+ } finally {+ if (originalFetch === undefined) {+ delete (globalThis as { fetch?: unknown }).fetch;+ } else {+ (globalThis as { fetch?: typeof fetch }).fetch = originalFetch;+ }+ }+ });++ it("treats a boolean retry: true as default retry options", async () => {+ const fetchImpl = jest+ .fn()+ .mockResolvedValueOnce({+ ok: false,+ status: 503,+ text: async () => "down",+ })+ .mockResolvedValueOnce({+ ok: true,+ status: 200,+ headers: { get: () => null },+ text: async () => JSON.stringify({ ok: true }),+ });+ const result = await safeFetch("https://api.example.com", {+ lookup,+ fetchImpl: fetchImpl as unknown as typeof fetch,+ retry: true,+ });+ expect(result).toEqual({ ok: true });+ expect(fetchImpl).toHaveBeenCalledTimes(2);+ });++ it("returns undefined for a successful response with an empty body", async () => {+ const fetchImpl = jest.fn().mockResolvedValue({+ ok: true,+ status: 200,+ headers: { get: () => null },+ text: async () => "",+ });+ const result = await safeFetch("https://api.example.com", {+ lookup,+ fetchImpl: fetchImpl as unknown as typeof fetch,+ });+ expect(result).toBeUndefined();+ });++ it("redacts secrets from a thrown non-Error value that has no message", async () => {+ const fetchImpl = jest+ .fn()+ .mockRejectedValue("raw-secret-string-failure");+ await expect(+ safeFetch("https://api.example.com", {+ lookup,+ fetchImpl: fetchImpl as unknown as typeof fetch,+ redactValues: ["raw-secret-string-failure"],+ })+ ).rejects.toThrow(/\[REDACTED\]/);+ });});diff --git a/src/client/src/__tests__/lib/platform/datasource/sample-fetch-list.test.ts b/src/client/src/__tests__/lib/platform/datasource/sample-fetch-list.test.tsindex bb97ef60..4e753c6c 100644--- a/src/client/src/__tests__/lib/platform/datasource/sample-fetch-list.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/sample-fetch-list.test.ts@@ -1,8 +1,10 @@import {collapseToRootSpans,+ fetchSpansForAggregation,fetchSpansForList,pickRootSpan,} from "@/lib/platform/connectors/datasource/graph/sample-fetch";+import { __clearCache } from "@/lib/platform/connectors/datasource/http/cache";import type { NormalizedSpan, OpenLITQuery } from "@/lib/platform/connectors/datasource/types";function span(partial: Partial<NormalizedSpan>): NormalizedSpan {@@ -30,6 +32,10 @@ const windowQuery: OpenLITQuery = {aiSelector: true,};+beforeEach(() => {+ __clearCache();+});+describe("sample-fetch list stratification", () => {it("picks root span and collapses one root per trace", () => {const root = span({@@ -135,4 +141,343 @@ describe("sample-fetch list stratification", () => {expect(sampled).toBe(true);expect(result.spans).toHaveLength(1);});++ it("extracts service names from array-valued and scalar service.name filters", async () => {+ const calls: string[] = [];+ const source = {+ discoverServices: async () => {+ throw new Error("should not discover when filters already scope services");+ },+ sampleTracesForGraph: async (q: OpenLITQuery) => {+ const value = (q.filters || []).find((f) => f.key === "service.name")+ ?.value;+ calls.push(String(value));+ return [+ span({+ spanId: `s-${value}`,+ traceId: `t-${value}`,+ serviceName: String(value),+ }),+ ];+ },+ };++ const result = await fetchSpansForList(+ source,+ {+ ...windowQuery,+ filters: [+ {+ target: "attribute",+ scope: "resource",+ key: "http.method",+ op: "eq",+ value: "GET",+ },+ {+ target: "attribute",+ scope: "resource",+ key: "service.name",+ op: "in",+ value: ["svc-a", "", "svc-b"],+ },+ ],+ },+ { maxRows: 10, skipCache: true }+ );++ expect(calls.sort()).toEqual(["svc-a", "svc-b"]);+ expect(result.spans).toHaveLength(2);+ });++ it("returns null from stratification when discoverServices throws with no service filter", async () => {+ let sampleCalls = 0;+ const source = {+ discoverServices: async () => {+ throw new Error("discovery unavailable");+ },+ sampleTracesForGraph: async () => {+ sampleCalls += 1;+ return [span({ spanId: "1" })];+ },+ };++ const result = await fetchSpansForAggregation(source, windowQuery, {+ skipCache: true,+ });++ expect(sampleCalls).toBe(1);+ expect(result.spans).toHaveLength(1);+ });++ it("returns empty spans when the source has neither sampleTracesForGraph nor listSpans", async () => {+ const result = await fetchSpansForAggregation(+ {},+ windowQuery,+ { skipCache: true }+ );+ expect(result).toEqual({ spans: [], truncated: false });+ });++ it("returns flat listSpans rows unchanged when they are not roots-only", async () => {+ const child = span({+ spanId: "child",+ traceId: "t1",+ parentSpanId: "root-not-included",+ });+ const source = {+ listSpans: async () => ({ fields: [], rows: [child] }),+ getTraceSpans: async () => {+ throw new Error("should not expand a non-roots-only list");+ },+ };++ const result = await fetchSpansForAggregation(source, windowQuery, {+ skipCache: true,+ });++ expect(result.spans).toEqual([child]);+ });++ it("uses the cache path for fetchSpansForAggregation when skipCache is not set", async () => {+ let calls = 0;+ const source = {+ sampleCacheKey: "agg-cache-test-source",+ sampleTracesForGraph: async () => {+ calls += 1;+ return [span({ spanId: "1" })];+ },+ };++ const first = await fetchSpansForAggregation(source, windowQuery);+ const second = await fetchSpansForAggregation(source, windowQuery);++ expect(first.spans).toEqual(second.spans);+ expect(calls).toBe(1);+ });++ it("uses the cache path when skipCache is not set", async () => {+ let calls = 0;+ const source = {+ sampleCacheKey: "cache-test-source",+ sampleTracesForGraph: async () => {+ calls += 1;+ return [span({ spanId: "1" })];+ },+ };++ const first = await fetchSpansForList(source, windowQuery, { maxRows: 5 });+ const second = await fetchSpansForList(source, windowQuery, { maxRows: 5 });++ expect(first.spans).toEqual(second.spans);+ expect(calls).toBe(1);+ });++ it("dedupes repeated trace ids from a full-trace stratified sample", async () => {+ const source = {+ discoverServices: async () => [+ { serviceName: "a", environment: "default", clusterId: "default" },+ { serviceName: "b", environment: "default", clusterId: "default" },+ ],+ sampleTracesForGraph: async (q: OpenLITQuery) => {+ const value = String(+ (q.filters || []).find((f) => f.key === "service.name")?.value || ""+ );+ // Simulate a full trace: multiple spans share the same traceId.+ return [+ span({ spanId: `${value}-root`, traceId: `t-${value}` }),+ span({+ spanId: `${value}-child`,+ traceId: `t-${value}`,+ parentSpanId: `${value}-root`,+ }),+ ];+ },+ };++ const result = await fetchSpansForAggregation(source, windowQuery, {+ maxTraces: 10,+ skipCache: true,+ });++ const traceIds = new Set(result.spans.map((s) => s.traceId));+ expect(traceIds.size).toBe(2);+ expect(result.spans).toHaveLength(4);+ });++ it("returns null from stratification when discovery resolves to a single service", async () => {+ let sampleCalls = 0;+ const source = {+ discoverServices: async () => [+ { serviceName: "only-service", environment: "default", clusterId: "default" },+ ],+ sampleTracesForGraph: async () => {+ sampleCalls += 1;+ return [span({ spanId: "1" })];+ },+ };++ const result = await fetchSpansForAggregation(source, windowQuery, {+ skipCache: true,+ });++ expect(sampleCalls).toBe(1);+ expect(result.spans).toHaveLength(1);+ });++ it("distributes an uneven trace budget so the first services get the remainder", async () => {+ const requested: Record<string, number> = {};+ const source = {+ discoverServices: async () => [+ { serviceName: "a", environment: "default", clusterId: "default" },+ { serviceName: "b", environment: "default", clusterId: "default" },+ { serviceName: "c", environment: "default", clusterId: "default" },+ ],+ sampleTracesForGraph: async (q: OpenLITQuery, limit: number) => {+ const value = String(+ (q.filters || []).find((f) => f.key === "service.name")?.value || ""+ );+ requested[value] = limit;+ return [];+ },+ };++ await fetchSpansForAggregation(source, windowQuery, {+ maxTraces: 10,+ skipCache: true,+ });++ expect(requested).toEqual({ a: 4, b: 3, c: 3 });+ });++ it("treats an explicit meta.truncated flag as truncated regardless of row count", async () => {+ const source = {+ listSpans: async () => ({+ fields: [],+ rows: [span({ spanId: "1", parentSpanId: "not-a-root" })],+ meta: { truncated: true },+ }),+ };++ const result = await fetchSpansForAggregation(source, windowQuery, {+ skipCache: true,+ });++ expect(result.truncated).toBe(true);+ });++ it("defaults listSpans rows to [] when the frame omits rows", async () => {+ const source = {+ listSpans: async () => ({ fields: [] }) as unknown as {+ fields: never[];+ rows: NormalizedSpan[];+ },+ };++ const result = await fetchSpansForAggregation(source, windowQuery, {+ skipCache: true,+ });++ expect(result.spans).toEqual([]);+ });++ it("falls back to AGGREGATE_SAMPLE_TRACE_CAP when neither opts.maxTraces nor query.limit is set", async () => {+ let receivedLimit: number | undefined;+ const source = {+ sampleTracesForGraph: async (_q: OpenLITQuery, limit: number) => {+ receivedLimit = limit;+ return [];+ },+ };+ const { limit: _omit, ...queryWithoutLimit } = windowQuery;++ await fetchSpansForAggregation(source, queryWithoutLimit, { skipCache: true });++ expect(receivedLimit).toBe(200);+ });++ it("falls back to DEFAULT_SAMPLE_TRACE_CAP for fetchSpansForList when nothing else is set", async () => {+ const source = {+ sampleTracesForGraph: async () => [span({ spanId: "1" })],+ };+ const { limit: _omit, ...queryWithoutLimit } = windowQuery;++ const result = await fetchSpansForList(source, queryWithoutLimit, {+ skipCache: true,+ });++ expect(result.spans).toHaveLength(1);+ });++ it("uses query.limit for fetchSpansForList maxRows when opts.maxRows is not set", async () => {+ const source = {+ sampleTracesForGraph: async () => [+ span({ spanId: "1" }),+ span({ spanId: "2", traceId: "t2" }),+ ],+ };++ const result = await fetchSpansForList(+ source,+ { ...windowQuery, limit: 1 },+ { skipCache: true }+ );++ expect(result.spans.length).toBeLessThanOrEqual(1);+ });+});++describe("pickRootSpan", () => {+ it("returns undefined for an empty span list", () => {+ expect(pickRootSpan([])).toBeUndefined();+ });++ it("falls back to the first span when none matches the root parent condition", () => {+ const a = span({ spanId: "a", parentSpanId: "not-a-root" });+ const b = span({ spanId: "b", parentSpanId: "also-not-a-root" });+ expect(pickRootSpan([a, b])).toBe(a);+ });++ it("matches the all-zero root parent id", () => {+ const zeroParent = span({+ spanId: "z",+ parentSpanId: "0".repeat(16),+ });+ const other = span({ spanId: "o", parentSpanId: "not-a-root" });+ expect(pickRootSpan([other, zeroParent])).toBe(zeroParent);+ });+});++describe("collapseToRootSpans", () => {+ it("skips spans without a traceId and sorts missing timestamps last", () => {+ const noTraceId = { ...span({ spanId: "no-trace" }), traceId: "" };+ const noTimestamp = {+ ...span({ spanId: "no-ts", traceId: "t-no-ts" }),+ timestamp: "",+ };+ const withTimestamp = span({+ spanId: "with-ts",+ traceId: "t-with-ts",+ timestamp: "2026-07-11T12:00:00.000Z",+ });++ const roots = collapseToRootSpans([noTraceId, noTimestamp, withTimestamp]);++ expect(roots.map((r) => r.spanId)).toEqual(["with-ts", "no-ts"]);+ });++ it("sorts consistently when the missing-timestamp span is compared first", () => {+ const noTimestampFirst = {+ ...span({ spanId: "no-ts-1", traceId: "t-a" }),+ timestamp: "",+ };+ const noTimestampSecond = {+ ...span({ spanId: "no-ts-2", traceId: "t-b" }),+ timestamp: "",+ };++ const roots = collapseToRootSpans([noTimestampFirst, noTimestampSecond]);++ expect(roots.map((r) => r.spanId).sort()).toEqual(["no-ts-1", "no-ts-2"]);+ });});diff --git a/src/client/src/__tests__/lib/platform/datasource/secret.test.ts b/src/client/src/__tests__/lib/platform/datasource/secret.test.tsindex ab515556..dc99344a 100644--- a/src/client/src/__tests__/lib/platform/datasource/secret.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/secret.test.ts@@ -1,7 +1,10 @@import {__resetSourceSecretCacheForTests,+ invalidateSourceSecretCache,+ redactableSecretValues,resolveSourceSecret,} from "@/lib/platform/connectors/datasource/http/secret";+import { encryptValue } from "@/utils/crypto";jest.mock("@/lib/platform/vault", () => ({getSecretById: jest.fn(),@@ -79,6 +82,31 @@ describe("resolveSourceSecret", () => {.rejects.toThrow(/could not be loaded from the OpenLIT vault/i);});+ it("reports the secret as not found when the vault returns no rows", async () => {+ (getSecretById as jest.Mock).mockResolvedValue({ data: [] });+ await expect(resolveSourceSecret("sec-empty")).rejects.toThrow(+ /missing from the OpenLIT vault/i+ );+ });++ it("reports the secret as not found when the row's value is an empty string", async () => {+ (getSecretById as jest.Mock).mockResolvedValue({+ data: [{ value: "" }],+ });+ await expect(resolveSourceSecret("sec-empty-value")).rejects.toThrow(+ /missing from the OpenLIT vault/i+ );+ });++ it("reports the secret as not found when the row's value is not a string", async () => {+ (getSecretById as jest.Mock).mockResolvedValue({+ data: [{ value: 12345 as unknown as string }],+ });+ await expect(resolveSourceSecret("sec-non-string-value")).rejects.toThrow(+ /missing from the OpenLIT vault/i+ );+ });+it("treats a non-JSON vault value as a bearer token", async () => {(getSecretById as jest.Mock).mockResolvedValue({data: [{ value: "opaque-token" }],@@ -107,4 +135,118 @@ describe("resolveSourceSecret", () => {expect(getSecretById).toHaveBeenCalledTimes(2);dateNow.mockRestore();});++ it("re-queries the vault after invalidating a specific secretRef's cache entry", async () => {+ (getSecretById as jest.Mock).mockResolvedValue({+ data: [{ value: '{"token":"first"}' }],+ });+ const first = await resolveSourceSecret("sec-invalidate");+ expect(first.credentials).toEqual({ token: "first" });+ expect(getSecretById).toHaveBeenCalledTimes(1);++ // Cache hit: no additional vault query.+ await resolveSourceSecret("sec-invalidate");+ expect(getSecretById).toHaveBeenCalledTimes(1);++ invalidateSourceSecretCache("sec-invalidate");++ (getSecretById as jest.Mock).mockResolvedValue({+ data: [{ value: '{"token":"second"}' }],+ });+ const second = await resolveSourceSecret("sec-invalidate");+ expect(second.credentials).toEqual({ token: "second" });+ expect(getSecretById).toHaveBeenCalledTimes(2);+ });++ it("leaves unrelated cache entries untouched when invalidating one secretRef", async () => {+ (getSecretById as jest.Mock).mockResolvedValue({+ data: [{ value: '{"token":"keep-me"}' }],+ });+ await resolveSourceSecret("sec-keep");+ invalidateSourceSecretCache("sec-unrelated");++ // Still cached: no additional vault query for the untouched ref.+ await resolveSourceSecret("sec-keep");+ expect(getSecretById).toHaveBeenCalledTimes(1);+ });++ it("fails closed when an inline encrypted secretRef cannot be decrypted", async () => {+ await expect(+ resolveSourceSecret("enc:v1:iv:tag:ciphertext")+ ).rejects.toThrow(/could not be decrypted/i);+ expect(getSecretById).not.toHaveBeenCalled();+ });++ it("decrypts an inline encrypted secretRef without querying the vault", async () => {+ const previous = process.env.NEXTAUTH_SECRET;+ process.env.NEXTAUTH_SECRET = "test-only-encryption-secret";+ try {+ const encryptedRef = encryptValue(+ JSON.stringify({ token: "direct-vault-value" })+ );+ const secret = await resolveSourceSecret(encryptedRef);+ expect(secret.credentials).toEqual({ token: "direct-vault-value" });+ expect(getSecretById).not.toHaveBeenCalled();+ } finally {+ if (previous === undefined) delete process.env.NEXTAUTH_SECRET;+ else process.env.NEXTAUTH_SECRET = previous;+ }+ });++ it("fails locally when the vault lookup throws and there is no usable stale cache", async () => {+ (getSecretById as jest.Mock).mockRejectedValueOnce(+ new Error("ECONNRESET")+ );+ await expect(resolveSourceSecret("sec-throws")).rejects.toThrow(+ /could not be loaded from the OpenLIT vault/i+ );+ });++ it("serves the stale cache when a rejected vault promise follows a prior hit", async () => {+ const now = Date.now();+ const dateNow = jest.spyOn(Date, "now").mockReturnValue(now);+ (getSecretById as jest.Mock).mockResolvedValueOnce({+ data: [{ value: JSON.stringify({ token: "fresh-reject" }) }],+ });+ const first = await resolveSourceSecret("sec-stale-reject");+ expect(first.credentials).toEqual({ token: "fresh-reject" });++ dateNow.mockReturnValue(now + 3 * 60_000);+ (getSecretById as jest.Mock).mockRejectedValueOnce(+ new Error("vault outage")+ );+ const second = await resolveSourceSecret("sec-stale-reject");+ expect(second.credentials).toEqual({ token: "fresh-reject" });+ dateNow.mockRestore();+ });+});++describe("redactableSecretValues", () => {+ it("collects the raw secret and every credential value", () => {+ const values = redactableSecretValues({+ raw: '{"token":"abc"}',+ credentials: { token: "abc", extra: "def" },+ });+ expect(values.sort()).toEqual(['{"token":"abc"}', "abc", "def"].sort());+ });++ it("de-duplicates repeated values across raw and credentials", () => {+ const values = redactableSecretValues({+ raw: "shared-value",+ credentials: { a: "shared-value", b: "shared-value" },+ });+ expect(values).toEqual(["shared-value"]);+ });++ it("skips falsy raw and falsy credential values", () => {+ const values = redactableSecretValues({+ raw: "",+ credentials: { empty: "", present: "value" },+ });+ expect(values).toEqual(["value"]);+ });++ it("returns an empty array when there is nothing to redact", () => {+ expect(redactableSecretValues({ raw: "", credentials: {} })).toEqual([]);+ });});diff --git a/src/client/src/__tests__/lib/platform/evaluation/evaluation-config.test.ts b/src/client/src/__tests__/lib/platform/evaluation/evaluation-config.test.tsindex c20a653d..13a63406 100644--- a/src/client/src/__tests__/lib/platform/evaluation/evaluation-config.test.ts+++ b/src/client/src/__tests__/lib/platform/evaluation/evaluation-config.test.ts@@ -64,7 +64,7 @@ jest.mock('path', () => ({dirname: jest.fn((p: string) => p.split('/').slice(0, -1).join('/')),}));-import { getEvaluationConfig, setEvaluationConfig, getEvaluationConfigById, restoreEvaluationCronJobs } from '@/lib/platform/evaluation/config';+import { getEvaluationConfig, setEvaluationConfig, getEvaluationConfigById, getEvaluationConfigByDbConfigId, restoreEvaluationCronJobs } from '@/lib/platform/evaluation/config';import { normalizeThresholdScore } from '@/lib/platform/evaluation/threshold';import { getEvaluationTypeDefaultPrompts } from '@/lib/platform/evaluation/evaluation-type-defaults';import { getDBConfigByUser } from '@/lib/db-config';@@ -208,6 +208,18 @@ describe('getEvaluationConfig', () => {secret: mockSecret,});});++ it('defaults meta to an empty object when config.meta is undefined', async () => {+ const configWithoutMeta = { ...makeMockEvalConfig(), meta: undefined };+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, mockDBConfig])+ .mockResolvedValueOnce([null, configWithoutMeta]);++ const result = await getEvaluationConfig();++ expect(result.evaluationTypes).toBeDefined();+ expect(result.evaluationTypes!.length).toBeGreaterThan(0);+ });});// ---------------------------------------------------------------------------@@ -380,6 +392,61 @@ describe('setEvaluationConfig', () => {);});+ it('defaults previousMeta to an empty object when previousConfig.meta is undefined', async () => {+ const previousConfig = { ...makeMockEvalConfig(), meta: undefined };+ const inputConfig = {+ id: 'eval-cfg-1',+ auto: false,+ recurringTime: '',+ meta: JSON.stringify({ engine: 'new-engine' }),+ };+ const updatedRecord = { ...previousConfig, ...inputConfig };++ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, mockDBConfig])+ .mockResolvedValueOnce([null, previousConfig])+ .mockResolvedValueOnce([null, updatedRecord]);++ await setEvaluationConfig(inputConfig as any, 'http://api.example.com');++ expect(prisma.evaluationConfigs.update).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ meta: expect.stringContaining('"engine":"new-engine"'),+ }),+ })+ );+ });++ it('defaults incoming meta to an empty object when evaluationConfig.meta is undefined', async () => {+ const previousConfig = {+ ...makeMockEvalConfig(),+ meta: JSON.stringify({ cronJobId: 'existing-cron', engine: 'old-engine' }),+ };+ const inputConfig = {+ id: 'eval-cfg-1',+ auto: false,+ recurringTime: '',+ meta: undefined,+ };+ const updatedRecord = { ...previousConfig, ...inputConfig };++ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, mockDBConfig])+ .mockResolvedValueOnce([null, previousConfig])+ .mockResolvedValueOnce([null, updatedRecord]);++ await setEvaluationConfig(inputConfig as any, 'http://api.example.com');++ expect(prisma.evaluationConfigs.update).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ meta: expect.stringContaining('"engine":"old-engine"'),+ }),+ })+ );+ });+it('merges incoming meta with previous meta on update', async () => {const previousConfig = {...makeMockEvalConfig(),@@ -467,6 +534,77 @@ describe('getEvaluationConfigById', () => {expect(result.secret).toEqual({});});++ it('defaults meta to an empty object when config.meta is undefined', async () => {+ const configWithoutMeta = { ...makeMockEvalConfig(), meta: undefined };+ (asaw as jest.Mock).mockResolvedValueOnce([null, configWithoutMeta]);++ const result = await getEvaluationConfigById('eval-cfg-1');++ expect(result.evaluationTypes).toBeDefined();+ expect(result.evaluationTypes!.length).toBeGreaterThan(0);+ });+});++// ---------------------------------------------------------------------------+// getEvaluationConfigByDbConfigId+// ---------------------------------------------------------------------------++describe('getEvaluationConfigByDbConfigId', () => {+ it('throws EVALUATION_CONFIG_NOT_FOUND when config not found', async () => {+ (asaw as jest.Mock).mockResolvedValueOnce([null, null]);++ await expect(getEvaluationConfigByDbConfigId('db-1')).rejects.toThrow(+ 'Eval config not found'+ );+ });++ it('throws EVALUATION_VAULT_SECRET_NOT_FOUND when secret not found', async () => {+ (asaw as jest.Mock).mockResolvedValueOnce([null, makeMockEvalConfig()]);+ (getSecretById as jest.Mock).mockResolvedValue({ data: [] });++ await expect(getEvaluationConfigByDbConfigId('db-1')).rejects.toThrow(+ 'Vault secret not found'+ );+ });++ it('returns full config with secret and evaluationTypes when found', async () => {+ (asaw as jest.Mock).mockResolvedValueOnce([null, makeMockEvalConfig()]);+ (getSecretById as jest.Mock).mockResolvedValue({ data: [mockSecret] });++ const result = await getEvaluationConfigByDbConfigId('db-1');++ expect(getSecretById).toHaveBeenCalledWith('vault-1', 'db-1', true);+ expect(result).toMatchObject({+ id: 'eval-cfg-1',+ vaultId: 'vault-1',+ databaseConfigId: 'db-1',+ secret: mockSecret,+ });+ expect(result.evaluationTypes).toBeDefined();+ });++ it('passes through excludeVaultValue=false to getSecretById', async () => {+ const secretWithValue = { ...mockSecret, value: 'sk-actual-key' };+ (asaw as jest.Mock).mockResolvedValueOnce([null, makeMockEvalConfig()]);+ (getSecretById as jest.Mock).mockResolvedValue({ data: [secretWithValue] });++ const result = await getEvaluationConfigByDbConfigId('db-1', false);++ expect(getSecretById).toHaveBeenCalledWith('vault-1', 'db-1', false);+ expect(result.secret).toEqual(secretWithValue);+ });++ it('defaults meta to an empty object when config.meta is undefined', async () => {+ const configWithoutMeta = { ...makeMockEvalConfig(), meta: undefined };+ (asaw as jest.Mock).mockResolvedValueOnce([null, configWithoutMeta]);+ (getSecretById as jest.Mock).mockResolvedValue({ data: [mockSecret] });++ const result = await getEvaluationConfigByDbConfigId('db-1');++ expect(result.evaluationTypes).toBeDefined();+ expect(result.evaluationTypes!.length).toBeGreaterThan(0);+ });});// ---------------------------------------------------------------------------@@ -984,4 +1122,21 @@ describe('restoreEvaluationCronJobs', () => {expect(errorSpy).toHaveBeenCalledWith('Failed to restore evaluation cron jobs:', expect.any(Error));errorSpy.mockRestore();});++ it('defaults meta to an empty object when config.meta is undefined, skipping the config', async () => {+ const mockUpdateCrontab = jest.fn();+ (Cron as unknown as jest.Mock).mockImplementation(() => ({+ validateCronSchedule: jest.fn(),+ updateCrontab: mockUpdateCrontab,+ deleteCronJob: jest.fn(),+ }));++ (prisma.evaluationConfigs.findMany as jest.Mock).mockResolvedValue([+ { id: 'cfg-no-meta', recurringTime: '0 * * * *', meta: undefined },+ ]);++ await restoreEvaluationCronJobs('http://localhost:3000');++ expect(mockUpdateCrontab).not.toHaveBeenCalled();+ });});diff --git a/src/client/src/__tests__/lib/platform/evaluation/evaluation.test.ts b/src/client/src/__tests__/lib/platform/evaluation/evaluation.test.tsindex 1c87395e..2b94c366 100644--- a/src/client/src/__tests__/lib/platform/evaluation/evaluation.test.ts+++ b/src/client/src/__tests__/lib/platform/evaluation/evaluation.test.ts@@ -88,8 +88,12 @@ jest.mock('@/lib/platform/evaluation/evaluation-type-defaults', () => ({getEvaluationTypeDefaultPrompts: jest.fn().mockResolvedValue({}),getEvaluationTypeDefaultPrompt: jest.fn().mockResolvedValue(undefined),}));+// Used only by runOfflineEvaluation's attribute-based rule-context lookup.+jest.mock('@/lib/platform/rule-engine/evaluate', () => ({+ evaluateRules: jest.fn(),+}));-import { getEvaluationsForSpanId, getEvaluationDetectedByType, autoEvaluate, setEvaluationsForSpanId, getEvaluationSummaryForSpanId, storeManualFeedback, extractEvalPromptCompletion } from '@/lib/platform/evaluation/index';+import { getEvaluationsForSpanId, getEvaluationDetectedByType, autoEvaluate, setEvaluationsForSpanId, getEvaluationSummaryForSpanId, storeManualFeedback, extractEvalPromptCompletion, runOfflineEvaluation } from '@/lib/platform/evaluation/index';import { dataCollector } from '@/lib/platform/common';import { getCurrentUser } from '@/lib/session';import { getEvaluationConfig, getEvaluationConfigById } from '@/lib/platform/evaluation/config';@@ -100,6 +104,7 @@ import { getRequestViaSpanId } from '@/lib/platform/request';import asaw from '@/utils/asaw';import { runEvaluation } from '@/lib/platform/evaluation/run-evaluation';import { CronRunStatus } from '@/types/cron';+import { evaluateRules } from '@/lib/platform/rule-engine/evaluate';beforeEach(() => {jest.clearAllMocks();@@ -120,6 +125,8 @@ beforeEach(() => {});// Default runEvaluation success(runEvaluation as jest.Mock).mockResolvedValue({ success: true, result: [] });+ (evaluateRules as jest.Mock).mockReset();+ (evaluateRules as jest.Mock).mockResolvedValue({ matchingRuleIds: [], entities: [] });});describe('getEvaluationsForSpanId', () => {@@ -178,6 +185,89 @@ describe('getEvaluationsForSpanId', () => {const result = await getEvaluationsForSpanId('span-1');expect(result.err).toBe('Python error occurred');});++ it('logs the traceId and environment from opts instead of falling back to null', async () => {+ const { consoleLog } = require('@/utils/log');+ (dataCollector as jest.Mock).mockResolvedValue({ data: [], err: null });+ (asaw as jest.Mock).mockResolvedValueOnce([null, { id: 'cfg-1' }]);++ await getEvaluationsForSpanId('span-1', { traceId: 'trace-99', environment: 'staging' });++ expect(consoleLog).toHaveBeenCalledWith(+ '[evaluation] load span evaluations',+ expect.objectContaining({ traceId: 'trace-99', environment: 'staging' })+ );+ expect(consoleLog).toHaveBeenCalledWith(+ '[evaluation] trace lookup for evaluation',+ expect.objectContaining({ traceId: 'trace-99' })+ );+ });++ it('falls back to an empty array when dataCollector returns null data', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: null, err: null });+ (asaw as jest.Mock).mockResolvedValueOnce([null, { id: 'cfg-1' }]);++ const result = await getEvaluationsForSpanId('span-1');+ expect(result.config).toBe('cfg-1');+ });++ it('defaults contextEntityIds to an empty array when the rule engine omits the field (no prior evaluations)', async () => {+ const { getContextFromRuleEngineForTrace } = require('@/lib/platform/evaluation/rule-engine-context');+ (getContextFromRuleEngineForTrace as jest.Mock).mockResolvedValueOnce({+ contextContents: [],+ matchingRuleIds: ['r1'],+ });+ (dataCollector as jest.Mock).mockResolvedValue({ data: [], err: null });+ (asaw as jest.Mock).mockResolvedValueOnce([null, { id: 'cfg-1', databaseConfigId: 'db-1' }]);+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: { SpanId: 'span-1' } });++ const result = await getEvaluationsForSpanId('span-1');+ expect(result.ruleContext?.contextEntityIds).toEqual([]);+ expect(result.ruleContext?.contextApplied).toBe(true);+ });++ it('defaults contextEntityIds to an empty array when the rule engine omits the field (prior evaluations exist)', async () => {+ const { getContextFromRuleEngineForTrace } = require('@/lib/platform/evaluation/rule-engine-context');+ (getContextFromRuleEngineForTrace as jest.Mock).mockResolvedValueOnce({+ contextContents: [],+ matchingRuleIds: ['r1'],+ });+ const evalRecord = { spanId: 'span-1', evaluations: [], id: 'eval-1', createdAt: new Date(), meta: {} };+ (dataCollector as jest.Mock).mockResolvedValue({ data: [evalRecord], err: null });+ (asaw as jest.Mock).mockResolvedValueOnce([null, { id: 'cfg-1', databaseConfigId: 'db-1' }]);+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: { SpanId: 'span-1' } });++ const result = await getEvaluationsForSpanId('span-1');+ expect(result.ruleContext?.contextEntityIds).toEqual([]);+ });++ it('maps run meta/evaluations defaults and parses a numeric cost from prior evaluations', async () => {+ const evalRecordWithCost = {+ spanId: 'span-1',+ id: 'eval-1',+ createdAt: new Date(),+ meta: { cost: '0.0042' },+ evaluations: [{ evaluation: 'toxicity', score: 0.1, classification: 'low', explanation: 'ok', verdict: 'no' }],+ };+ const evalRecordNoMetaOrEvaluations = {+ spanId: 'span-1',+ id: 'eval-2',+ createdAt: new Date(),+ meta: undefined,+ evaluations: undefined,+ };+ (dataCollector as jest.Mock).mockResolvedValue({+ data: [evalRecordWithCost, evalRecordNoMetaOrEvaluations],+ err: null,+ });+ (asaw as jest.Mock).mockResolvedValueOnce([null, { id: 'cfg-1', databaseConfigId: 'db-1' }]);++ const result = await getEvaluationsForSpanId('span-1');+ expect(result.runs?.[0].cost).toBeCloseTo(0.0042);+ expect(result.runs?.[1].meta).toEqual({});+ expect(result.runs?.[1].evaluations).toEqual([]);+ expect(result.runs?.[1].cost).toBeUndefined();+ });});describe('getEvaluationDetectedByType', () => {@@ -203,6 +293,46 @@ describe('getEvaluationDetectedByType', () => {expect(query).toContain("verdict = 'yes'");expect(query).toContain('bias');});++ it('scopes the query to selectedConfig.serviceNames when provided as a non-empty array', async () => {+ const scopedParams = {+ ...params,+ selectedConfig: { serviceNames: ['svc-a', 'svc-b'] },+ };+ await getEvaluationDetectedByType(scopedParams as any, 'toxicity');+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).toContain("AND meta['service.name'] IN ('svc-a', 'svc-b')");+ });++ it('filters out non-string entries from selectedConfig.serviceNames', async () => {+ const scopedParams = {+ ...params,+ selectedConfig: { serviceNames: ['svc-a', 123, '', null] },+ };+ await getEvaluationDetectedByType(scopedParams as any, 'toxicity');+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).toContain("AND meta['service.name'] IN ('svc-a')");+ });++ it('does not scope by service name when selectedConfig.serviceNames is not an array', async () => {+ const scopedParams = {+ ...params,+ selectedConfig: { serviceNames: 'not-an-array' },+ };+ await getEvaluationDetectedByType(scopedParams as any, 'toxicity');+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).not.toContain("meta['service.name']");+ });++ it('does not scope by service name when selectedConfig.serviceNames is an empty array', async () => {+ const scopedParams = {+ ...params,+ selectedConfig: { serviceNames: [] },+ };+ await getEvaluationDetectedByType(scopedParams as any, 'toxicity');+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).not.toContain("meta['service.name']");+ });});describe('autoEvaluate', () => {@@ -585,6 +715,190 @@ describe('autoEvaluate', () => {expect(dataCollector).not.toHaveBeenCalled();});+ it('falls back to the raw thrown value when the traces adapter rejects with a non-Error', async () => {+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, { id: 'eval-cfg-1', databaseConfigId: 'db-1', provider: 'openai', model: 'gpt-4', secret: {} }])+ .mockResolvedValueOnce([null, { id: 'db-1' }]);+ (getTelemetryAdapterForDbConfig as jest.Mock).mockRejectedValue('plain rejection string');++ const result = await autoEvaluate(autoEvalConfig as any);+ expect(result.success).toBe(false);+ expect(String(result.err)).toContain('plain rejection string');+ });++ it('converts a Date lastRunTime into an ISO string for the built-in traces query', async () => {+ (getLastRunCronLogByCronId as jest.Mock).mockResolvedValue(new Date('2024-03-15T10:00:00.000Z'));+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, { id: 'eval-cfg-1', databaseConfigId: 'db-1', provider: 'openai', model: 'gpt-4', secret: {} }])+ .mockResolvedValueOnce([null, { id: 'db-1' }]);+ (dataCollector as jest.Mock).mockResolvedValue({ data: [], err: null });++ await autoEvaluate(autoEvalConfig as any);++ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).toContain('2024-03-15T10:00:00.000Z');+ });++ it('uses a Date lastRunTime as the listSpans time-range start for the routed traces connector', async () => {+ const listSpans = jest.fn().mockResolvedValue({ rows: [] });+ (getLastRunCronLogByCronId as jest.Mock).mockResolvedValue(new Date('2024-03-15T10:00:00.000Z'));+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, { id: 'eval-cfg-1', databaseConfigId: 'db-1', provider: 'openai', model: 'gpt-4', secret: {} }])+ .mockResolvedValueOnce([null, { id: 'db-1' }]);+ (getTelemetryAdapterForDbConfig as jest.Mock).mockResolvedValue({+ isBuiltIn: false,+ descriptor: { type: 'jaeger', isBuiltIn: false },+ adapter: { listSpans },+ });++ const result = await autoEvaluate(autoEvalConfig as any);++ expect(result.success).toBe(true);+ const [{ timeRange }] = listSpans.mock.calls[0];+ expect(timeRange.start).toEqual(new Date('2024-03-15T10:00:00.000Z'));+ });++ it('excludes handled span ids and returns them via the routed traces connector when loadAutoHandledSpanIds succeeds', async () => {+ const listSpans = jest.fn().mockResolvedValue({+ rows: [+ { spanId: 'handled-span', spanAttributes: {}, resourceAttributes: {} },+ { spanId: 'new-span', spanAttributes: {}, resourceAttributes: {} },+ ],+ });+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, { id: 'eval-cfg-1', databaseConfigId: 'db-1', provider: 'openai', model: 'gpt-4', secret: {} }])+ .mockResolvedValueOnce([null, { id: 'db-1' }]);+ (getTelemetryAdapterForDbConfig as jest.Mock).mockResolvedValue({+ isBuiltIn: false,+ descriptor: { type: 'jaeger', isBuiltIn: false },+ adapter: { listSpans },+ });+ // First dataCollector call is loadAutoHandledSpanIds' query.+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [{ span_id: 'handled-span' }], err: null })+ .mockResolvedValue({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({ success: true, result: [] });++ const result = await autoEvaluate(autoEvalConfig as any);++ expect(result.success).toBe(true);+ expect(runEvaluation).toHaveBeenCalledTimes(1);+ });++ it('treats loadAutoHandledSpanIds as returning an empty set when its query errors', async () => {+ const listSpans = jest.fn().mockResolvedValue({+ rows: [{ spanId: 'span-x', spanAttributes: {}, resourceAttributes: {} }],+ });+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, { id: 'eval-cfg-1', databaseConfigId: 'db-1', provider: 'openai', model: 'gpt-4', secret: {} }])+ .mockResolvedValueOnce([null, { id: 'db-1' }]);+ (getTelemetryAdapterForDbConfig as jest.Mock).mockResolvedValue({+ isBuiltIn: false,+ descriptor: { type: 'jaeger', isBuiltIn: false },+ adapter: { listSpans },+ });+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: null, err: 'query failed' })+ .mockResolvedValue({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({ success: true, result: [] });++ const result = await autoEvaluate(autoEvalConfig as any);++ expect(result.success).toBe(true);+ expect(runEvaluation).toHaveBeenCalledTimes(1);+ });++ it('treats loadAutoHandledSpanIds as returning an empty set when its query data is null', async () => {+ const listSpans = jest.fn().mockResolvedValue({+ rows: [{ spanId: 'span-y', spanAttributes: {}, resourceAttributes: {} }],+ });+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, { id: 'eval-cfg-1', databaseConfigId: 'db-1', provider: 'openai', model: 'gpt-4', secret: {} }])+ .mockResolvedValueOnce([null, { id: 'db-1' }]);+ (getTelemetryAdapterForDbConfig as jest.Mock).mockResolvedValue({+ isBuiltIn: false,+ descriptor: { type: 'jaeger', isBuiltIn: false },+ adapter: { listSpans },+ });+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: null, err: null })+ .mockResolvedValue({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({ success: true, result: [] });++ const result = await autoEvaluate(autoEvalConfig as any);++ expect(result.success).toBe(true);+ expect(runEvaluation).toHaveBeenCalledTimes(1);+ });++ it('falls back to an empty array when the built-in traces query returns null data', async () => {+ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, { id: 'eval-cfg-1', databaseConfigId: 'db-1', provider: 'openai', model: 'gpt-4', secret: {} }])+ .mockResolvedValueOnce([null, { id: 'db-1' }]);+ (dataCollector as jest.Mock).mockResolvedValue({ data: null, err: null });++ const result = await autoEvaluate(autoEvalConfig as any);++ expect(result.success).toBe(true);+ expect(runEvaluation).not.toHaveBeenCalled();+ });++ it('resolves the skipped trace service name from ResourceAttributes and omits an empty Timestamp', async () => {+ const evalConfig = {+ id: 'eval-cfg-1',+ databaseConfigId: 'db-1',+ provider: 'openai',+ model: 'gpt-4',+ secret: { value: 'sk-1' },+ meta: JSON.stringify({ evalSampleRate: 0 }),+ };+ const trace = {+ SpanId: 'span-skip-1',+ ResourceAttributes: { 'service.name': 'svc-from-resource' },+ SpanAttributes: {},+ };++ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, evalConfig])+ .mockResolvedValueOnce([null, { id: 'db-1' }]);+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [trace], err: null })+ .mockResolvedValue({ data: true, err: null });++ await autoEvaluate(autoEvalConfig as any);++ const skipInsertCall = (dataCollector as jest.Mock).mock.calls.find(+ ([params]) => params?.table === 'openlit_evaluation'+ );+ expect(skipInsertCall?.[0].values[0].meta).toMatchObject({+ 'service.name': 'svc-from-resource',+ traceTimeStamp: '',+ });+ });++ it('logs but does not fail the run when storing an auto-skip result errors', async () => {+ const evalConfig = {+ id: 'eval-cfg-1',+ databaseConfigId: 'db-1',+ provider: 'openai',+ model: 'gpt-4',+ secret: { value: 'sk-1' },+ meta: JSON.stringify({ evalSampleRate: 0 }),+ };+ const trace = { SpanId: 'span-skip-err', Timestamp: '2024-01-01', SpanAttributes: {} };++ (asaw as jest.Mock)+ .mockResolvedValueOnce([null, evalConfig])+ .mockResolvedValueOnce([null, { id: 'db-1' }]);+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [trace], err: null })+ .mockResolvedValue({ data: null, err: 'skip insert failed' });++ const result = await autoEvaluate(autoEvalConfig as any);++ expect(result.success).toBe(true);+ });+it('lists candidate spans from the routed traces connector', async () => {const listSpans = jest.fn().mockResolvedValue({rows: [{ spanId: 'jaeger-span', spanAttributes: {}, resourceAttributes: {} }],@@ -668,6 +982,36 @@ describe('setEvaluationsForSpanId', () => {const result = await setEvaluationsForSpanId('span-1');expect(result).toMatchObject({ success: false });});++ it('logs the traceId and environment from opts instead of falling back to null', async () => {+ const { consoleLog } = require('@/utils/log');+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: { SpanId: 'span-1' } });+ (getEvaluationConfig as jest.Mock).mockResolvedValue({+ id: 'cfg-1',+ provider: 'openai',+ model: 'gpt-4',+ secret: { value: 'sk-1' },+ databaseConfigId: 'db-1',+ });++ await setEvaluationsForSpanId('span-1', { traceId: 'trace-1', environment: 'prod' });++ expect(consoleLog).toHaveBeenCalledWith(+ '[evaluation] run evaluation',+ expect.objectContaining({ traceId: 'trace-1', environment: 'prod' })+ );+ expect(consoleLog).toHaveBeenCalledWith(+ '[evaluation] run trace lookup',+ expect.objectContaining({ traceId: 'trace-1' })+ );+ });++ it('throws with the trace lookup error string when the span is missing and traceResult.err is a string', async () => {+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: {}, err: 'Custom trace lookup failure' });+ await expect(setEvaluationsForSpanId('missing-span')).rejects.toThrow(+ 'Custom trace lookup failure'+ );+ });});describe('getEvaluationSummaryForSpanId', () => {@@ -765,6 +1109,32 @@ describe('storeManualFeedback', () => {const result = await storeManualFeedback('span-1', 'positive');expect(result).toMatchObject({ err: 'Insert failed' });});++ it('logs the traceId and environment from opts instead of falling back to null', async () => {+ const { consoleLog } = require('@/utils/log');+ (dataCollector as jest.Mock).mockResolvedValue({ data: true, err: null });++ await storeManualFeedback('span-1', 'positive', undefined, undefined, {+ traceId: 'trace-1',+ environment: 'prod',+ });++ expect(consoleLog).toHaveBeenCalledWith(+ '[evaluation] save manual feedback',+ expect.objectContaining({ traceId: 'trace-1', environment: 'prod' })+ );+ expect(consoleLog).toHaveBeenCalledWith(+ '[evaluation] feedback trace lookup',+ expect.objectContaining({ traceId: 'trace-1' })+ );+ });++ it('throws with the trace lookup error string when the span is missing and traceResult.err is a string', async () => {+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: {}, err: 'Custom trace lookup failure' });+ await expect(storeManualFeedback('missing-span', 'positive')).rejects.toThrow(+ 'Custom trace lookup failure'+ );+ });});describe('getEvaluationsForSpanId — feedback rows', () => {@@ -887,28 +1257,155 @@ describe('setEvaluationsForSpanId — evaluationTypes branches', () => {'db-1');});-});-describe('extractEvalPromptCompletion (attribute-first extraction)', () => {- it('prefers span attributes (gen_ai.input/output.messages)', () => {- const trace = {- SpanAttributes: {- 'gen_ai.input.messages': 'attr-prompt',- 'gen_ai.output.messages': 'attr-response',- },- // events would resolve via the mocked SpanAttributes.<key> path- prompt: 'event-prompt',- response: 'event-response',- };- expect(extractEvalPromptCompletion(trace)).toEqual({- prompt: 'attr-prompt',- response: 'attr-response',+ it('defaults priority to 0 for a legacy t.ruleId entry with no priority field', async () => {+ const { getContextFromRulesWithPriority } = require('@/lib/platform/evaluation/rule-engine-context');+ (getContextFromRulesWithPriority as jest.Mock).mockResolvedValue({ contextContents: [], matchingRuleIds: [], contextEntityIds: [] });++ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: { SpanId: 'span-1', SpanAttributes: {} } });+ (getEvaluationConfig as jest.Mock).mockResolvedValue({+ id: 'cfg-1', provider: 'openai', model: 'gpt-4', secret: { value: 'sk-1' }, databaseConfigId: 'db-1',+ evaluationTypes: [{ id: 'hallucination', enabled: true, ruleId: 'r-no-priority' }],});- });+ (runEvaluation as jest.Mock).mockResolvedValue({ success: true, result: [] });- it('falls back through legacy attribute keys', () => {- const trace = {- SpanAttributes: {+ await setEvaluationsForSpanId('span-1');+ expect(getContextFromRulesWithPriority).toHaveBeenCalledWith(+ expect.anything(),+ expect.arrayContaining([{ ruleId: 'r-no-priority', priority: 0 }]),+ 'db-1'+ );+ });++ it('defaults contextEntityIds to an empty array when getContextFromRulesWithPriority omits the field', async () => {+ const { getContextFromRulesWithPriority } = require('@/lib/platform/evaluation/rule-engine-context');+ (getContextFromRulesWithPriority as jest.Mock).mockResolvedValue({ contextContents: [], matchingRuleIds: ['r1'] });++ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: { SpanId: 'span-1', SpanAttributes: {} } });+ (getEvaluationConfig as jest.Mock).mockResolvedValue({+ id: 'cfg-1', provider: 'openai', model: 'gpt-4', secret: { value: 'sk-1' }, databaseConfigId: 'db-1',+ evaluationTypes: [{ id: 'hallucination', enabled: true, ruleId: 'r1' }],+ });+ (dataCollector as jest.Mock).mockResolvedValue({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({ success: true, result: [] });++ const result = await setEvaluationsForSpanId('span-1');+ expect(result).toMatchObject({ success: true });+ });++ it('defaults contextEntityIds to an empty array when getContextFromRuleEngineForTrace omits the field (no rules configured)', async () => {+ const { getContextFromRuleEngineForTrace } = require('@/lib/platform/evaluation/rule-engine-context');+ (getContextFromRuleEngineForTrace as jest.Mock).mockResolvedValueOnce({ contextContents: [], matchingRuleIds: [] });++ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: { SpanId: 'span-1', SpanAttributes: {} } });+ (getEvaluationConfig as jest.Mock).mockResolvedValue({+ id: 'cfg-1', provider: 'openai', model: 'gpt-4', secret: { value: 'sk-1' }, databaseConfigId: 'db-1',+ evaluationTypes: [{ id: 'hallucination', enabled: true }],+ });+ (dataCollector as jest.Mock).mockResolvedValue({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({ success: true, result: [] });++ const result = await setEvaluationsForSpanId('span-1');+ expect(result).toMatchObject({ success: true });+ });++ it('uses the default prompt when the evaluation type has no custom prompt', async () => {+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: { SpanId: 'span-1', SpanAttributes: {} } });+ (getEvaluationConfig as jest.Mock).mockResolvedValue({+ id: 'cfg-1', provider: 'openai', model: 'gpt-4', secret: { value: 'sk-1' }, databaseConfigId: 'db-1',+ evaluationTypes: [{ id: 'hallucination', enabled: true, defaultPrompt: 'default hallucination prompt' }],+ });+ (runEvaluation as jest.Mock).mockResolvedValue({ success: true, result: [] });++ await setEvaluationsForSpanId('span-1');+ expect(runEvaluation).toHaveBeenCalledWith(+ expect.objectContaining({ contexts: expect.stringContaining('default hallucination prompt') })+ );+ });++ it('includes a service.name meta field derived from the trace ServiceName', async () => {+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({+ record: { SpanId: 'span-1', ServiceName: 'my-app-service', SpanAttributes: {} },+ });+ (getEvaluationConfig as jest.Mock).mockResolvedValue({+ id: 'cfg-1', provider: 'openai', model: 'gpt-4', secret: { value: 'sk-1' }, databaseConfigId: 'db-1',+ evaluationTypes: [],+ });+ (dataCollector as jest.Mock).mockResolvedValue({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({ success: true, result: [] });++ await setEvaluationsForSpanId('span-1');++ const insertCall = (dataCollector as jest.Mock).mock.calls.find(+ ([params]) => params?.table === 'openlit_evaluation'+ );+ expect(insertCall?.[0].values[0].meta).toMatchObject({ 'service.name': 'my-app-service' });+ });++ it('sets a positive cost in stored meta when usage is returned and the model is priced', async () => {+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: { SpanId: 'span-1', SpanAttributes: {} } });+ (getEvaluationConfig as jest.Mock).mockResolvedValue({+ id: 'cfg-1', provider: 'openai', model: 'gpt-4', secret: { value: 'sk-1' }, databaseConfigId: 'db-1',+ evaluationTypes: [],+ });+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({+ data: [{ id: 'gpt-4', inputPricePerMToken: 5, outputPricePerMToken: 15 }],+ err: null,+ })+ .mockResolvedValueOnce({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({+ success: true,+ result: [],+ usage: { promptTokens: 1000, completionTokens: 500 },+ });++ await setEvaluationsForSpanId('span-1');++ const insertCall = (dataCollector as jest.Mock).mock.calls.find(+ ([params]) => params?.table === 'openlit_evaluation'+ );+ expect(Number(insertCall?.[0].values[0].meta.cost)).toBeGreaterThan(0);+ });++ it('defaults data.result to an empty array when storing evaluation results', async () => {+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: { SpanId: 'span-1', SpanAttributes: {} } });+ (getEvaluationConfig as jest.Mock).mockResolvedValue({+ id: 'cfg-1', provider: 'openai', model: 'gpt-4', secret: { value: 'sk-1' }, databaseConfigId: 'db-1',+ evaluationTypes: [],+ });+ (dataCollector as jest.Mock).mockResolvedValue({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({ success: true });++ const result = await setEvaluationsForSpanId('span-1');+ expect(result).toMatchObject({ success: true });+ const insertCall = (dataCollector as jest.Mock).mock.calls.find(+ ([params]) => params?.table === 'openlit_evaluation'+ );+ expect(insertCall?.[0].values[0]['evaluationData.evaluation']).toEqual([]);+ });+});++describe('extractEvalPromptCompletion (attribute-first extraction)', () => {+ it('prefers span attributes (gen_ai.input/output.messages)', () => {+ const trace = {+ SpanAttributes: {+ 'gen_ai.input.messages': 'attr-prompt',+ 'gen_ai.output.messages': 'attr-response',+ },+ // events would resolve via the mocked SpanAttributes.<key> path+ prompt: 'event-prompt',+ response: 'event-response',+ };+ expect(extractEvalPromptCompletion(trace)).toEqual({+ prompt: 'attr-prompt',+ response: 'attr-response',+ });+ });++ it('falls back through legacy attribute keys', () => {+ const trace = {+ SpanAttributes: {'gen_ai.prompt': 'legacy-prompt','gen_ai.completion': 'legacy-completion',},@@ -942,3 +1439,470 @@ describe('extractEvalPromptCompletion (attribute-first extraction)', () => {});});});++describe('runOfflineEvaluation', () => {+ const baseConfig = {+ provider: 'openai',+ model: 'gpt-4',+ secret: { value: 'sk-1' },+ evaluationTypes: [+ { id: 'hallucination', enabled: true, defaultPrompt: 'Check for hallucination' },+ { id: 'bias', enabled: false, defaultPrompt: 'Check for bias' },+ { id: 'toxicity', enabled: false, defaultPrompt: 'Check for toxicity' },+ { id: 'custom_check', enabled: true, prompt: 'Custom prompt check' },+ ],+ };++ const baseInput = { prompt: 'What is 2+2?', response: '4' };++ beforeEach(() => {+ (runEvaluation as jest.Mock).mockResolvedValue({ success: true, result: [] });+ (evaluateRules as jest.Mock).mockResolvedValue({ matchingRuleIds: [], entities: [] });+ (dataCollector as jest.Mock).mockResolvedValue({ data: [], err: null });+ });++ it('runs explicitly enabled evaluation types when evalTypes is not requested', async () => {+ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(result.success).toBe(true);+ expect(result.metadata?.evalTypesRun).toEqual(['hallucination', 'custom_check']);+ });++ it('filters to requested evalTypes when provided', async () => {+ const result = await runOfflineEvaluation(+ { ...baseInput, evalTypes: ['bias'] },+ baseConfig as any,+ 'db-1'+ );+ expect(result.success).toBe(true);+ expect(result.metadata?.evalTypesRun).toEqual(['bias']);+ });++ it('falls back to default hallucination/bias/toxicity when no types are enabled and none requested', async () => {+ const configAllDisabled = {+ ...baseConfig,+ evaluationTypes: [+ { id: 'hallucination', enabled: false },+ { id: 'bias', enabled: false },+ { id: 'toxicity', enabled: false },+ { id: 'custom', enabled: false },+ ],+ };+ const result = await runOfflineEvaluation(baseInput, configAllDisabled as any, 'db-1');+ expect([...(result.metadata?.evalTypesRun || [])].sort()).toEqual([+ 'bias',+ 'hallucination',+ 'toxicity',+ ]);+ });++ it('returns a failure without calling runEvaluation when requested evalTypes contains an unknown id', async () => {+ const result = await runOfflineEvaluation(+ { ...baseInput, evalTypes: ['nonexistent'] },+ baseConfig as any,+ 'db-1'+ );+ expect(result.success).toBe(false);+ expect(result.error).toBe('Unknown eval types: nonexistent');+ expect(runEvaluation).not.toHaveBeenCalled();+ });++ it('resolves context from attributes via the rule engine and extracts entity ids', async () => {+ (evaluateRules as jest.Mock).mockResolvedValue({+ matchingRuleIds: ['r1'],+ entities: [],+ entity_data: { 'context:ctx-1': { content: 'attribute-derived context' } },+ });+ const result = await runOfflineEvaluation(+ { ...baseInput, attributes: { 'service.name': 'my-svc' } },+ baseConfig as any,+ 'db-1'+ );+ expect(evaluateRules).toHaveBeenCalledWith(+ {+ fields: { 'service.name': 'my-svc' },+ entity_type: 'context',+ include_entity_data: true,+ },+ 'db-1'+ );+ expect(result.contextApplied?.ruleMatched).toBe(true);+ expect(result.contextApplied?.matchingRuleIds).toEqual(['r1']);+ expect(result.contextApplied?.contextEntityIds).toEqual(['ctx-1']);+ });++ it('skips the rule engine lookup entirely when attributes is empty', async () => {+ await runOfflineEvaluation({ ...baseInput, attributes: {} }, baseConfig as any, 'db-1');+ expect(evaluateRules).not.toHaveBeenCalled();+ });++ it('skips the rule engine lookup when attributes is not provided', async () => {+ await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(evaluateRules).not.toHaveBeenCalled();+ });++ it('continues with empty rule context when evaluateRules throws', async () => {+ (evaluateRules as jest.Mock).mockRejectedValue(new Error('rule engine down'));+ const result = await runOfflineEvaluation(+ { ...baseInput, attributes: { 'service.name': 'svc' } },+ baseConfig as any,+ 'db-1'+ );+ expect(result.success).toBe(true);+ expect(result.contextApplied?.matchingRuleIds).toEqual([]);+ expect(result.contextApplied?.contextEntityIds).toEqual([]);+ });++ it('gracefully handles entity_data entries whose key does not match the context: prefix', async () => {+ (evaluateRules as jest.Mock).mockResolvedValue({+ matchingRuleIds: ['r1'],+ entities: [],+ entity_data: { 'not-a-context-key': { content: 'still has content' } },+ });+ const result = await runOfflineEvaluation(+ { ...baseInput, attributes: { 'service.name': 'svc' } },+ baseConfig as any,+ 'db-1'+ );+ expect(result.success).toBe(true);+ expect(result.contextApplied?.contextEntityIds).toEqual([]);+ });++ it('skips entity_data entries without content', async () => {+ (evaluateRules as jest.Mock).mockResolvedValue({+ matchingRuleIds: [],+ entities: [],+ entity_data: { 'context:ctx-1': { content: '' } },+ });+ const result = await runOfflineEvaluation(+ { ...baseInput, attributes: { 'service.name': 'svc' } },+ baseConfig as any,+ 'db-1'+ );+ expect(result.contextApplied?.contextEntityIds).toEqual([]);+ });++ it('does nothing extra when evaluateRules resolves without entity_data', async () => {+ (evaluateRules as jest.Mock).mockResolvedValue({ matchingRuleIds: ['r1'], entities: [] });+ const result = await runOfflineEvaluation(+ { ...baseInput, attributes: { 'service.name': 'svc' } },+ baseConfig as any,+ 'db-1'+ );+ expect(result.contextApplied?.matchingRuleIds).toEqual(['r1']);+ expect(result.contextApplied?.contextEntityIds).toEqual([]);+ });++ it('appends user-supplied contexts and reports the user contexts count', async () => {+ const result = await runOfflineEvaluation(+ { ...baseInput, contexts: ['user ctx 1', 'user ctx 2'] },+ baseConfig as any,+ 'db-1'+ );+ expect(result.contextApplied?.userContextsCount).toBe(2);+ });++ it('defaults userContextsCount to 0 when contexts is not provided', async () => {+ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(result.contextApplied?.userContextsCount).toBe(0);+ });++ it('uses the custom prompt over the default prompt when both are present', async () => {+ await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(runEvaluation).toHaveBeenCalledWith(+ expect.objectContaining({ contexts: expect.stringContaining('Custom prompt check') })+ );+ });++ it('falls back to the default prompt when no custom prompt is set', async () => {+ await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(runEvaluation).toHaveBeenCalledWith(+ expect.objectContaining({ contexts: expect.stringContaining('Check for hallucination') })+ );+ });++ it('sends an empty contexts string when there are no prebuilt prompts or context contents', async () => {+ const configNoPrompts = {+ ...baseConfig,+ evaluationTypes: [{ id: 'hallucination', enabled: true }],+ };+ await runOfflineEvaluation(baseInput, configNoPrompts as any, 'db-1');+ expect(runEvaluation).toHaveBeenCalledWith(expect.objectContaining({ contexts: '' }));+ });++ it('returns failure without storing when runEvaluation reports failure', async () => {+ (runEvaluation as jest.Mock).mockResolvedValue({ success: false, error: 'Model unavailable' });+ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(result).toEqual({ success: false, error: 'Model unavailable' });+ expect(dataCollector).not.toHaveBeenCalled();+ });++ it('includes runId in stored meta and returned metadata when provided', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: true, err: null });+ const result = await runOfflineEvaluation(+ { ...baseInput, runId: 'run-123' },+ baseConfig as any,+ 'db-1'+ );+ expect(result.metadata?.runId).toBe('run-123');+ const [callArg] = (dataCollector as jest.Mock).mock.calls[0];+ expect(callArg.values[0].meta).toMatchObject({ runId: 'run-123' });+ });++ it('omits runId from returned metadata when not provided', async () => {+ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(result.metadata?.runId).toBeUndefined();+ });++ it('stringifies userMetadata entries into meta with a user_ prefix', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: true, err: null });+ await runOfflineEvaluation(+ { ...baseInput, metadata: { experimentId: 'exp-1', attempt: '2' } },+ baseConfig as any,+ 'db-1'+ );+ const [callArg] = (dataCollector as jest.Mock).mock.calls[0];+ expect(callArg.values[0].meta).toMatchObject({+ user_experimentId: 'exp-1',+ user_attempt: '2',+ });+ });++ it('does not add any user_ meta keys when userMetadata is not provided', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: true, err: null });+ await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ const [callArg] = (dataCollector as jest.Mock).mock.calls[0];+ const metaKeys = Object.keys(callArg.values[0].meta);+ expect(metaKeys.some((k) => k.startsWith('user_'))).toBe(false);+ });++ it('records usage token counts and estimates a positive cost when the model is found', async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({+ data: [+ {+ id: 'gpt-4',+ displayName: 'GPT-4',+ modelType: 'chat',+ contextWindow: 8192,+ inputPricePerMToken: 5,+ outputPricePerMToken: 15,+ cacheReadPricePerMToken: 0,+ cacheCreationPricePerMToken: 0,+ capabilities: [],+ },+ ],+ err: null,+ })+ .mockResolvedValueOnce({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({+ success: true,+ result: [],+ usage: { promptTokens: 1000, completionTokens: 500 },+ });++ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');++ expect(result.success).toBe(true);+ expect(result.metadata?.usage).toEqual({ promptTokens: 1000, completionTokens: 500 });+ expect(result.metadata?.cost).toBeGreaterThan(0);+ const [callArg] = (dataCollector as jest.Mock).mock.calls[1];+ expect(callArg.values[0].meta).toMatchObject({ promptTokens: '1000', completionTokens: '500' });+ expect(Number(callArg.values[0].meta.cost)).toBeGreaterThan(0);+ });++ it('omits the cost meta field when the model is not found in Manage Models (cost is 0)', async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [], err: null })+ .mockResolvedValueOnce({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({+ success: true,+ result: [],+ usage: { promptTokens: 100, completionTokens: 50 },+ });++ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');++ expect(result.metadata?.cost).toBeUndefined();+ const [callArg] = (dataCollector as jest.Mock).mock.calls[1];+ expect(callArg.values[0].meta.cost).toBeUndefined();+ });++ it('skips cost estimation and stores no cost when databaseConfigId is empty', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({+ success: true,+ result: [],+ usage: { promptTokens: 100, completionTokens: 50 },+ });++ const result = await runOfflineEvaluation(baseInput, baseConfig as any, '');++ expect(result.metadata?.cost).toBeUndefined();+ // Only the storeEvaluation insert call — cost lookup is skipped entirely.+ expect(dataCollector).toHaveBeenCalledTimes(1);+ });++ it('still estimates a cost when only completionTokens is non-zero', async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({+ data: [+ {+ id: 'gpt-4',+ inputPricePerMToken: 5,+ outputPricePerMToken: 15,+ },+ ],+ err: null,+ })+ .mockResolvedValueOnce({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({+ success: true,+ result: [],+ usage: { promptTokens: 0, completionTokens: 500 },+ });++ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');++ expect(result.metadata?.cost).toBeGreaterThan(0);+ });++ it('still estimates a cost when only promptTokens is non-zero', async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({+ data: [+ {+ id: 'gpt-4',+ inputPricePerMToken: 5,+ outputPricePerMToken: 15,+ },+ ],+ err: null,+ })+ .mockResolvedValueOnce({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({+ success: true,+ result: [],+ usage: { promptTokens: 1000, completionTokens: 0 },+ });++ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');++ expect(result.metadata?.cost).toBeGreaterThan(0);+ });++ it('skips cost estimation entirely when both promptTokens and completionTokens are zero', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({+ success: true,+ result: [],+ usage: { promptTokens: 0, completionTokens: 0 },+ });++ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');++ expect(result.metadata?.cost).toBeUndefined();+ // Only the storeEvaluation insert call — cost lookup is skipped for zero usage.+ expect(dataCollector).toHaveBeenCalledTimes(1);+ });++ it('does not attempt cost estimation when usage is absent from the runEvaluation result', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: true, err: null });+ (runEvaluation as jest.Mock).mockResolvedValue({ success: true, result: [] });++ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');++ expect(result.metadata?.usage).toBeUndefined();+ expect(result.metadata?.cost).toBeUndefined();+ // Only the storeEvaluation insert call — no cost-lookup query call.+ expect(dataCollector).toHaveBeenCalledTimes(1);+ });++ it('stores results with an offline_-prefixed span id when storeResults is true (default)', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: true, err: null });+ await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ const [callArg] = (dataCollector as jest.Mock).mock.calls[0];+ expect(callArg.values[0].span_id).toMatch(/^offline_/);+ expect(callArg.values[0].meta).toMatchObject({ source: 'offline_sdk' });+ });++ it('does not call dataCollector to store results when storeResults is false', async () => {+ const result = await runOfflineEvaluation(+ { ...baseInput, storeResults: false },+ baseConfig as any,+ 'db-1'+ );+ expect(result.success).toBe(true);+ expect(dataCollector).not.toHaveBeenCalled();+ });++ it('logs but does not fail the overall result when storing offline results errors', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: null, err: 'Insert failed' });+ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(result.success).toBe(true);+ });++ it('defaults thresholdScore to 0.5 and includes it in the returned metadata', async () => {+ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(result.metadata?.thresholdScore).toBe(0.5);+ expect(runEvaluation).toHaveBeenCalledWith(expect.objectContaining({ thresholdScore: 0.5 }));+ });++ it('uses a caller-supplied thresholdScore when provided', async () => {+ const result = await runOfflineEvaluation(+ { ...baseInput, thresholdScore: 0.75 },+ baseConfig as any,+ 'db-1'+ );+ expect(result.metadata?.thresholdScore).toBe(0.75);+ expect(runEvaluation).toHaveBeenCalledWith(expect.objectContaining({ thresholdScore: 0.75 }));+ });++ it('returns a failure with the Error message when runEvaluation throws an Error', async () => {+ (runEvaluation as jest.Mock).mockRejectedValue(new Error('provider timeout'));+ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(result).toEqual({ success: false, error: 'provider timeout' });+ });++ it('returns a failure with a stringified error when runEvaluation throws a non-Error value', async () => {+ (runEvaluation as jest.Mock).mockRejectedValue('plain string failure');+ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(result).toEqual({ success: false, error: 'plain string failure' });+ });++ it('returns the evaluations array from a successful run', async () => {+ (runEvaluation as jest.Mock).mockResolvedValue({+ success: true,+ result: [+ { evaluation: 'hallucination', score: 0.1, classification: 'low', explanation: 'ok', verdict: 'no' },+ ],+ });+ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(result.evaluations).toEqual([+ { evaluation: 'hallucination', score: 0.1, classification: 'low', explanation: 'ok', verdict: 'no' },+ ]);+ });++ it('defaults evaluations to an empty array when runEvaluation returns no result', async () => {+ (runEvaluation as jest.Mock).mockResolvedValue({ success: true });+ const result = await runOfflineEvaluation(baseInput, baseConfig as any, 'db-1');+ expect(result.evaluations).toEqual([]);+ });++ it('falls back to hallucination/bias/toxicity when evaluationConfig.evaluationTypes is undefined', async () => {+ const configWithoutTypes = { provider: 'openai', model: 'gpt-4', secret: { value: 'sk-1' } };+ const result = await runOfflineEvaluation(baseInput, configWithoutTypes as any, 'db-1');+ expect(result.success).toBe(true);+ expect(result.metadata?.evalTypesRun).toEqual([]);+ });++ it('defaults matchingRuleIds to an empty array when evaluateRules resolves without the field', async () => {+ (evaluateRules as jest.Mock).mockResolvedValue({ entities: [] });+ const result = await runOfflineEvaluation(+ { ...baseInput, attributes: { 'service.name': 'svc' } },+ baseConfig as any,+ 'db-1'+ );+ expect(result.contextApplied?.matchingRuleIds).toEqual([]);+ expect(result.contextApplied?.ruleMatched).toBe(false);+ });+});diff --git a/src/client/src/__tests__/lib/platform/evaluation/sync-rule-entities.test.ts b/src/client/src/__tests__/lib/platform/evaluation/sync-rule-entities.test.tsindex dbe25973..497c3f2e 100644--- a/src/client/src/__tests__/lib/platform/evaluation/sync-rule-entities.test.ts+++ b/src/client/src/__tests__/lib/platform/evaluation/sync-rule-entities.test.ts@@ -229,6 +229,16 @@ describe("addRuleToEvaluationType", () => {expect(mockJsonParse).toHaveBeenCalledWith("{}");});++ it("defaults types to an empty array when meta has no evaluationTypes key", async () => {+ const config = { id: "cfg-1", meta: "{}" };+ mockAsaw.mockResolvedValueOnce([null, config]);+ mockJsonParse.mockReturnValue({});++ await addRuleToEvaluationType("rule-1", "type-1");++ expect(mockPrismaUpdate).not.toHaveBeenCalled();+ });});describe("removeRuleFromEvaluationType", () => {@@ -375,6 +385,17 @@ describe("removeRuleFromEvaluationType", () => {expect(mockPrismaUpdate).toHaveBeenCalled();});++ it("handles empty meta string by defaulting to empty object, resulting in no matching type", async () => {+ const config = { id: "cfg-1", meta: "" };+ mockAsaw.mockResolvedValueOnce([null, config]);+ mockJsonParse.mockReturnValue({});++ await removeRuleFromEvaluationType("rule-1", "type-1");++ expect(mockJsonParse).toHaveBeenCalledWith("{}");+ expect(mockPrismaUpdate).not.toHaveBeenCalled();+ });});describe("syncRuleEntitiesFromConfig", () => {@@ -433,6 +454,21 @@ describe("syncRuleEntitiesFromConfig", () => {expect(mockAddRuleEntity).not.toHaveBeenCalled();});+ it("defaults types to an empty array when meta has no evaluationTypes key, deleting all existing entities", async () => {+ const config = { id: "cfg-1", meta: "" };+ mockAsaw.mockResolvedValueOnce([null, config]);+ mockJsonParse.mockReturnValue({});+ const entities = [{ id: "entity-1", rule_id: "rule-1", entity_id: "type-1" }];+ mockGetRuleEntities.mockResolvedValue({ err: undefined, data: entities } as any);+ mockAsaw.mockResolvedValue([null, {}]);++ await syncRuleEntitiesFromConfig();++ expect(mockJsonParse).toHaveBeenCalledWith("{}");+ expect(mockDeleteRuleEntity).toHaveBeenCalledWith("entity-1", { emitAlert: false });+ expect(mockAddRuleEntity).not.toHaveBeenCalled();+ });+it("calls getRuleEntities with entity_type evaluation", async () => {const config = { id: "cfg-1", meta: '{}' };mockAsaw.mockResolvedValueOnce([null, config]);diff --git a/src/client/src/__tests__/lib/platform/generation-health/classify.test.ts b/src/client/src/__tests__/lib/platform/generation-health/classify.test.tsindex 7ae73c09..97ca4630 100644--- a/src/client/src/__tests__/lib/platform/generation-health/classify.test.ts+++ b/src/client/src/__tests__/lib/platform/generation-health/classify.test.ts@@ -1,12 +1,15 @@import {classifyFromNormalizedTrace,classifyGenerationHealth,+ finishReasonTokens,+ firstSpanMatchingGenerationHealth,isGenerationHealthChip,matchesGenerationHealthChip,normalizeModelName,parseGenerationHealthChips,percentOfEligible,listedSpansMatchingGenerationHealth,+ spanGenerationHealthAttrs,spanMatchesAnyGenerationHealthChip,hasGenerationHealthFilter,uniqueTraceCount,@@ -110,6 +113,36 @@ describe("classifyGenerationHealth", () => {expect(health.modelSwap).toBe(true);});+ it("returns defaults when attrs is undefined", () => {+ const health = classifyGenerationHealth(undefined);+ expect(health.finishReasonRaw).toBe("");+ expect(health.requestedModel).toBe("");+ expect(health.servedModel).toBe("");+ });++ it("treats a non-numeric output-tokens value as absent", () => {+ const health = classifyGenerationHealth({+ "gen_ai.usage.output_tokens": "not-a-number",+ });+ expect(health.hasOutputTokens).toBe(false);+ expect(health.outputTokens).toBeNull();+ });++ it("defaults an unrecognized finish reason token to ok", () => {+ const health = classifyGenerationHealth({+ "gen_ai.response.finish_reasons": "some_unrecognized_reason",+ "gen_ai.usage.output_tokens": "5",+ });+ expect(health.finishCategory).toBe("ok");+ });++ it("classifies as unknown when there is no finish reason and output tokens are absent", () => {+ const health = classifyGenerationHealth({});+ expect(health.finishCategory).toBe("unknown");+ expect(health.hasFinishReason).toBe(false);+ expect(health.hasOutputTokens).toBe(false);+ });+it("still matches empty when a truncated call has 0 output tokens", () => {const health = classifyGenerationHealth({"gen_ai.response.finish_reasons": "length",@@ -151,6 +184,60 @@ describe("helpers", () => {expect(normalizeModelName(" OpenAI/GPT-4o ")).toBe("gpt-4o");});+ it("tokenizes a raw finish reason string", () => {+ expect(finishReasonTokens("STOP")).toEqual(["stop"]);+ expect(finishReasonTokens("")).toEqual([]);+ });++ it("returns no tokens when the raw finish reason has no alphanumeric characters", () => {+ expect(finishReasonTokens("!!!")).toEqual([]);+ });++ it("merges resource and span attributes, spans winning on conflicts", () => {+ expect(+ spanGenerationHealthAttrs({+ resourceAttributes: { "service.name": "svc", shared: "resource" },+ spanAttributes: { "gen_ai.request.model": "gpt-4o", shared: "span" },+ })+ ).toEqual({+ "service.name": "svc",+ shared: "span",+ "gen_ai.request.model": "gpt-4o",+ });+ });++ it("defaults to an empty object when neither attribute bag is present", () => {+ expect(spanGenerationHealthAttrs({})).toEqual({});+ });++ it("finds the first span matching any selected chip", () => {+ const spans = [+ { traceId: "t-1", spanAttributes: { "http.method": "GET" } },+ {+ traceId: "t-1",+ spanAttributes: { "gen_ai.response.finish_reasons": "length" },+ },+ ];+ expect(firstSpanMatchingGenerationHealth(spans, ["truncated"])).toBe(+ spans[1]+ );+ });++ it("returns undefined from firstSpanMatchingGenerationHealth when no chips are selected", () => {+ expect(+ firstSpanMatchingGenerationHealth(+ [{ traceId: "t-1", spanAttributes: {} }],+ undefined+ )+ ).toBeUndefined();+ expect(+ firstSpanMatchingGenerationHealth(+ [{ traceId: "t-1", spanAttributes: {} }],+ []+ )+ ).toBeUndefined();+ });+it("parses chip lists", () => {expect(isGenerationHealthChip("truncated")).toBe(true);expect(isGenerationHealthChip("loop")).toBe(false);@@ -183,6 +270,26 @@ describe("helpers", () => {).toBe(true);});+ it("returns all spans unchanged when no chips are selected", () => {+ const spans = [{ traceId: "t-1", spanAttributes: {} }];+ expect(listedSpansMatchingGenerationHealth(spans, undefined)).toBe(spans);+ expect(listedSpansMatchingGenerationHealth(spans, [])).toBe(spans);+ });++ it("groups spans without a traceId under a per-index fallback key", () => {+ const listed = listedSpansMatchingGenerationHealth(+ [+ { spanAttributes: { "gen_ai.response.finish_reasons": "length" } },+ { spanAttributes: { "gen_ai.response.finish_reasons": "stop" } },+ ],+ ["truncated"]+ );+ expect(listed).toHaveLength(1);+ expect(listed[0]?.spanAttributes?.["gen_ai.response.finish_reasons"]).toBe(+ "length"+ );+ });+it("lists one matching span per trace", () => {const listed = listedSpansMatchingGenerationHealth([@@ -221,6 +328,10 @@ describe("helpers", () => {).toBe(2);});+ it("falls back to the raw span count when no span has a traceId", () => {+ expect(uniqueTraceCount([{}, {}, { traceId: "" }])).toBe(3);+ });+it("returns 0% when the eligible set is empty", () => {expect(percentOfEligible(4, 0)).toBe(0);expect(percentOfEligible(4, 8)).toBe(50);diff --git a/src/client/src/__tests__/lib/platform/gpu/external.test.ts b/src/client/src/__tests__/lib/platform/gpu/external.test.tsnew file mode 100644index 00000000..8e438e0d--- /dev/null+++ b/src/client/src/__tests__/lib/platform/gpu/external.test.ts@@ -0,0 +1,355 @@+const mockResolveDescriptor = jest.fn();+const mockGetAdapter = jest.fn();++jest.mock("@/lib/telemetry-source", () => ({+ resolveTelemetrySourceDescriptor: (...a: unknown[]) =>+ mockResolveDescriptor(...a),+ getTelemetryAdapter: (...a: unknown[]) => mockGetAdapter(...a),+}));++import {+ externalAverageUtilization,+ externalUtilizationParamsPerTime,+ externalAverageTemperature,+ externalAverageTemperatureParamsPerTime,+ externalAveragePowerDraw,+ externalPowerParamsPerTime,+ externalAverageMemoryUsage,+ externalMemoryParamsPerTime,+ externalFanspeedParamsPerTime,+} from "@/lib/platform/gpu/external";++const prometheus = {+ type: "prometheus",+ id: "src-prom",+ isBuiltIn: false,+ settings: {},+ signals: ["metrics"],+ name: "Prometheus",+ dbConfigId: "db-1",+};++const builtin = {+ type: "clickhouse",+ id: "builtin:db-1",+ isBuiltIn: true,+ settings: {},+ signals: ["metrics"],+ name: "CH",+ dbConfigId: "db-1",+};++const params = {+ timeLimit: {+ start: new Date("2026-07-01T00:00:00.000Z"),+ end: new Date("2026-07-01T01:00:00.000Z"),+ type: "CUSTOM",+ },+ limit: 10,+ offset: 0,+ selectedConfig: {},+};++beforeEach(() => {+ jest.clearAllMocks();+ mockResolveDescriptor.mockResolvedValue(prometheus);+});++describe("built-in ClickHouse routing", () => {+ it("returns null for every export on the built-in source", async () => {+ mockResolveDescriptor.mockResolvedValue(builtin);+ expect(await externalAverageUtilization(params)).toBeNull();+ expect(await externalUtilizationParamsPerTime(params)).toBeNull();+ expect(await externalAverageTemperature(params)).toBeNull();+ expect(await externalAverageTemperatureParamsPerTime(params)).toBeNull();+ expect(await externalAveragePowerDraw(params)).toBeNull();+ expect(await externalPowerParamsPerTime(params)).toBeNull();+ expect(await externalAverageMemoryUsage(params)).toBeNull();+ expect(await externalMemoryParamsPerTime(params)).toBeNull();+ expect(await externalFanspeedParamsPerTime(params)).toBeNull();+ expect(mockGetAdapter).not.toHaveBeenCalled();+ });++ it("returns null when the resolved type is clickhouse even if not flagged built-in", async () => {+ mockResolveDescriptor.mockResolvedValue({ ...prometheus, isBuiltIn: false, type: "clickhouse" });+ expect(await externalAverageUtilization(params)).toBeNull();+ });++ it("resolves the metrics adapter for an external source", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });+ await externalAverageUtilization(params);+ expect(mockGetAdapter).toHaveBeenCalledWith({ signal: "metrics", environment: undefined });+ });+});++describe("externalAverageUtilization", () => {+ it("averages utilization values and filters the metric name into the query", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({+ rows: [{ value: 10 }, { value: 20 }],+ });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalAverageUtilization(params);+ expect(res).toEqual({ err: null, data: [{ utilization: 15 }] });+ const query = metricTimeSeries.mock.calls[0][0];+ expect(query.filters).toEqual(+ expect.arrayContaining([+ { target: "spanName", op: "in", value: ["gpu.utilization"] },+ ])+ );+ expect(query.aggregations).toEqual([{ fn: "avg", as: "utilization" }]);+ });++ it("falls back to count when value is absent and rounds to two decimals", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({+ rows: [{ count: 1 }, { count: 2 }, { count: 3 }],+ });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalAverageUtilization(params);+ expect(res).toEqual({ err: null, data: [{ utilization: 2 }] });+ });++ it("ignores non-finite values and returns zero when nothing remains", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({+ rows: [{ value: Number.NaN }, { value: Number.POSITIVE_INFINITY }],+ });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalAverageUtilization(params);+ expect(res).toEqual({ err: null, data: [{ utilization: 0 }] });+ });++ it("defaults to zero when neither value nor count is present", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({ rows: [{}] });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalAverageUtilization(params);+ expect(res).toEqual({ err: null, data: [{ utilization: 0 }] });+ });++ it("returns zero for an empty row set", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalAverageUtilization(params);+ expect(res).toEqual({ err: null, data: [{ utilization: 0 }] });+ });++ it("returns a stringified error when the adapter throws a non-Error value", async () => {+ const metricTimeSeries = jest.fn().mockRejectedValue("boom");+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalAverageUtilization(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });++ it("returns the Error message when the adapter throws an Error", async () => {+ const metricTimeSeries = jest.fn().mockRejectedValue(new Error("prometheus down"));+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalAverageUtilization(params);+ expect(res).toEqual({ err: "prometheus down", data: [] });+ });+});++describe("externalUtilizationParamsPerTime", () => {+ it("buckets values per time by mapped metric key", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({+ rows: [+ { request_time: "00:00", metricName: "gpu.utilization", value: 10 },+ { request_time: "00:00", __name__: "gpu.enc.utilization", value: 20 },+ { request_time: "01:00", metricName: "gpu.dec.utilization", value: 30 },+ ],+ });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalUtilizationParamsPerTime(params);+ expect(res).toEqual({+ err: null,+ data: [+ { request_time: "00:00", utilization: 10, enc_utilization: 20 },+ { request_time: "01:00", dec_utilization: 30 },+ ],+ });+ });++ it("skips rows missing a time label or a finite value", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({+ rows: [+ { metricName: "gpu.utilization", value: 10 },+ { request_time: "00:00", metricName: "gpu.utilization", value: Number.NaN },+ { request_time: "00:00", metricName: "", value: 5 },+ { request_time: "00:00", value: 5 },+ ],+ });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalUtilizationParamsPerTime(params);+ expect(res).toEqual({ err: null, data: [] });+ });++ it("uses timestamp/label fallbacks for the time bucket key", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({+ rows: [{ timestamp: "t1", metricName: "gpu.utilization", value: 1 }],+ });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalUtilizationParamsPerTime(params);+ expect(res).toEqual({ err: null, data: [{ request_time: "t1", utilization: 1 }] });+ });++ it("returns an error payload on failure", async () => {+ const metricTimeSeries = jest.fn().mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalUtilizationParamsPerTime(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });+});++describe("externalAverageTemperature", () => {+ it("averages temperature values", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({ rows: [{ value: 50 }, { value: 60 }] });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalAverageTemperature(params);+ expect(res).toEqual({ err: null, data: [{ temperature: 55 }] });+ });+});++describe("externalAverageTemperatureParamsPerTime", () => {+ it("buckets temperature by time via bucketByTime", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({+ rows: [+ { request_time: "01:00", value: 70 },+ { request_time: "00:00", value: 50 },+ { request_time: "00:00", value: 60 },+ { label: "" },+ { timestamp: "02:00", value: 80 },+ { request_time: "02:00", value: Number.NaN },+ ],+ });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalAverageTemperatureParamsPerTime(params);+ expect(res).toEqual({+ err: null,+ data: [+ { request_time: "00:00", temperature: 55 },+ { request_time: "01:00", temperature: 70 },+ { request_time: "02:00", temperature: 80 },+ ],+ });+ });++ it("returns an error payload on failure", async () => {+ const metricTimeSeries = jest.fn().mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalAverageTemperatureParamsPerTime(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });+});++describe("externalAveragePowerDraw / externalPowerParamsPerTime", () => {+ it("averages power draw", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({ rows: [{ value: 100 }] });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalAveragePowerDraw(params);+ expect(res).toEqual({ err: null, data: [{ power_draw: 100 }] });+ });++ it("buckets power draw/limit series by mapped keys", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({+ rows: [+ { request_time: "00:00", metricName: "gpu.power.draw", value: 12.345 },+ { request_time: "00:00", metricName: "gpu.power.limit", value: 20 },+ ],+ });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalPowerParamsPerTime(params);+ expect(res).toEqual({+ err: null,+ data: [{ request_time: "00:00", power_draw: 12.345, power_limit: 20 }],+ });+ });++ it("returns an error payload on failure for power series", async () => {+ const metricTimeSeries = jest.fn().mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalPowerParamsPerTime(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });+});++describe("externalAverageMemoryUsage / externalMemoryParamsPerTime", () => {+ it("averages memory usage", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({ rows: [{ value: 40 }] });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalAverageMemoryUsage(params);+ expect(res).toEqual({ err: null, data: [{ memory_used: 40 }] });+ });++ it("buckets each memory series by mapped key", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({+ rows: [+ { request_time: "00:00", metricName: "gpu.memory.available", value: 1 },+ { request_time: "00:00", metricName: "gpu.memory.total", value: 2 },+ { request_time: "00:00", metricName: "gpu.memory.used", value: 3 },+ { request_time: "00:00", metricName: "gpu.memory.free", value: 4 },+ ],+ });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalMemoryParamsPerTime(params);+ expect(res).toEqual({+ err: null,+ data: [+ {+ request_time: "00:00",+ memory_available: 1,+ memory_total: 2,+ memory_used: 3,+ memory_free: 4,+ },+ ],+ });+ });++ it("returns an error payload on failure for memory series", async () => {+ const metricTimeSeries = jest.fn().mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalMemoryParamsPerTime(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });+});++describe("externalFanspeedParamsPerTime", () => {+ it("buckets fan speed values by time", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({+ rows: [+ { request_time: "00:00", value: 30 },+ { request_time: "00:00", value: 40 },+ ],+ });+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalFanspeedParamsPerTime(params);+ expect(res).toEqual({ err: null, data: [{ request_time: "00:00", fan_speed: 35 }] });+ });++ it("returns an error payload on failure", async () => {+ const metricTimeSeries = jest.fn().mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue({ metricTimeSeries });++ const res = await externalFanspeedParamsPerTime(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });+});diff --git a/src/client/src/__tests__/lib/platform/kubernetes.test.ts b/src/client/src/__tests__/lib/platform/kubernetes.test.tsindex f6252fcf..5c24a0b4 100644--- a/src/client/src/__tests__/lib/platform/kubernetes.test.ts+++ b/src/client/src/__tests__/lib/platform/kubernetes.test.ts@@ -114,6 +114,32 @@ describe("platform kubernetes helpers", () => {expect(consoleLog).toHaveBeenCalledWith({ body: { message: "already exists" } });});+ it("falls back to error.message when create failures have no body.message", async () => {+ mockCreateNamespacedCustomObject.mockRejectedValueOnce(+ new Error("connection refused")+ );++ await expect(+ createAgentInstrumentation({+ namespace: "default",+ serviceName: "api",+ })+ ).resolves.toEqual({ err: "connection refused" });+ });++ it("falls back to a default message when create failures have neither body.message nor message", async () => {+ mockCreateNamespacedCustomObject.mockRejectedValueOnce({});++ await expect(+ createAgentInstrumentation({+ namespace: "default",+ serviceName: "api",+ })+ ).resolves.toEqual({+ err: "Failed to create AutoInstrumentation CRD. Ensure the OpenLIT operator is installed and K8s access is configured.",+ });+ });+it("reads existing AutoInstrumentation custom objects", async () => {mockGetNamespacedCustomObject.mockResolvedValueOnce({ body: "found" });@@ -139,6 +165,45 @@ describe("platform kubernetes helpers", () => {});});+ it("maps a body.code 404 to exists=false when statusCode is not 404", async () => {+ mockGetNamespacedCustomObject.mockRejectedValueOnce({+ body: { code: 404 },+ });++ await expect(getAgentInstrumentation("default", "api")).resolves.toEqual({+ exists: false,+ });+ });++ it("returns body.message for non-404 get failures", async () => {+ mockGetNamespacedCustomObject.mockRejectedValueOnce({+ statusCode: 500,+ body: { message: "internal error" },+ });++ await expect(getAgentInstrumentation("default", "api")).resolves.toEqual({+ err: "internal error",+ });+ });++ it("falls back to error.message for non-404 get failures without body.message", async () => {+ mockGetNamespacedCustomObject.mockRejectedValueOnce(+ new Error("network unreachable")+ );++ await expect(getAgentInstrumentation("default", "api")).resolves.toEqual({+ err: "network unreachable",+ });+ });++ it("falls back to a default message for non-404 get failures with no message at all", async () => {+ mockGetNamespacedCustomObject.mockRejectedValueOnce({});++ await expect(getAgentInstrumentation("default", "api")).resolves.toEqual({+ err: "Failed to read AutoInstrumentation CRD",+ });+ });+it("deletes AutoInstrumentation custom objects and reports errors", async () => {mockDeleteNamespacedCustomObject.mockResolvedValueOnce({ body: "deleted" });await expect(deleteAgentInstrumentation("default", "api")).resolves.toEqual({@@ -150,4 +215,23 @@ describe("platform kubernetes helpers", () => {err: "no access",});});++ it("prefers body.message over error.message for delete failures", async () => {+ mockDeleteNamespacedCustomObject.mockRejectedValueOnce({+ body: { message: "forbidden" },+ message: "generic error",+ });++ await expect(deleteAgentInstrumentation("default", "api")).resolves.toEqual({+ err: "forbidden",+ });+ });++ it("falls back to a default message when delete failures have neither body.message nor message", async () => {+ mockDeleteNamespacedCustomObject.mockRejectedValueOnce({});++ await expect(deleteAgentInstrumentation("default", "api")).resolves.toEqual({+ err: "Failed to delete CRD",+ });+ });});diff --git a/src/client/src/__tests__/lib/platform/llm/agent-loop.test.ts b/src/client/src/__tests__/lib/platform/llm/agent-loop.test.tsindex c7756d57..2ac903f0 100644--- a/src/client/src/__tests__/lib/platform/llm/agent-loop.test.ts+++ b/src/client/src/__tests__/lib/platform/llm/agent-loop.test.ts@@ -32,6 +32,7 @@ import {summarizeAgentLoopFromSpans,} from "@/lib/platform/llm/agent-loop";import { resolveTelemetrySourceDescriptor } from "@/lib/telemetry-source";+import { UnsupportedCapabilityError } from "@/lib/platform/connectors/datasource/types";const mockedDataCollector = dataCollector as jest.MockedFunction<typeof dataCollector@@ -192,6 +193,84 @@ describe("getAgentLoop", () => {"traces");});++ it("returns unsupported (without throwing) when sampling raises UnsupportedCapabilityError", async () => {+ mockedResolve.mockResolvedValue({+ isBuiltIn: false,+ type: "tempo",+ } as any);+ const { resolveSignalReadContext } = await import(+ "@/lib/platform/connectors/datasource/facade"+ );+ const sampleTracesForGraph = jest.fn(async () => {+ throw new UnsupportedCapabilityError("tempo", "sampleTracesForGraph");+ });+ (resolveSignalReadContext as jest.Mock).mockResolvedValue({+ adapter: { sampleTracesForGraph },+ descriptor: { type: "tempo" },+ });++ const result = await getAgentLoop(params);++ expect(result.err).toBeUndefined();+ expect(result.data?.[0]?.unsupported).toBe(true);+ });++ it("surfaces unexpected sampling errors as a top-level error instead of throwing", async () => {+ mockedResolve.mockResolvedValue({+ isBuiltIn: false,+ type: "tempo",+ } as any);+ const { resolveSignalReadContext } = await import(+ "@/lib/platform/connectors/datasource/facade"+ );+ const boom = new Error("adapter exploded");+ const sampleTracesForGraph = jest.fn(async () => {+ throw boom;+ });+ (resolveSignalReadContext as jest.Mock).mockResolvedValue({+ adapter: { sampleTracesForGraph },+ descriptor: { type: "tempo" },+ });++ const result = await getAgentLoop(params);++ expect(result.err).toBe(boom);+ expect(result.data).toEqual([]);+ });++ it("propagates a ClickHouse query error", async () => {+ mockedDataCollector.mockResolvedValue({ err: "query failed", data: [] });++ const result = await getAgentLoop(params);++ expect(result.err).toBe("query failed");+ expect(result.data).toEqual([]);+ });++ it("defaults to an empty rows array and empty current row when the query returns no data", async () => {+ mockedDataCollector.mockResolvedValue({ err: null, data: undefined });++ const result = await getAgentLoop(params);++ expect(result.data?.[0]).toMatchObject({+ tool_traces: 0,+ loops: 0,+ previous_tool_traces: 0,+ previous_loops: 0,+ });+ });++ it("defaults the current row to an empty object when the result set is empty", async () => {+ mockedDataCollector.mockResolvedValue({ err: null, data: [] });++ const result = await getAgentLoop(params);++ expect(result.data?.[0]).toMatchObject({+ tool_traces: 0,+ loops: 0,+ });+ });});describe("summarizeAgentLoopFromSpans", () => {@@ -226,4 +305,20 @@ describe("summarizeAgentLoopFromSpans", () => {expect(row.tool_traces).toBe(2);expect(row.loops).toBe(1);});++ it("skips spans that are not tool calls", () => {+ const row = summarizeAgentLoopFromSpans([+ {+ traceId: "t-1",+ spanAttributes: { "gen_ai.tool.name": "search", "gen_ai.tool.args": "{}" },+ },+ {+ // No tool name/args — not a tool span, must not count toward tool_traces.+ traceId: "t-2",+ spanAttributes: { "gen_ai.system": "openai" },+ },+ ]);+ expect(row.tool_traces).toBe(1);+ expect(row.loops).toBe(0);+ });});diff --git a/src/client/src/__tests__/lib/platform/llm/cost.test.ts b/src/client/src/__tests__/lib/platform/llm/cost.test.tsindex 63416b14..08cfda82 100644--- a/src/client/src/__tests__/lib/platform/llm/cost.test.ts+++ b/src/client/src/__tests__/lib/platform/llm/cost.test.ts@@ -28,13 +28,31 @@ jest.mock("@/lib/platform/llm/external", () => ({import { dataCollector } from "@/lib/platform/common";import {+ getAverageCost,getCostByApplication,+ getCostByEnvironment,getCostByModel,getCostByProvider,getCostPerTime,+ getTotalCost,} from "@/lib/platform/llm/cost";+import * as external from "@/lib/platform/llm/external";const mockedDataCollector = dataCollector as jest.MockedFunction<typeof dataCollector>;+const mockedExternalTotalCost = external.externalTotalCost as jest.MockedFunction<+ typeof external.externalTotalCost+>;+const mockedExternalAverageCost = external.externalAverageCost as jest.MockedFunction<+ typeof external.externalAverageCost+>;+const mockedExternalCostByApplication =+ external.externalCostByApplication as jest.MockedFunction<+ typeof external.externalCostByApplication+ >;+const mockedExternalCostByEnvironment =+ external.externalCostByEnvironment as jest.MockedFunction<+ typeof external.externalCostByEnvironment+ >;const params = {timeLimit: {@@ -48,6 +66,97 @@ describe("llm cost analytics queries", () => {beforeEach(() => {mockedDataCollector.mockReset();mockedDataCollector.mockResolvedValue({ data: [] });+ mockedExternalTotalCost.mockReset().mockResolvedValue(null);+ mockedExternalAverageCost.mockReset().mockResolvedValue(null);+ mockedExternalCostByApplication.mockReset().mockResolvedValue(null);+ mockedExternalCostByEnvironment.mockReset().mockResolvedValue(null);+ });++ it("queries total cost via the built-in ClickHouse path when there is no external source", async () => {+ await getTotalCost(params);+ const query = mockedDataCollector.mock.calls[0][0].query as string;+ expect(query).toContain("total_usage_cost");+ expect(query).toContain("previous_total_usage_cost");+ expect(query).toContain("gen_ai.usage.cost");+ });++ it("returns the external total cost result directly when available", async () => {+ mockedExternalTotalCost.mockResolvedValue({+ err: null,+ data: [{ total_usage_cost: 12, previous_total_usage_cost: 8 }],+ });++ const result = await getTotalCost(params);++ expect(result).toEqual({+ err: null,+ data: [{ total_usage_cost: 12, previous_total_usage_cost: 8 }],+ });+ expect(mockedDataCollector).not.toHaveBeenCalled();+ });++ it("queries average cost via the built-in ClickHouse path when there is no external source", async () => {+ await getAverageCost(params);+ const query = mockedDataCollector.mock.calls[0][0].query as string;+ expect(query).toContain("average_usage_cost");+ expect(query).toContain("previous_average_usage_cost");+ });++ it("returns the external average cost result directly when available", async () => {+ mockedExternalAverageCost.mockResolvedValue({+ err: null,+ data: [{ average_usage_cost: 4 }],+ });++ const result = await getAverageCost(params);++ expect(result).toEqual({ err: null, data: [{ average_usage_cost: 4 }] });+ expect(mockedDataCollector).not.toHaveBeenCalled();+ });++ it("maps the external cost-by-application result to applicationName/cost", async () => {+ mockedExternalCostByApplication.mockResolvedValue({+ err: null,+ data: [{ application: "svc-a", total_cost: 3 }],+ });++ const result = await getCostByApplication(params);++ expect(result).toEqual({+ err: null,+ data: [{ applicationName: "svc-a", cost: 3 }],+ });+ expect(mockedDataCollector).not.toHaveBeenCalled();+ });++ it("defaults to an empty list when the external cost-by-application data is missing", async () => {+ mockedExternalCostByApplication.mockResolvedValue({+ err: "boom",+ data: undefined,+ } as any);++ const result = await getCostByApplication(params);++ expect(result).toEqual({ err: "boom", data: [] });+ });++ it("queries cost by environment via the built-in ClickHouse path when there is no external source", async () => {+ await getCostByEnvironment(params);+ const query = mockedDataCollector.mock.calls[0][0].query as string;+ expect(query).toContain("as environment");+ expect(query).toContain("deployment.environment");+ });++ it("returns the external cost-by-environment result directly when available", async () => {+ mockedExternalCostByEnvironment.mockResolvedValue({+ err: null,+ data: [{ environment: "prod", cost: 9 }],+ });++ const result = await getCostByEnvironment(params);++ expect(result).toEqual({ err: null, data: [{ environment: "prod", cost: 9 }] });+ expect(mockedDataCollector).not.toHaveBeenCalled();});it("queries cost by application via ServiceName fallbacks", async () => {diff --git a/src/client/src/__tests__/lib/platform/llm/external.test.ts b/src/client/src/__tests__/lib/platform/llm/external.test.tsnew file mode 100644index 00000000..6ee0a50a--- /dev/null+++ b/src/client/src/__tests__/lib/platform/llm/external.test.ts@@ -0,0 +1,634 @@+const mockResolveDescriptor = jest.fn();+const mockGetAdapter = jest.fn();+const mockReadSignalBucketRollup = jest.fn();+const mockReadLlmRollup = jest.fn();++jest.mock("@/lib/telemetry-source", () => ({+ resolveTelemetrySourceDescriptor: (...a: unknown[]) =>+ mockResolveDescriptor(...a),+ getTelemetryAdapter: (...a: unknown[]) => mockGetAdapter(...a),+}));++jest.mock("@/lib/platform/telemetry/rollups", () => ({+ readSignalBucketRollup: (...a: unknown[]) => mockReadSignalBucketRollup(...a),+ readLlmRollup: (...a: unknown[]) => mockReadLlmRollup(...a),+}));++import {+ externalTotalCost,+ externalAverageCost,+ externalCostPerTime,+ externalAverageTokens,+ externalTokensPerTime,+ externalGenerationByCategories,+ externalGenerationByProvider,+ externalTopModels,+ externalCostByApplication,+ externalCostByEnvironment,+ externalModelsPerTime,+} from "@/lib/platform/llm/external";++const tempo = {+ type: "tempo",+ id: "src-tempo",+ isBuiltIn: false,+ settings: {},+ signals: ["traces"],+ name: "Tempo",+ dbConfigId: "db-1",+};++const builtin = {+ type: "clickhouse",+ id: "builtin:db-1",+ isBuiltIn: true,+ settings: {},+ signals: ["traces"],+ name: "CH",+ dbConfigId: "db-1",+};++const params = {+ timeLimit: {+ start: new Date("2026-07-01T00:00:00.000Z"),+ end: new Date("2026-07-01T01:00:00.000Z"),+ type: "CUSTOM",+ },+ limit: 10,+ offset: 0,+ selectedConfig: {},+};++function serverAggregationAdapter() {+ return {+ capabilities: () => ({ serverAggregation: true }),+ aggregateSpans: jest.fn(),+ spanTimeSeries: jest.fn(),+ };+}++beforeEach(() => {+ jest.clearAllMocks();+ mockResolveDescriptor.mockResolvedValue(tempo);+});++describe("built-in ClickHouse routing", () => {+ it("returns null for the implicit built-in source so callers fall back to SQL", async () => {+ mockResolveDescriptor.mockResolvedValue(builtin);+ expect(await externalTotalCost(params)).toBeNull();+ expect(mockGetAdapter).not.toHaveBeenCalled();+ });++ it("returns null when the resolved type is clickhouse even if not flagged built-in", async () => {+ mockResolveDescriptor.mockResolvedValue({ ...tempo, isBuiltIn: false, type: "clickhouse" });+ expect(await externalAverageCost(params)).toBeNull();+ });++ it("resolves the adapter for the traces signal when the source is external", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({ rows: [{ average_usage_cost: 1 }] });+ mockGetAdapter.mockResolvedValue(adapter);+ await externalAverageCost(params);+ expect(mockGetAdapter).toHaveBeenCalledWith({ signal: "traces", environment: undefined });+ });++ it("returns null for every remaining export on the built-in source", async () => {+ mockResolveDescriptor.mockResolvedValue(builtin);+ expect(await externalCostPerTime(params)).toBeNull();+ expect(await externalAverageTokens(params)).toBeNull();+ expect(await externalTokensPerTime(params)).toBeNull();+ expect(await externalGenerationByCategories(params)).toBeNull();+ expect(await externalGenerationByProvider(params)).toBeNull();+ expect(await externalTopModels(params)).toBeNull();+ expect(await externalCostByApplication(params)).toBeNull();+ expect(await externalCostByEnvironment(params)).toBeNull();+ expect(await externalModelsPerTime(params)).toBeNull();+ expect(mockGetAdapter).not.toHaveBeenCalled();+ });+});++describe("externalTotalCost", () => {+ it("aggregates current and previous window cost via the adapter", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans+ .mockResolvedValueOnce({ rows: [{ total_usage_cost: 120 }] })+ .mockResolvedValueOnce({ rows: [{ total_usage_cost: 80 }] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalTotalCost(params);+ expect(res).toEqual({+ err: null,+ data: [{ total_usage_cost: 120, previous_total_usage_cost: 80 }],+ });+ });++ it("defaults to zero when the aggregation returns no rows", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalTotalCost(params);+ expect(res).toEqual({+ err: null,+ data: [{ total_usage_cost: 0, previous_total_usage_cost: 0 }],+ });+ });++ it("returns a stringified error when the adapter throws a non-Error value", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockRejectedValue("boom");+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalTotalCost(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });++ it("returns the Error message when the adapter throws an Error", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockRejectedValue(new Error("tempo down"));+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalTotalCost(params);+ expect(res).toEqual({ err: "tempo down", data: [] });+ });++ it("prefers the L2 rollup total when the adapter has no server aggregation", async () => {+ const adapter = { capabilities: () => ({ serverAggregation: false }), aggregateSpans: jest.fn() };+ mockGetAdapter.mockResolvedValue(adapter);+ mockReadSignalBucketRollup.mockResolvedValue({+ rows: [{ cost: 10 }, { cost: 15 }],+ meta: { freshness: "accelerated" },+ });++ const res = await externalTotalCost(params);+ expect(mockReadSignalBucketRollup).toHaveBeenCalled();+ expect(adapter.aggregateSpans).not.toHaveBeenCalled();+ expect(res).toEqual({+ err: null,+ data: [{ total_usage_cost: 25, previous_total_usage_cost: 25 }],+ });+ });++ it("treats a missing per-row cost as zero in the rollup reducer", async () => {+ const adapter = { capabilities: () => ({ serverAggregation: false }), aggregateSpans: jest.fn() };+ mockGetAdapter.mockResolvedValue(adapter);+ mockReadSignalBucketRollup.mockResolvedValue({ rows: [{}], meta: {} });++ const res = await externalTotalCost(params);+ expect(res).toEqual({+ err: null,+ data: [{ total_usage_cost: 0, previous_total_usage_cost: 0 }],+ });+ });++ it("falls back to the adapter when the rollup reports no series", async () => {+ const adapter = {+ capabilities: () => ({ serverAggregation: false }),+ aggregateSpans: jest.fn().mockResolvedValue({ rows: [{ total_usage_cost: 42 }] }),+ };+ mockGetAdapter.mockResolvedValue(adapter);+ mockReadSignalBucketRollup.mockResolvedValue(null);++ const res = await externalTotalCost(params);+ expect(adapter.aggregateSpans).toHaveBeenCalled();+ expect(res).toEqual({+ err: null,+ data: [{ total_usage_cost: 42, previous_total_usage_cost: 42 }],+ });+ });+});++describe("externalAverageCost", () => {+ it("returns the average cost from the adapter", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({ rows: [{ average_usage_cost: 3.5 }] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalAverageCost(params);+ expect(res).toEqual({ err: null, data: [{ average_usage_cost: 3.5 }] });+ });++ it("defaults to zero without rows", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalAverageCost(params);+ expect(res).toEqual({ err: null, data: [{ average_usage_cost: 0 }] });+ });++ it("returns an error payload on failure", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalAverageCost(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });+});++describe("externalCostPerTime", () => {+ it("maps a time series of cost buckets", async () => {+ const adapter = serverAggregationAdapter();+ adapter.spanTimeSeries.mockResolvedValue({+ rows: [+ { total_cost: 10, request_time: "2026-07-01 00:00" },+ { cost: 5, label: "2026-07-01 01:00" },+ ],+ });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalCostPerTime(params);+ expect(res).toEqual({+ err: null,+ data: [+ { total_cost: 10, request_time: "2026-07-01 00:00" },+ { total_cost: 5, request_time: "2026-07-01 01:00" },+ ],+ });+ });++ it("returns an error payload on failure", async () => {+ const adapter = serverAggregationAdapter();+ adapter.spanTimeSeries.mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalCostPerTime(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });++ it("falls back to the bucket label and zero cost when fields are absent", async () => {+ const adapter = serverAggregationAdapter();+ adapter.spanTimeSeries.mockResolvedValue({ rows: [{ bucket: "2026-07-01 02:00" }] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalCostPerTime(params);+ expect(res).toEqual({+ err: null,+ data: [{ total_cost: 0, request_time: "2026-07-01 02:00" }],+ });+ });++ it("prefers the L2 rollup series when supported", async () => {+ const adapter = { capabilities: () => ({ serverAggregation: false }), spanTimeSeries: jest.fn() };+ mockGetAdapter.mockResolvedValue(adapter);+ mockReadSignalBucketRollup.mockResolvedValue({+ rows: [{ total_cost: 7, request_time: "2026-07-01 00:00" }],+ meta: {},+ });++ const res = await externalCostPerTime(params);+ expect(adapter.spanTimeSeries).not.toHaveBeenCalled();+ expect(res).toEqual({+ err: null,+ data: [{ total_cost: 7, request_time: "2026-07-01 00:00" }],+ });+ });+});++describe("externalAverageTokens", () => {+ it("uses the prompt token field", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({ rows: [{ total_tokens: 11 }] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalAverageTokens({ ...params, type: "prompt" });+ expect(res).toEqual({ err: null, data: [{ total_tokens: 11 }] });+ });++ it("uses the completion token field", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({ rows: [{ total_tokens: 22 }] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalAverageTokens({ ...params, type: "completion" });+ expect(res).toEqual({ err: null, data: [{ total_tokens: 22 }] });+ });++ it("adds the previous window when type is total", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans+ .mockResolvedValueOnce({ rows: [{ total_tokens: 30 }] })+ .mockResolvedValueOnce({ rows: [{ total_tokens: 20 }] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalAverageTokens({ ...params, type: "total" });+ expect(res).toEqual({+ err: null,+ data: [{ total_tokens: 30, previous_total_tokens: 20 }],+ });+ });++ it("returns an error payload on failure", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalAverageTokens({ ...params, type: "total" });+ expect(res).toEqual({ err: "boom", data: [] });+ });++ it("defaults current and previous totals to zero without rows", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalAverageTokens({ ...params, type: "total" });+ expect(res).toEqual({+ err: null,+ data: [{ total_tokens: 0, previous_total_tokens: 0 }],+ });+ });+});++describe("externalTokensPerTime", () => {+ it("maps a time series of token buckets", async () => {+ const adapter = serverAggregationAdapter();+ adapter.spanTimeSeries.mockResolvedValue({+ rows: [+ { total_tokens: 10, request_time: "2026-07-01 00:00" },+ { tokens: 4, bucket: "2026-07-01 01:00" },+ ],+ });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalTokensPerTime(params);+ expect(res).toEqual({+ err: null,+ data: [+ { total_tokens: 10, request_time: "2026-07-01 00:00" },+ { total_tokens: 4, request_time: "2026-07-01 01:00" },+ ],+ });+ });++ it("returns an error payload on failure", async () => {+ const adapter = serverAggregationAdapter();+ adapter.spanTimeSeries.mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalTokensPerTime(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });++ it("prefers the L2 rollup series when supported", async () => {+ const adapter = { capabilities: () => ({ serverAggregation: false }), spanTimeSeries: jest.fn() };+ mockGetAdapter.mockResolvedValue(adapter);+ mockReadSignalBucketRollup.mockResolvedValue({+ rows: [{ total_tokens: 9, request_time: "2026-07-01 00:00" }],+ meta: {},+ });++ const res = await externalTokensPerTime(params);+ expect(adapter.spanTimeSeries).not.toHaveBeenCalled();+ expect(res).toEqual({+ err: null,+ data: [{ total_tokens: 9, request_time: "2026-07-01 00:00" }],+ });+ });++ it("falls back to the bucket label and zero tokens when fields are absent", async () => {+ const adapter = serverAggregationAdapter();+ adapter.spanTimeSeries.mockResolvedValue({ rows: [{ bucket: "2026-07-01 02:00" }] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalTokensPerTime(params);+ expect(res).toEqual({+ err: null,+ data: [{ total_tokens: 0, request_time: "2026-07-01 02:00" }],+ });+ });+});++describe("externalGenerationByCategories / ByProvider / TopModels", () => {+ it("groups by operation name for categories", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({+ rows: [{ group_value: "chat", count: 4 }],+ });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalGenerationByCategories(params);+ expect(res).toEqual({ err: null, data: [{ category: "chat", count: 4 }] });+ });++ it("groups by gen_ai.system for provider", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({+ rows: [{ g0: "openai", count: 2 }],+ });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalGenerationByProvider(params);+ expect(res).toEqual({ err: null, data: [{ provider: "openai", count: 2 }] });+ });++ it("groups by request model for top models", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({+ rows: [{ "gen_ai.request.model": "gpt-4o", count: 9 }],+ });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalTopModels(params);+ expect(res).toEqual({ err: null, data: [{ model: "gpt-4o", count: 9 }] });+ });++ it("defaults to an empty label and zero count when missing", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({ rows: [{}] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalTopModels(params);+ expect(res).toEqual({ err: null, data: [{ model: "", count: 0 }] });+ });++ it("returns an error payload on failure", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalGenerationByCategories(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });++ it("prefers the L2 rollup series when supported", async () => {+ const adapter = { capabilities: () => ({ serverAggregation: false }), aggregateSpans: jest.fn() };+ mockGetAdapter.mockResolvedValue(adapter);+ mockReadLlmRollup.mockResolvedValue({+ rows: [{ group_value: "chat", count: 6 }],+ meta: {},+ });++ const res = await externalGenerationByCategories(params);+ expect(adapter.aggregateSpans).not.toHaveBeenCalled();+ expect(res).toEqual({ err: null, data: [{ category: "chat", count: 6 }] });+ });+});++describe("externalCostByApplication", () => {+ it("groups cost by service name", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({+ rows: [{ group_value: "api", total_cost: 15 }],+ });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalCostByApplication(params);+ expect(res).toEqual({ err: null, data: [{ application: "api", total_cost: 15 }] });+ });++ it("returns an error payload on failure", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalCostByApplication(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });++ it("falls back to the raw service.name field and zero cost when absent", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({ rows: [{ "service.name": "api" }] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalCostByApplication(params);+ expect(res).toEqual({ err: null, data: [{ application: "api", total_cost: 0 }] });+ });++ it("defaults to an empty application label when no field is present", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({ rows: [{}] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalCostByApplication(params);+ expect(res).toEqual({ err: null, data: [{ application: "", total_cost: 0 }] });+ });++ it("prefers the L2 rollup series when supported", async () => {+ const adapter = { capabilities: () => ({ serverAggregation: false }), aggregateSpans: jest.fn() };+ mockGetAdapter.mockResolvedValue(adapter);+ mockReadLlmRollup.mockResolvedValue({+ rows: [{ group_value: "worker", total_cost: 3 }],+ meta: {},+ });++ const res = await externalCostByApplication(params);+ expect(adapter.aggregateSpans).not.toHaveBeenCalled();+ expect(res).toEqual({ err: null, data: [{ application: "worker", total_cost: 3 }] });+ });+});++describe("externalCostByEnvironment", () => {+ it("groups cost by deployment environment", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({+ rows: [{ "deployment.environment": "prod", total_cost: 8 }],+ });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalCostByEnvironment(params);+ expect(res).toEqual({ err: null, data: [{ environment: "prod", cost: 8 }] });+ });++ it("defaults to an empty environment label when missing", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({ rows: [{ total_cost: 2 }] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalCostByEnvironment(params);+ expect(res).toEqual({ err: null, data: [{ environment: "", cost: 2 }] });+ });++ it("returns an error payload on failure", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalCostByEnvironment(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });++ it("falls back to the raw deployment.environment field and zero cost when absent", async () => {+ const adapter = serverAggregationAdapter();+ adapter.aggregateSpans.mockResolvedValue({ rows: [{ "deployment.environment": "staging" }] });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalCostByEnvironment(params);+ expect(res).toEqual({ err: null, data: [{ environment: "staging", cost: 0 }] });+ });++ it("prefers the L2 rollup series when supported", async () => {+ const adapter = { capabilities: () => ({ serverAggregation: false }), aggregateSpans: jest.fn() };+ mockGetAdapter.mockResolvedValue(adapter);+ mockReadLlmRollup.mockResolvedValue({+ rows: [{ group_value: "staging", total_cost: 1 }],+ meta: {},+ });++ const res = await externalCostByEnvironment(params);+ expect(adapter.aggregateSpans).not.toHaveBeenCalled();+ expect(res).toEqual({ err: null, data: [{ environment: "staging", cost: 1 }] });+ });+});++describe("externalModelsPerTime", () => {+ it("buckets model counts per time bucket, sorted by time", async () => {+ const adapter = serverAggregationAdapter();+ adapter.spanTimeSeries.mockResolvedValue({+ rows: [+ { request_time: "2026-07-01 01:00", "gen_ai.request.model": "gpt-4o", model_count: 3 },+ { request_time: "2026-07-01 00:00", g0: "gpt-4o-mini", count: 2 },+ { request_time: "2026-07-01 00:00", group_value: "", model_count: 5 },+ ],+ });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalModelsPerTime(params);+ expect(res?.err).toBeNull();+ expect(res?.data).toEqual([+ {+ request_time: "2026-07-01 00:00",+ models: ["gpt-4o-mini"],+ model_counts: [2],+ total_model_count: 7,+ },+ {+ request_time: "2026-07-01 01:00",+ models: ["gpt-4o"],+ model_counts: [3],+ total_model_count: 3,+ },+ ]);+ });++ it("returns an error payload on failure", async () => {+ const adapter = serverAggregationAdapter();+ adapter.spanTimeSeries.mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalModelsPerTime(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });++ it("falls back to label/bucket time keys and a count field, skipping unnamed models", async () => {+ const adapter = serverAggregationAdapter();+ adapter.spanTimeSeries.mockResolvedValue({+ rows: [{ label: "2026-07-01 03:00", count: 4 }],+ });+ mockGetAdapter.mockResolvedValue(adapter);++ const res = await externalModelsPerTime(params);+ expect(res).toEqual({+ err: null,+ data: [+ {+ request_time: "2026-07-01 03:00",+ models: [],+ model_counts: [],+ total_model_count: 4,+ },+ ],+ });+ });+});diff --git a/src/client/src/__tests__/lib/platform/llm/generation-health.test.ts b/src/client/src/__tests__/lib/platform/llm/generation-health.test.tsindex 032e56d1..bc62abe4 100644--- a/src/client/src/__tests__/lib/platform/llm/generation-health.test.ts+++ b/src/client/src/__tests__/lib/platform/llm/generation-health.test.ts@@ -32,6 +32,7 @@ import {summarizeGenerationHealthFromSpans,} from "@/lib/platform/llm/generation-health";import { resolveTelemetrySourceDescriptor } from "@/lib/telemetry-source";+import { UnsupportedCapabilityError } from "@/lib/platform/connectors/datasource/types";const mockedDataCollector = dataCollector as jest.MockedFunction<typeof dataCollector@@ -113,6 +114,24 @@ describe("getGenerationHealth", () => {expect(query).not.toContain("operationType");});+ it("defaults to an empty row when dataCollector returns no rows", async () => {+ mockedDataCollector.mockResolvedValue({ data: undefined });++ const result = await getGenerationHealth(params);++ expect(result.err).toBeUndefined();+ expect(result.data?.[0]?.llm_spans).toBe(0);+ });++ it("returns the ClickHouse dataCollector error", async () => {+ mockedDataCollector.mockResolvedValue({ err: "query failed", data: [] });++ const result = await getGenerationHealth(params);++ expect(result.err).toBe("query failed");+ expect(result.data).toEqual([]);+ });+it("prefers an explicit databaseConfigId over the resolved traces binding", async () => {mockedResolve.mockResolvedValue({isBuiltIn: true,@@ -151,6 +170,50 @@ describe("getGenerationHealth", () => {expect(mockedDataCollector).not.toHaveBeenCalled();});+ it("returns unsupported when sampling raises UnsupportedCapabilityError", async () => {+ mockedResolve.mockResolvedValue({+ isBuiltIn: false,+ type: "tempo",+ } as any);+ const { resolveSignalReadContext } = await import(+ "@/lib/platform/connectors/datasource/facade"+ );+ const sampleTracesForGraph = jest.fn(async () => {+ throw new UnsupportedCapabilityError("tempo", "sampleTracesForGraph");+ });+ (resolveSignalReadContext as jest.Mock).mockResolvedValue({+ adapter: { sampleTracesForGraph },+ descriptor: { type: "tempo" },+ });++ const result = await getGenerationHealth(params);++ expect(result.data?.[0]?.unsupported).toBe(true);+ expect(result.err).toBeUndefined();+ });++ it("surfaces other sampling errors instead of swallowing them", async () => {+ mockedResolve.mockResolvedValue({+ isBuiltIn: false,+ type: "tempo",+ } as any);+ const { resolveSignalReadContext } = await import(+ "@/lib/platform/connectors/datasource/facade"+ );+ const sampleTracesForGraph = jest.fn(async () => {+ throw new Error("adapter exploded");+ });+ (resolveSignalReadContext as jest.Mock).mockResolvedValue({+ adapter: { sampleTracesForGraph },+ descriptor: { type: "tempo" },+ });++ const result = await getGenerationHealth(params);++ expect(result.data).toEqual([]);+ expect((result.err as Error)?.message).toBe("adapter exploded");+ });+it("classifies sampled spans for any traces adapter with sampleTracesForGraph", async () => {mockedResolve.mockResolvedValue({isBuiltIn: false,@@ -229,4 +292,41 @@ describe("summarizeGenerationHealthFromSpans", () => {expect(row.truncated).toBe(1);expect(row.swapped_eligible).toBe(1);});++ it("counts filtered and empty chips when a trace matches them", () => {+ const row = summarizeGenerationHealthFromSpans([+ {+ traceId: "t-filtered",+ spanAttributes: {+ "gen_ai.response.finish_reasons": "content_filter",+ "gen_ai.request.model": "gpt-4o",+ },+ },+ {+ traceId: "t-empty",+ spanAttributes: {+ "gen_ai.response.finish_reasons": "stop",+ "gen_ai.usage.output_tokens": "0",+ },+ },+ ]);+ expect(row.llm_spans).toBe(2);+ expect(row.filtered).toBe(1);+ expect(row.empty).toBe(1);+ });++ it("ignores spans from non-LLM traces entirely", () => {+ const row = summarizeGenerationHealthFromSpans([+ { traceId: "t-plain", spanAttributes: { "http.method": "GET" } },+ ]);+ expect(row.llm_spans).toBe(0);+ expect(row.truncated).toBe(0);+ });++ it("handles spans with neither spanAttributes nor a traceId", () => {+ const row = summarizeGenerationHealthFromSpans([+ { resourceAttributes: { "gen_ai.operation.name": "chat" } },+ ]);+ expect(row.llm_spans).toBe(1);+ });});diff --git a/src/client/src/__tests__/lib/platform/metrics/read.test.ts b/src/client/src/__tests__/lib/platform/metrics/read.test.tsindex 0e4d498b..82511b3d 100644--- a/src/client/src/__tests__/lib/platform/metrics/read.test.ts+++ b/src/client/src/__tests__/lib/platform/metrics/read.test.ts@@ -23,7 +23,13 @@ jest.mock("@/lib/platform/connectors/datasource/facade", () => ({},}));-import { listMetricRecords, getMetricsSummary, getMetricsFilterConfig, getMetricAttributeKeysRecord } from "@/lib/platform/metrics/read";+import {+ listMetricRecords,+ getMetricsSummary,+ getMetricsFilterConfig,+ getMetricAttributeKeysRecord,+ getMetricDetailRecord,+} from "@/lib/platform/metrics/read";import { AdapterError } from "@openplait/adapter-sdk";const params = {@@ -179,6 +185,67 @@ describe("getMetricsSummary", () => {buckets: [{ label: "2026-07-01T00:00:00.000Z", count: 4 }],});});++ it("preserves existing aggregations instead of forcing a count", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({ fields: [], rows: [] });+ mockResolveCtx.mockResolvedValue({+ adapter: { metricTimeSeries },+ descriptor: {},+ isBuiltIn: false,+ });++ await getMetricsSummary({+ ...(params as Record<string, unknown>),+ selectedConfig: { aggregations: [{ fn: "sum", field: "value" }] },+ } as never);++ expect(metricTimeSeries).toHaveBeenCalled();+ });++ it("skips rows without a usable label or a finite count", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({+ fields: [],+ rows: [+ { value: 12 },+ { timestamp: "2026-07-01T00:00:00.000Z", value: "not-a-number" },+ ],+ });+ mockResolveCtx.mockResolvedValue({+ adapter: { metricTimeSeries },+ descriptor: {},+ isBuiltIn: false,+ });++ const res = await getMetricsSummary(params);+ expect(res).toMatchObject({ total: 0, peak: 0, buckets: [] });+ });++ it("returns the empty summary when getMetricsSummary fails", async () => {+ mockResolveCtx.mockResolvedValue({+ adapter: {+ metricTimeSeries: jest.fn().mockRejectedValue(new Error("summary boom")),+ },+ descriptor: {},+ isBuiltIn: false,+ });++ const res = await getMetricsSummary(params);+ expect(res).toMatchObject({ err: "summary boom", buckets: [], total: 0, peak: 0 });+ });++ it("rethrows AdapterError from getMetricsSummary", async () => {+ mockResolveCtx.mockResolvedValue({+ adapter: {+ metricTimeSeries: jest+ .fn()+ .mockRejectedValue(new AdapterError("EXECUTION_FAILED", "boom")),+ },+ descriptor: {},+ isBuiltIn: false,+ });++ await expect(getMetricsSummary(params)).rejects.toBeInstanceOf(AdapterError);+ });});describe("getMetricsFilterConfig", () => {@@ -224,6 +291,52 @@ describe("getMetricsFilterConfig", () => {const res = await getMetricsFilterConfig(params);expect(res.data?.[0]?.services).toEqual(["prometheus"]);});++ it("skips distinctValues when the adapter has no support for it", async () => {+ mockResolveCtx.mockResolvedValue({+ adapter: {+ capabilities: () => ({ distinctValues: false }),+ metricNames: jest.fn().mockResolvedValue(["up"]),+ },+ descriptor: {},+ isBuiltIn: false,+ });++ const res = await getMetricsFilterConfig(params);+ expect(res.data?.[0]?.services).toEqual([]);+ });++ it("returns an error payload when getMetricsFilterConfig fails", async () => {+ mockResolveCtx.mockResolvedValue({+ adapter: {+ metricNames: jest.fn().mockResolvedValue([]),+ capabilities: () => {+ throw new Error("filter config boom");+ },+ },+ descriptor: {},+ isBuiltIn: false,+ });++ const res = await getMetricsFilterConfig(params);+ expect(res.err).toBe("filter config boom");+ expect(res.data?.[0]).toMatchObject({ services: [], metricNames: [] });+ });++ it("rethrows AdapterError from getMetricsFilterConfig", async () => {+ mockResolveCtx.mockResolvedValue({+ adapter: {+ metricNames: jest.fn().mockResolvedValue([]),+ capabilities: () => {+ throw new AdapterError("EXECUTION_FAILED", "boom");+ },+ },+ descriptor: {},+ isBuiltIn: false,+ });++ await expect(getMetricsFilterConfig(params)).rejects.toBeInstanceOf(AdapterError);+ });});describe("getMetricAttributeKeysRecord", () => {@@ -242,4 +355,150 @@ describe("getMetricAttributeKeysRecord", () => {resourceAttributeKeys: ["service_name", "job"],});});++ it("returns the empty payload when attribute discovery fails", async () => {+ mockResolveCtx.mockResolvedValue({+ adapter: {+ attributeKeys: jest.fn().mockRejectedValue(new Error("attr boom")),+ },+ descriptor: {},+ isBuiltIn: false,+ });++ const res = await getMetricAttributeKeysRecord(params);+ expect(res).toMatchObject({+ err: "attr boom",+ spanAttributeKeys: [],+ resourceAttributeKeys: [],+ metricAttributeKeys: [],+ scopeAttributeKeys: [],+ });+ });++ it("rethrows AdapterError from getMetricAttributeKeysRecord", async () => {+ mockResolveCtx.mockResolvedValue({+ adapter: {+ attributeKeys: jest+ .fn()+ .mockRejectedValue(new AdapterError("EXECUTION_FAILED", "boom")),+ },+ descriptor: {},+ isBuiltIn: false,+ });++ await expect(getMetricAttributeKeysRecord(params)).rejects.toBeInstanceOf(+ AdapterError+ );+ });+});++describe("getMetricDetailRecord", () => {+ it("builds a sorted series and raw points from metric time series", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({+ fields: [],+ rows: [+ {+ metricName: "cpu",+ timestamp: "2026-07-01T00:01:00.000Z",+ value: 20,+ unit: "percent",+ description: "CPU usage",+ serviceName: "api",+ attributes: { host: "a" },+ resourceAttributes: { "service.name": "api" },+ },+ {+ metricName: "cpu",+ timestamp: "2026-07-01T00:00:00.000Z",+ value: 10,+ serviceName: "api",+ attributes: {},+ resourceAttributes: {},+ },+ ],+ });+ mockResolveCtx.mockResolvedValue({+ adapter: { metricTimeSeries },+ descriptor: {},+ isBuiltIn: false,+ });++ const res = await getMetricDetailRecord("cpu", "gauge", "api", params);++ expect(metricTimeSeries).toHaveBeenCalledWith(+ expect.objectContaining({+ filters: expect.arrayContaining([+ { target: "spanName", op: "in", value: ["cpu"] },+ ]),+ })+ );+ expect(res.err).toBeNull();+ expect(res.series).toEqual([+ { request_time: "2026-07-01T00:00:00.000Z", value: 10 },+ { request_time: "2026-07-01T00:01:00.000Z", value: 20 },+ ]);+ expect(res.points).toEqual([+ expect.objectContaining({+ MetricName: "cpu",+ metric_type: "gauge",+ metric_value: 20,+ MetricUnit: "percent",+ MetricDescription: "CPU usage",+ ServiceName: "api",+ Attributes: { host: "a" },+ ResourceAttributes: { "service.name": "api" },+ }),+ expect.objectContaining({+ MetricName: "cpu",+ metric_type: "gauge",+ metric_value: 10,+ MetricUnit: "",+ MetricDescription: "",+ ServiceName: "api",+ Attributes: {},+ ResourceAttributes: {},+ }),+ ]);+ });++ it("defaults the metric type to gauge and works without params", async () => {+ const metricTimeSeries = jest.fn().mockResolvedValue({ fields: [], rows: [] });+ mockResolveCtx.mockResolvedValue({+ adapter: { metricTimeSeries },+ descriptor: {},+ isBuiltIn: false,+ });++ const res = await getMetricDetailRecord("cpu");+ expect(res).toEqual({ err: null, series: [], points: [] });+ });++ it("returns an error payload when getMetricDetailRecord fails", async () => {+ mockResolveCtx.mockResolvedValue({+ adapter: {+ metricTimeSeries: jest.fn().mockRejectedValue(new Error("detail boom")),+ },+ descriptor: {},+ isBuiltIn: false,+ });++ const res = await getMetricDetailRecord("cpu", "gauge", "api", params);+ expect(res).toEqual({ err: "detail boom", series: [], points: [] });+ });++ it("rethrows AdapterError from getMetricDetailRecord", async () => {+ mockResolveCtx.mockResolvedValue({+ adapter: {+ metricTimeSeries: jest+ .fn()+ .mockRejectedValue(new AdapterError("EXECUTION_FAILED", "boom")),+ },+ descriptor: {},+ isBuiltIn: false,+ });++ await expect(+ getMetricDetailRecord("cpu", "gauge", "api", params)+ ).rejects.toBeInstanceOf(AdapterError);+ });});diff --git a/src/client/src/__tests__/lib/platform/observability-deprecation.test.ts b/src/client/src/__tests__/lib/platform/observability-deprecation.test.tsnew file mode 100644index 00000000..7980f6f7--- /dev/null+++ b/src/client/src/__tests__/lib/platform/observability-deprecation.test.ts@@ -0,0 +1,134 @@+class TestHeaders {+ private map = new Map<string, string>();++ constructor(init?: TestHeaders | Record<string, string> | null) {+ if (init instanceof TestHeaders) {+ init.map.forEach((value, key) => this.map.set(key, value));+ } else if (init && typeof (init as { forEach?: unknown }).forEach === "function") {+ (init as unknown as { forEach: (cb: (v: string, k: string) => void) => void }).forEach(+ (value, key) => this.map.set(key.toLowerCase(), value)+ );+ } else if (init) {+ Object.entries(init).forEach(([key, value]) => this.map.set(key.toLowerCase(), value));+ }+ }++ get(key: string) {+ return this.map.get(key.toLowerCase()) ?? null;+ }++ set(key: string, value: string) {+ this.map.set(key.toLowerCase(), value);+ }++ forEach(cb: (value: string, key: string) => void) {+ this.map.forEach((value, key) => cb(value, key));+ }+}++class TestResponse {+ status: number;+ statusText: string;+ headers: TestHeaders;+ body: unknown;++ constructor(+ body?: unknown,+ init?: { status?: number; statusText?: string; headers?: TestHeaders | Record<string, string> }+ ) {+ this.body = body;+ this.status = init?.status ?? 200;+ this.statusText = init?.statusText ?? "";+ this.headers = new TestHeaders(init?.headers);+ }++ static json(body: unknown, init?: { status?: number; headers?: Record<string, string> }) {+ return new TestResponse(JSON.stringify(body), init);+ }++ async json() {+ return typeof this.body === "string" ? JSON.parse(this.body) : this.body;+ }+}++(globalThis as unknown as { Response: unknown }).Response = TestResponse;+(globalThis as unknown as { Headers: unknown }).Headers = TestHeaders;++import {+ deprecatedObservabilityResponse,+ jsonWithObservabilityDeprecation,+} from "@/lib/platform/observability-deprecation";++describe("deprecatedObservabilityResponse", () => {+ it("stamps Deprecation, Link, and alias headers while preserving status/body", () => {+ const original = new Response("hello", { status: 201, statusText: "Created" });++ const result = deprecatedObservabilityResponse(+ original as unknown as Response,+ "/api/telemetry/logs"+ ) as unknown as TestResponse;++ expect(result.status).toBe(201);+ expect(result.statusText).toBe("Created");+ expect(result.body).toBe("hello");+ expect(result.headers.get("Deprecation")).toBe("true");+ expect(result.headers.get("Link")).toBe('</api/telemetry/logs>; rel="successor-version"');+ expect(result.headers.get("X-OpenLIT-Deprecated-Alias")).toBe("observability→telemetry");+ });++ it("preserves pre-existing headers on the original response", () => {+ const original = new Response("body", {+ status: 200,+ headers: { "x-custom": "keep-me" },+ });++ const result = deprecatedObservabilityResponse(+ original as unknown as Response,+ "/api/telemetry/metrics"+ ) as unknown as TestResponse;++ expect(result.headers.get("x-custom")).toBe("keep-me");+ expect(result.headers.get("Deprecation")).toBe("true");+ });++ it("defaults status to 200 when the original response omits it", () => {+ const original = new Response("body");++ const result = deprecatedObservabilityResponse(+ original as unknown as Response,+ "/api/telemetry/traces"+ ) as unknown as TestResponse;++ expect(result.status).toBe(200);+ });+});++describe("jsonWithObservabilityDeprecation", () => {+ it("serializes the body and stamps deprecation headers", async () => {+ const result = (await jsonWithObservabilityDeprecation(+ { ok: true, count: 3 },+ "/api/telemetry/logs",+ { status: 202 }+ )) as unknown as TestResponse;++ expect(result.status).toBe(202);+ expect(result.headers.get("Deprecation")).toBe("true");+ expect(result.headers.get("Link")).toBe('</api/telemetry/logs>; rel="successor-version"');+ expect(await (result as unknown as { json: () => Promise<unknown> }).json()).toEqual({+ ok: true,+ count: 3,+ });+ });++ it("defaults to status 200 when no init is provided", async () => {+ const result = (await jsonWithObservabilityDeprecation(+ { hello: "world" },+ "/api/telemetry/metrics"+ )) as unknown as TestResponse;++ expect(result.status).toBe(200);+ expect(await (result as unknown as { json: () => Promise<unknown> }).json()).toEqual({+ hello: "world",+ });+ });+});diff --git a/src/client/src/__tests__/lib/platform/observability.test.ts b/src/client/src/__tests__/lib/platform/observability.test.tsindex cb66e63f..5789fdaf 100644--- a/src/client/src/__tests__/lib/platform/observability.test.ts+++ b/src/client/src/__tests__/lib/platform/observability.test.ts@@ -333,4 +333,91 @@ describe("observability platform queries", () => {"MetricName = 'cpu.usage'");});++ it("falls back to defaults when timeLimit and selectedConfig are missing", async () => {+ await getLogsConfig({} as any);++ const query = (dataCollector as jest.Mock).mock.calls[0][0].query;+ expect(query).toContain("WHERE 1 = 1");+ });++ it("filters on a non-default environment", async () => {+ await getLogsConfig({+ ...params,+ selectedConfig: { environments: ["production"] },+ } as any);++ const query = (dataCollector as jest.Mock).mock.calls[0][0].query;+ expect(query).toContain(+ "ResourceAttributes['deployment.environment'] IN ('production')"+ );+ });++ it("does not filter when the only environment is the synthetic default", async () => {+ await getLogsConfig({+ ...params,+ selectedConfig: { environments: ["default"] },+ } as any);++ const query = (dataCollector as jest.Mock).mock.calls[0][0].query;+ expect(query).not.toContain("deployment.environment");+ });++ it("filters when multiple environments include default alongside others", async () => {+ await getLogsConfig({+ ...params,+ selectedConfig: { environments: ["default", "staging"] },+ } as any);++ const query = (dataCollector as jest.Mock).mock.calls[0][0].query;+ expect(query).toContain(+ "ResourceAttributes['deployment.environment'] IN ('default', 'staging')"+ );+ });++ it("defaults attribute-key results to empty arrays when data is missing", async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ err: null })+ .mockResolvedValueOnce({ err: null })+ .mockResolvedValueOnce({ err: null });++ const logKeys = await getLogAttributeKeys(params as any);+ expect(logKeys.logAttributeKeys).toEqual([]);+ expect(logKeys.resourceAttributeKeys).toEqual([]);+ expect(logKeys.scopeAttributeKeys).toEqual([]);++ (dataCollector as jest.Mock).mockClear();+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ err: null })+ .mockResolvedValueOnce({ err: null })+ .mockResolvedValueOnce({ err: null });++ const metricKeys = await getMetricAttributeKeys(params as any);+ expect(metricKeys.metricAttributeKeys).toEqual([]);+ expect(metricKeys.resourceAttributeKeys).toEqual([]);+ expect(metricKeys.scopeAttributeKeys).toEqual([]);+ });++ it("treats missing bucket counts as zero when totaling and finding the peak", async () => {+ (dataCollector as jest.Mock).mockResolvedValue({+ data: [{ label: "05/16 01:00" }],+ err: null,+ });++ const result = await getSignalSummary(params as any, "logs");++ expect(result.total).toBe(0);+ expect(result.peak).toBe(0);+ });++ it("defaults metric detail series and points to empty arrays when data is missing", async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ err: null })+ .mockResolvedValueOnce({ err: null });++ const result = await getMetricDetail("cpu.usage");++ expect(result.series).toEqual([]);+ expect(result.points).toEqual([]);+ });});diff --git a/src/client/src/__tests__/lib/platform/openplait/index.test.ts b/src/client/src/__tests__/lib/platform/openplait/index.test.tsnew file mode 100644index 00000000..494df530--- /dev/null+++ b/src/client/src/__tests__/lib/platform/openplait/index.test.ts@@ -0,0 +1,582 @@+/**+ * Unit tests for the OpenPlait ClickHouse wrapper (`lib/platform/openplait/index.ts`).+ *+ * `@openplait/adapter-clickhouse` and `@openplait/runtime` are real ESM+ * packages resolved through jest's moduleNameMapper. We mock them here with+ * lightweight jest classes so tests fully control connection/execute+ * behavior without touching a real ClickHouse server.+ */++import type { DatabaseConfig } from "@prisma/client";++const mockAdapterClose = jest.fn();+const mockAdapterCtor = jest.fn();+const mockRegistryRegister = jest.fn();+const mockRuntimeExecute = jest.fn();+const mockRuntimeCtor = jest.fn();++jest.mock("@openplait/adapter-clickhouse", () => {+ class MockClickHouseAdapter {+ config: unknown;+ close = mockAdapterClose;+ constructor(config: unknown) {+ this.config = config;+ mockAdapterCtor(config);+ }+ }+ return {+ ClickHouseAdapter: MockClickHouseAdapter,+ OPENLIT_CLICKHOUSE_DATASETS: ["traces", "logs", "metrics"],+ OTEL_CLICKHOUSE_DATASETS: ["otel_traces", "otel_logs", "otel_metrics"],+ };+});++jest.mock("@openplait/runtime", () => {+ class MockDatasourceRegistry {+ register(config: unknown) {+ mockRegistryRegister(config);+ return this;+ }+ }+ class MockOpenPlaitRuntime {+ options: unknown;+ execute = mockRuntimeExecute;+ constructor(registry: unknown, options: unknown) {+ this.options = options;+ mockRuntimeCtor(registry, options);+ }+ }+ return {+ DatasourceRegistry: MockDatasourceRegistry,+ OpenPlaitRuntime: MockOpenPlaitRuntime,+ };+});++jest.mock("@/utils/parser", () => ({+ constructURL: jest.fn((host: string, port: string) => `http://${host}:${port}`),+ parseQueryStringToObject: jest.fn((query: string) =>+ query ? { raw: query } : {}+ ),+}));++const mockNormalize = jest.fn((query: string) => query);+jest.mock("../../../../lib/platform/openplait/native", () => ({+ normalizeOpenPlaitReadStatement: (query: string) => mockNormalize(query),+}));++const mockFramesToRows = jest.fn();+jest.mock("../../../../lib/platform/openplait/frames", () => ({+ openPlaitFramesToRows: (frames: unknown) => mockFramesToRows(frames),+}));++import {+ validateOpenPlaitClickHouseConnection,+ executeOpenPlaitRead,+ closeOpenPlaitRuntimes,+ type OpenPlaitClickHouseConnection,+} from "@/lib/platform/openplait/index";++function buildDbConfig(overrides: Partial<DatabaseConfig> = {}): DatabaseConfig {+ return {+ id: "db-1",+ host: "clickhouse.local",+ port: "8123",+ database: "openlit",+ username: "default",+ password: "secret",+ query: "",+ updatedAt: new Date("2026-01-01T00:00:00.000Z"),+ ...overrides,+ } as DatabaseConfig;+}++const CONNECTION: OpenPlaitClickHouseConnection = {+ host: "clickhouse.local",+ port: "8123",+ database: "openlit",+ username: "default",+ password: "secret",+ query: "",+};++const ORIGINAL_ENV = process.env;++beforeEach(async () => {+ // Drain any runtimes cached by the previous test BEFORE resetting the+ // mocks, so the drain's own `adapter.close()` calls don't pollute this+ // test's call-count assertions.+ await closeOpenPlaitRuntimes();+ jest.clearAllMocks();+ mockNormalize.mockImplementation((query: string) => query);+ mockFramesToRows.mockReturnValue([]);+ process.env = { ...ORIGINAL_ENV };+ delete process.env.OPENPLAIT_CLICKHOUSE_QUERY_TIMEOUT_MS;+ delete process.env.OPENPLAIT_CLICKHOUSE_MAX_RESULT_ROWS;+ delete process.env.OPENPLAIT_CLICKHOUSE_MAX_ROWS_TO_READ;+});++afterAll(() => {+ process.env = ORIGINAL_ENV;+});++describe("validateOpenPlaitClickHouseConnection", () => {+ it("constructs an adapter/registry/runtime, runs a SELECT 1 native query, and closes the adapter", async () => {+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });++ await validateOpenPlaitClickHouseConnection(CONNECTION);++ expect(mockAdapterCtor).toHaveBeenCalledTimes(1);+ expect(mockRegistryRegister).toHaveBeenCalledTimes(1);+ expect(mockRuntimeCtor).toHaveBeenCalledTimes(1);+ expect(mockRuntimeExecute).toHaveBeenCalledTimes(1);+ const executeArg = mockRuntimeExecute.mock.calls[0][0];+ expect(executeArg.queries[0].spec.native.statement).toBe(+ "SELECT 1 AS openplait_connection_ok"+ );+ expect(executeArg.queries[0].spec.mode).toBe("native");+ expect(mockAdapterClose).toHaveBeenCalledTimes(1);+ });++ it("throws a wrapped error including the plain error message and still closes the adapter", async () => {+ mockRuntimeExecute.mockRejectedValue(new Error("connection refused"));++ await expect(+ validateOpenPlaitClickHouseConnection(CONNECTION)+ ).rejects.toThrow(+ "OpenPlait ClickHouse validation failed: connection refused"+ );+ expect(mockAdapterClose).toHaveBeenCalledTimes(1);+ });++ it("walks a nested .cause chain to report the deepest error message", async () => {+ const root = new Error("root cause: socket died");+ const middle = new Error("middle wrapper", { cause: root });+ const top = new Error("top wrapper", { cause: middle });+ mockRuntimeExecute.mockRejectedValue(top);++ await expect(+ validateOpenPlaitClickHouseConnection(CONNECTION)+ ).rejects.toThrow(+ "OpenPlait ClickHouse validation failed: root cause: socket died"+ );+ expect(mockAdapterClose).toHaveBeenCalledTimes(1);+ });++ it("stops walking the cause chain after 5 levels and reports the deepest reached message", async () => {+ // Build a chain of 7 nested errors; only the first 5 (levels 0-4) are+ // visited by `deepestErrorMessage`'s loop bound.+ let current = new Error("level-0");+ for (let i = 1; i < 7; i += 1) {+ current = new Error(`level-${i}`, { cause: current });+ }+ mockRuntimeExecute.mockRejectedValue(current);++ await expect(+ validateOpenPlaitClickHouseConnection(CONNECTION)+ ).rejects.toThrow("OpenPlait ClickHouse validation failed: level-2");+ });++ it("keeps the outer message when a nested cause has an empty message", async () => {+ const inner = new Error("");+ const outer = new Error("outer failure", { cause: inner });+ mockRuntimeExecute.mockRejectedValue(outer);++ await expect(+ validateOpenPlaitClickHouseConnection(CONNECTION)+ ).rejects.toThrow(+ "OpenPlait ClickHouse validation failed: outer failure"+ );+ });++ it("falls back to String(error) for a non-Error rejection", async () => {+ mockRuntimeExecute.mockRejectedValue("plain string failure");++ await expect(+ validateOpenPlaitClickHouseConnection(CONNECTION)+ ).rejects.toThrow(+ "OpenPlait ClickHouse validation failed: plain string failure"+ );+ expect(mockAdapterClose).toHaveBeenCalledTimes(1);+ });+});++describe("executeOpenPlaitRead", () => {+ it("normalizes the raw query before executing", async () => {+ mockNormalize.mockReturnValue("SELECT 1");+ mockRuntimeExecute.mockResolvedValue({ result: { frames: ["frame"] } });+ mockFramesToRows.mockReturnValue([{ a: 1 }]);++ const rows = await executeOpenPlaitRead({+ query: " SELECT 1; ",+ dbConfig: buildDbConfig(),+ });++ expect(mockNormalize).toHaveBeenCalledWith(" SELECT 1; ");+ const executeArg = mockRuntimeExecute.mock.calls[0][0];+ expect(executeArg.queries[0].spec.native.statement).toBe("SELECT 1");+ expect(mockFramesToRows).toHaveBeenCalledWith(["frame"]);+ expect(rows).toEqual([{ a: 1 }]);+ });++ it("caches the runtime per dbConfig.id across calls with an unchanged fingerprint", async () => {+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ const dbConfig = buildDbConfig();++ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig });+ await executeOpenPlaitRead({ query: "SELECT 2", dbConfig });++ expect(mockAdapterCtor).toHaveBeenCalledTimes(1);+ expect(mockRuntimeCtor).toHaveBeenCalledTimes(1);+ expect(mockRuntimeExecute).toHaveBeenCalledTimes(2);+ expect(mockAdapterClose).not.toHaveBeenCalled();+ });++ it.each([+ ["host", { host: "new-host" }],+ ["port", { port: "9999" }],+ ["database", { database: "new-db" }],+ ["username", { username: "new-user" }],+ ["query", { query: "?a=b" }],+ ["updatedAt", { updatedAt: new Date("2026-06-01T00:00:00.000Z") }],+ ])(+ "invalidates the cached runtime when %s changes",+ async (_label, overrides) => {+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ const dbConfig = buildDbConfig();++ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig });+ expect(mockAdapterCtor).toHaveBeenCalledTimes(1);++ const changed = buildDbConfig(overrides);+ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig: changed });++ expect(mockAdapterCtor).toHaveBeenCalledTimes(2);+ expect(mockAdapterClose).toHaveBeenCalledTimes(1);+ }+ );++ it("still computes a stable fingerprint when updatedAt isn't a Date instance", async () => {+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ const dbConfig = buildDbConfig({+ updatedAt: "2026-01-01T00:00:00.000Z" as unknown as Date,+ });++ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig });+ await executeOpenPlaitRead({ query: "SELECT 2", dbConfig });++ expect(mockAdapterCtor).toHaveBeenCalledTimes(1);+ expect(mockAdapterClose).not.toHaveBeenCalled();+ });++ it("still computes a stable fingerprint when updatedAt is missing/falsy", async () => {+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ const dbConfig = buildDbConfig({ updatedAt: null as unknown as Date });++ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig });+ await executeOpenPlaitRead({ query: "SELECT 2", dbConfig });++ expect(mockAdapterCtor).toHaveBeenCalledTimes(1);+ expect(mockAdapterClose).not.toHaveBeenCalled();+ });++ it("does not rebuild the runtime when password changes alone (not part of the fingerprint)", async () => {+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ const dbConfig = buildDbConfig();+ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig });++ const samePassword = buildDbConfig({ password: "different-secret" });+ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig: samePassword });++ expect(mockAdapterCtor).toHaveBeenCalledTimes(1);+ expect(mockAdapterClose).not.toHaveBeenCalled();+ });++ it.each([+ ["ECONNRESET", new Error("read ECONNRESET")],+ ["ECONNREFUSED", new Error("connect ECONNREFUSED 127.0.0.1:8123")],+ ["ETIMEDOUT", new Error("connect ETIMEDOUT")],+ ["EPIPE", new Error("write EPIPE")],+ ["UND_ERR_SOCKET", Object.assign(new Error("fetch failed"), { code: "UND_ERR_SOCKET" })],+ ["socket hang up", new Error("socket hang up")],+ ["connection closed", new Error("connection closed unexpectedly")],+ ["connection reset", new Error("connection reset by peer")],+ ])(+ "retries exactly once and returns the successful result on a transient error (%s)",+ async (_label, transientError) => {+ mockRuntimeExecute+ .mockRejectedValueOnce(transientError)+ .mockResolvedValueOnce({ result: { frames: ["ok-frame"] } });+ mockFramesToRows.mockReturnValue([{ ok: true }]);+ const dbConfig = buildDbConfig();++ const rows = await executeOpenPlaitRead({ query: "SELECT 1", dbConfig });++ expect(rows).toEqual([{ ok: true }]);+ expect(mockRuntimeExecute).toHaveBeenCalledTimes(2);+ // Evicted + recreated once: the original adapter is closed and a+ // second adapter/runtime pair is constructed.+ expect(mockAdapterClose).toHaveBeenCalledTimes(1);+ expect(mockAdapterCtor).toHaveBeenCalledTimes(2);+ expect(mockRuntimeCtor).toHaveBeenCalledTimes(2);+ }+ );++ it("treats a raw (non-Error) transient-looking rejection as transient and retries", async () => {+ mockRuntimeExecute+ .mockRejectedValueOnce("ECONNRESET")+ .mockResolvedValueOnce({ result: { frames: [] } });+ const dbConfig = buildDbConfig();++ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig });++ expect(mockRuntimeExecute).toHaveBeenCalledTimes(2);+ expect(mockAdapterClose).toHaveBeenCalledTimes(1);+ });++ it("treats an error with an empty-string .code as non-transient when the message doesn't match either", async () => {+ const errorWithEmptyCode = Object.assign(new Error("boom"), { code: "" });+ mockRuntimeExecute.mockRejectedValueOnce(errorWithEmptyCode);+ const dbConfig = buildDbConfig();++ await expect(+ executeOpenPlaitRead({ query: "SELECT 1", dbConfig })+ ).rejects.toThrow("boom");+ expect(mockRuntimeExecute).toHaveBeenCalledTimes(1);+ });++ it("propagates a raw (non-Error), non-transient rejection immediately", async () => {+ mockRuntimeExecute.mockRejectedValueOnce("just a plain string failure");+ const dbConfig = buildDbConfig();++ await expect(+ executeOpenPlaitRead({ query: "SELECT 1", dbConfig })+ ).rejects.toBe("just a plain string failure");+ expect(mockRuntimeExecute).toHaveBeenCalledTimes(1);+ });++ it("builds a datasource config with an empty password when dbConfig.password is falsy", async () => {+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ const dbConfig = buildDbConfig({ password: null });++ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig });++ expect(mockAdapterCtor).toHaveBeenCalledTimes(1);+ expect(mockAdapterCtor.mock.calls[0][0].password).toBe("");+ });++ it("detects a transient error nested in a .cause chain", async () => {+ const nested = new Error("wrapper", {+ cause: new Error("ECONNRESET while streaming"),+ });+ mockRuntimeExecute+ .mockRejectedValueOnce(nested)+ .mockResolvedValueOnce({ result: { frames: [] } });+ const dbConfig = buildDbConfig();++ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig });++ expect(mockRuntimeExecute).toHaveBeenCalledTimes(2);+ expect(mockAdapterClose).toHaveBeenCalledTimes(1);+ });++ it("propagates a non-transient error immediately without retrying", async () => {+ mockRuntimeExecute.mockRejectedValueOnce(new Error("syntax error"));+ const dbConfig = buildDbConfig();++ await expect(+ executeOpenPlaitRead({ query: "SELECT 1", dbConfig })+ ).rejects.toThrow("syntax error");++ expect(mockRuntimeExecute).toHaveBeenCalledTimes(1);+ expect(mockAdapterClose).not.toHaveBeenCalled();+ });++ it("propagates a second transient failure (retry itself fails) without a further retry", async () => {+ mockRuntimeExecute+ .mockRejectedValueOnce(new Error("ECONNRESET"))+ .mockRejectedValueOnce(new Error("ECONNRESET again"));+ const dbConfig = buildDbConfig();++ await expect(+ executeOpenPlaitRead({ query: "SELECT 1", dbConfig })+ ).rejects.toThrow("ECONNRESET again");++ expect(mockRuntimeExecute).toHaveBeenCalledTimes(2);+ });+});++describe("evictRuntime race guard", () => {+ it("skips deleting/closing when the cache entry was already replaced by a concurrent caller", async () => {+ // Two concurrent `executeOpenPlaitRead` calls for the same dbConfig+ // both grab the same initial cached entry, then both hit a transient+ // error. The second eviction to run must be a no-op: the entry it+ // expected to delete has already been replaced by the first+ // eviction/rebuild, so it should neither delete the newer entry nor+ // close the newer adapter a second time.+ const dbConfig = buildDbConfig();++ let resolveFirstExecuteA: (v: unknown) => void;+ let resolveFirstExecuteB: (v: unknown) => void;+ const firstExecuteA = new Promise((resolve) => {+ resolveFirstExecuteA = resolve;+ });+ const firstExecuteB = new Promise((resolve) => {+ resolveFirstExecuteB = resolve;+ });++ let callCount = 0;+ mockRuntimeExecute.mockImplementation(() => {+ callCount += 1;+ if (callCount === 1) return firstExecuteA.then(() => { throw new Error("ECONNRESET"); });+ if (callCount === 2) return firstExecuteB.then(() => { throw new Error("ECONNRESET"); });+ return Promise.resolve({ result: { frames: [] } });+ });++ const callA = executeOpenPlaitRead({ query: "SELECT 1", dbConfig });+ const callB = executeOpenPlaitRead({ query: "SELECT 2", dbConfig });++ // Both calls have now grabbed the same cached `first` entry (only one+ // adapter/runtime constructed so far) and are awaiting their first+ // `execute()` call.+ await Promise.resolve();+ await Promise.resolve();+ expect(mockAdapterCtor).toHaveBeenCalledTimes(1);++ // Let A's first execute reject, triggering A's evict + rebuild.+ resolveFirstExecuteA!(undefined);+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();++ // Let B's first execute reject too. B's `first` reference is the+ // *original* (now-stale) entry, so its `evictRuntime` call should+ // see the cache already pointing at A's newer entry and no-op.+ resolveFirstExecuteB!(undefined);++ const [resultA, resultB] = await Promise.all([callA, callB]);+ expect(resultA).toEqual([]);+ expect(resultB).toEqual([]);++ // Exactly one adapter close: from A's successful eviction. B's+ // eviction attempt found a mismatched cache entry and skipped both+ // the delete and the close.+ expect(mockAdapterClose).toHaveBeenCalledTimes(1);+ expect(mockAdapterCtor).toHaveBeenCalledTimes(2);+ });+});++describe("closeOpenPlaitRuntimes", () => {+ it("closes every cached adapter and clears the cache so the next call rebuilds", async () => {+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig: buildDbConfig({ id: "db-a" }) });+ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig: buildDbConfig({ id: "db-b" }) });+ expect(mockAdapterCtor).toHaveBeenCalledTimes(2);++ await closeOpenPlaitRuntimes();++ expect(mockAdapterClose).toHaveBeenCalledTimes(2);++ await executeOpenPlaitRead({ query: "SELECT 1", dbConfig: buildDbConfig({ id: "db-a" }) });+ expect(mockAdapterCtor).toHaveBeenCalledTimes(3);+ });++ it("is a no-op when there are no cached runtimes", async () => {+ await expect(closeOpenPlaitRuntimes()).resolves.toBeUndefined();+ expect(mockAdapterClose).not.toHaveBeenCalled();+ });+});++describe("connectionConfig env var parsing (positiveInteger)", () => {+ it("uses defaults when env vars are unset", async () => {+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ await validateOpenPlaitClickHouseConnection(CONNECTION);++ const adapterConfig = mockAdapterCtor.mock.calls[0][0];+ expect(adapterConfig.queryTimeoutMs).toBe(60_000);+ expect(adapterConfig.maxResultRows).toBe(100_000);+ expect(adapterConfig.maxRowsToRead).toBe(10_000_000);+ });++ it.each([+ ["not-a-number", undefined],+ ["0", undefined],+ ["-5", undefined],+ ["3.5", undefined],+ ])(+ "falls back to the default for invalid queryTimeoutMs value %s",+ async (value) => {+ process.env.OPENPLAIT_CLICKHOUSE_QUERY_TIMEOUT_MS = value;+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ await validateOpenPlaitClickHouseConnection(CONNECTION);++ const adapterConfig = mockAdapterCtor.mock.calls[0][0];+ expect(adapterConfig.queryTimeoutMs).toBe(60_000);+ }+ );++ it("accepts a valid positive integer queryTimeoutMs", async () => {+ process.env.OPENPLAIT_CLICKHOUSE_QUERY_TIMEOUT_MS = "5000";+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ await validateOpenPlaitClickHouseConnection(CONNECTION);++ const adapterConfig = mockAdapterCtor.mock.calls[0][0];+ expect(adapterConfig.queryTimeoutMs).toBe(5000);+ const runtimeOptions = mockRuntimeCtor.mock.calls[0][1];+ expect(runtimeOptions.defaultTimeoutMs).toBe(5000);+ });++ it("accepts a valid positive integer maxResultRows and maxRowsToRead", async () => {+ process.env.OPENPLAIT_CLICKHOUSE_MAX_RESULT_ROWS = "42";+ process.env.OPENPLAIT_CLICKHOUSE_MAX_ROWS_TO_READ = "4200";+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ await validateOpenPlaitClickHouseConnection(CONNECTION);++ const adapterConfig = mockAdapterCtor.mock.calls[0][0];+ expect(adapterConfig.maxResultRows).toBe(42);+ expect(adapterConfig.maxRowsToRead).toBe(4200);+ });++ it("falls back to defaults for invalid maxResultRows/maxRowsToRead", async () => {+ process.env.OPENPLAIT_CLICKHOUSE_MAX_RESULT_ROWS = "not-a-number";+ process.env.OPENPLAIT_CLICKHOUSE_MAX_ROWS_TO_READ = "-1";+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ await validateOpenPlaitClickHouseConnection(CONNECTION);++ const adapterConfig = mockAdapterCtor.mock.calls[0][0];+ expect(adapterConfig.maxResultRows).toBe(100_000);+ expect(adapterConfig.maxRowsToRead).toBe(10_000_000);+ });++ it("passes through the OpenLIT ClickHouse datasets and application metadata", async () => {+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ await validateOpenPlaitClickHouseConnection(CONNECTION);++ const adapterConfig = mockAdapterCtor.mock.calls[0][0];+ expect(adapterConfig.datasets).toEqual([+ "otel_traces",+ "otel_logs",+ "otel_metrics",+ "traces",+ "logs",+ "metrics",+ ]);+ expect(adapterConfig.applicationName).toBe("openlit-openplait");+ expect(adapterConfig.allowNativeQueries).toBe(true);+ expect(adapterConfig.requireTimeRange).toBe(false);+ expect(adapterConfig.url).toBe("http://clickhouse.local:8123");+ });++ it("passes httpHeaders parsed from the connection query string", async () => {+ mockRuntimeExecute.mockResolvedValue({ result: { frames: [] } });+ await validateOpenPlaitClickHouseConnection({+ ...CONNECTION,+ query: "foo=bar",+ password: null,+ });++ const adapterConfig = mockAdapterCtor.mock.calls[0][0];+ expect(adapterConfig.httpHeaders).toEqual({ raw: "foo=bar" });+ expect(adapterConfig.password).toBe("");+ });+});diff --git a/src/client/src/__tests__/lib/platform/pricing/chat-cost.test.ts b/src/client/src/__tests__/lib/platform/pricing/chat-cost.test.tsindex fb0f40a5..bd8719a1 100644--- a/src/client/src/__tests__/lib/platform/pricing/chat-cost.test.ts+++ b/src/client/src/__tests__/lib/platform/pricing/chat-cost.test.ts@@ -51,6 +51,14 @@ describe("getChatModelCostPerM", () => {);expect(cost).toBeCloseTo(0.01035, 8);});++ it("defaults missing token/price fields to zero", () => {+ const cost = getChatModelCostPerM(+ { inputPricePerMToken: 0, outputPricePerMToken: 0 },+ { promptTokens: 0, completionTokens: 0 }+ );+ expect(cost).toBe(0);+ });});describe("promptTokensIncludeCache", () => {@@ -70,4 +78,18 @@ describe("promptTokensIncludeCache", () => {expect(promptTokensIncludeCache("unknown", 6200, 5000, 1000)).toBe(true);expect(promptTokensIncludeCache("unknown", 200, 5000, 1000)).toBe(false);});++ it("treats an empty provider name as falling through to the heuristic", () => {+ expect(promptTokensIncludeCache("", 6200, 5000, 1000)).toBe(true);+ });++ it("treats a claude/agent hybrid provider name (not in the explicit set) as inclusive", () => {+ expect(+ promptTokensIncludeCache("some-claude-custom-agent", 100, 0, 0)+ ).toBe(true);+ });++ it("returns false from the heuristic when there are no cache tokens at all", () => {+ expect(promptTokensIncludeCache("unknown", 0, 0, 0)).toBe(false);+ });});diff --git a/src/client/src/__tests__/lib/platform/pricing/cron-analytics.test.ts b/src/client/src/__tests__/lib/platform/pricing/cron-analytics.test.tsindex 6aa198e5..30902594 100644--- a/src/client/src/__tests__/lib/platform/pricing/cron-analytics.test.ts+++ b/src/client/src/__tests__/lib/platform/pricing/cron-analytics.test.ts@@ -88,4 +88,124 @@ describe("getPricingCronAnalytics", () => {"totalUpdated");});++ it("clamps the limit between 1 and 100 and defaults to 25", async () => {+ mockedDataCollector.mockResolvedValue({ data: [{}] });++ await getPricingCronAnalytics(params, { limit: 500 });+ expect(mockedDataCollector.mock.calls[2][0].query).toContain("LIMIT 100");++ mockedDataCollector.mockClear();+ mockedDataCollector.mockResolvedValue({ data: [{}] });+ await getPricingCronAnalytics(params, { limit: 0 });+ expect(mockedDataCollector.mock.calls[2][0].query).toContain("LIMIT 1");++ mockedDataCollector.mockClear();+ mockedDataCollector.mockResolvedValue({ data: [{}] });+ await getPricingCronAnalytics(params);+ expect(mockedDataCollector.mock.calls[2][0].query).toContain("LIMIT 25");+ });++ it("returns zeroed summaries and surfaces the error when the current period query fails", async () => {+ mockedDataCollector+ .mockResolvedValueOnce({ err: "clickhouse down", data: [] })+ .mockResolvedValueOnce({ data: [{ totalRuns: 1, successfulRuns: 1, totalUpdated: 1, totalSpans: 1 }] })+ .mockResolvedValueOnce({ data: [] });++ const res = await getPricingCronAnalytics(params);++ expect(res.data[0]).toEqual(+ expect.objectContaining({+ total_runs: 0,+ successful_runs: 0,+ total_updated: 0,+ total_spans: 0,+ })+ );+ expect(res.err).toBe("clickhouse down");+ });++ it("surfaces the error from the previous period query when only it fails", async () => {+ mockedDataCollector+ .mockResolvedValueOnce({ data: [{ totalRuns: 2, successfulRuns: 2, totalUpdated: 2, totalSpans: 2 }] })+ .mockResolvedValueOnce({ err: "previous failed", data: [] })+ .mockResolvedValueOnce({ data: [] });++ const res = await getPricingCronAnalytics(params);++ expect(res.data[0].previous_total_runs).toBe(0);+ expect(res.err).toBe("previous failed");+ });++ it("surfaces the runs-query error when both summaries succeed", async () => {+ mockedDataCollector+ .mockResolvedValueOnce({ data: [{ totalRuns: 1, successfulRuns: 1, totalUpdated: 1, totalSpans: 1 }] })+ .mockResolvedValueOnce({ data: [{ totalRuns: 1, successfulRuns: 1, totalUpdated: 1, totalSpans: 1 }] })+ .mockResolvedValueOnce({ err: "runs query failed", data: [] });++ const res = await getPricingCronAnalytics(params);++ expect(res.runs).toEqual([]);+ expect(res.err).toBe("runs query failed");+ });++ it("defaults missing numeric fields to 0 and handles an empty runs result set", async () => {+ mockedDataCollector+ .mockResolvedValueOnce({ data: [{}] })+ .mockResolvedValueOnce({ data: [{}] })+ .mockResolvedValueOnce({ data: undefined });++ const res = await getPricingCronAnalytics(params);++ expect(res.data[0]).toEqual({+ total_runs: 0,+ previous_total_runs: 0,+ successful_runs: 0,+ previous_successful_runs: 0,+ total_updated: 0,+ previous_total_updated: 0,+ total_spans: 0,+ previous_total_spans: 0,+ });+ expect(res.runs).toEqual([]);+ expect(res.err).toBeUndefined();+ });++ it("coerces non-finite row fields (missing startedAt/duration) to safe defaults", async () => {+ mockedDataCollector+ .mockResolvedValueOnce({ data: [{}] })+ .mockResolvedValueOnce({ data: [{}] })+ .mockResolvedValueOnce({+ data: [+ {+ duration: "not-a-number",+ totalSpans: undefined,+ },+ ],+ });++ const res = await getPricingCronAnalytics(params);++ expect(res.runs[0]).toEqual({+ startedAt: "",+ finishedAt: "",+ duration: 0,+ runStatus: "",+ totalSpans: 0,+ totalUpdated: 0,+ totalFailed: 0,+ totalSkipped: 0,+ });+ });++ it("treats a non-array summary data payload as an empty row", async () => {+ mockedDataCollector+ .mockResolvedValueOnce({ data: undefined })+ .mockResolvedValueOnce({ data: [{}] })+ .mockResolvedValueOnce({ data: [] });++ const res = await getPricingCronAnalytics(params);++ expect(res.data[0].total_runs).toBe(0);+ });});diff --git a/src/client/src/__tests__/lib/platform/pricing/pricing-config.test.ts b/src/client/src/__tests__/lib/platform/pricing/pricing-config.test.tsindex 5bfe5233..2936daa1 100644--- a/src/client/src/__tests__/lib/platform/pricing/pricing-config.test.ts+++ b/src/client/src/__tests__/lib/platform/pricing/pricing-config.test.ts@@ -50,7 +50,7 @@ jest.mock('path', () => ({join: jest.fn((...args: string[]) => args.join('/')),}));-import { getPricingConfig, setPricingConfig, restorePricingCronJobs } from '@/lib/platform/pricing/config';+import { getPricingConfig, getPricingConfigById, setPricingConfig, restorePricingCronJobs } from '@/lib/platform/pricing/config';import { getDBConfigByUser } from '@/lib/db-config';import prisma from '@/lib/prisma';import asaw from '@/utils/asaw';@@ -58,7 +58,7 @@ import { throwIfError } from '@/utils/error';import Cron from '@/helpers/server/cron';import getMessage from '@/constants/messages';import { randomUUID } from 'crypto';-import { jsonParse } from '@/utils/json';+import { jsonParse, jsonStringify } from '@/utils/json';const mockDBConfig = { id: 'db-1', name: 'test-db' };@@ -86,6 +86,9 @@ beforeEach(() => {(jsonParse as jest.Mock).mockImplementation((v: string) => {try { return JSON.parse(v); } catch { return {}; }});+ // Re-apply jsonStringify mock after resetAllMocks (unlike the `lodash` mock,+ // this aliased module's factory implementation does not survive a reset).+ (jsonStringify as jest.Mock).mockImplementation((v: unknown) => JSON.stringify(v));// Default asaw: wrap a promise into [err, data](asaw as jest.Mock).mockImplementation(async (promise: Promise<any>) => {@@ -129,6 +132,38 @@ describe('getPricingConfig', () => {expect(result).toBeNull();});++ it('uses the provided dbConfig and skips getDBConfigByUser when it already has an id', async () => {+ const mockConfig = { id: 'pc-1', auto: false, recurringTime: '', meta: '{}', databaseConfigId: 'db-provided' };+ (prisma.pricingConfigs.findFirst as jest.Mock).mockResolvedValue(mockConfig);++ const result = await getPricingConfig({ id: 'db-provided' } as any);++ expect(getDBConfigByUser).not.toHaveBeenCalled();+ expect(prisma.pricingConfigs.findFirst).toHaveBeenCalledWith(+ expect.objectContaining({ where: { databaseConfigId: 'db-provided' } })+ );+ expect(result).toEqual(mockConfig);+ });+});++describe('getPricingConfigById', () => {+ it('returns the config when found', async () => {+ const mockConfig = { id: 'pc-1', auto: true, recurringTime: '* * * * *', meta: '{}', databaseConfigId: 'db-1' };+ (prisma.pricingConfigs.findFirst as jest.Mock).mockResolvedValue(mockConfig);++ const result = await getPricingConfigById('pc-1');++ expect(result).toEqual(mockConfig);+ });++ it('returns null when not found', async () => {+ (prisma.pricingConfigs.findFirst as jest.Mock).mockResolvedValue(null);++ const result = await getPricingConfigById('nonexistent');++ expect(result).toBeNull();+ });});describe('setPricingConfig', () => {@@ -210,6 +245,44 @@ describe('setPricingConfig', () => {const cronInstance = (Cron as jest.Mock).mock.results[0].value;expect(cronInstance.deleteCronJob).toHaveBeenCalledWith('existing-cron-id');});++ it('generates a fresh cronJobId and defaults meta to {} when the previous config lookup returns nothing', async () => {+ (getDBConfigByUser as jest.Mock).mockResolvedValue(mockDBConfig);+ // previousConfig lookup (getPricingConfigById -> prisma.findFirst) returns null+ (prisma.pricingConfigs.findFirst as jest.Mock).mockResolvedValue(null);+ (prisma.pricingConfigs.update as jest.Mock).mockResolvedValue({ id: 'pc-missing' });++ await setPricingConfig(+ { id: 'pc-missing', auto: false, recurringTime: '', meta: '{}' },+ 'http://localhost:3000'+ );++ expect(prisma.pricingConfigs.update).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ meta: JSON.stringify({ cronJobId: 'test-cron-uuid' }),+ }),+ })+ );+ });++ it('defaults meta to {} on create when an empty meta string is provided', async () => {+ (getDBConfigByUser as jest.Mock).mockResolvedValue(mockDBConfig);+ (prisma.pricingConfigs.create as jest.Mock).mockResolvedValue({ id: 'pc-new' });++ await setPricingConfig(+ { auto: false, recurringTime: '', meta: '' },+ 'http://localhost:3000'+ );++ expect(prisma.pricingConfigs.create).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ meta: JSON.stringify({ cronJobId: 'test-cron-uuid' }),+ }),+ })+ );+ });});describe('restorePricingCronJobs', () => {@@ -301,4 +374,15 @@ describe('restorePricingCronJobs', () => {restorePricingCronJobs('http://localhost:3000')).resolves.toBeUndefined();});++ it('skips a config with a falsy meta string (defaults to {} then has no cronJobId)', async () => {+ (prisma.pricingConfigs.findMany as jest.Mock).mockResolvedValue([+ { id: 'pc-1', auto: true, recurringTime: '* * * * *', meta: '' },+ ]);++ await restorePricingCronJobs('http://localhost:3000');++ const cronInstance = (Cron as jest.Mock).mock.results[0]?.value;+ expect(cronInstance.updateCrontab).not.toHaveBeenCalled();+ });});diff --git a/src/client/src/__tests__/lib/platform/pricing/pricing.test.ts b/src/client/src/__tests__/lib/platform/pricing/pricing.test.tsindex b39a47d1..0e6401e9 100644--- a/src/client/src/__tests__/lib/platform/pricing/pricing.test.ts+++ b/src/client/src/__tests__/lib/platform/pricing/pricing.test.ts@@ -106,6 +106,7 @@ import { insertCronLog } from '@/lib/platform/cron-log';import getMessage from '@/constants/messages';import { throwIfError } from '@/utils/error';import asaw from '@/utils/asaw';+import Sanitizer from '@/utils/sanitizer';beforeEach(() => {jest.resetAllMocks();@@ -121,6 +122,10 @@ beforeEach(() => {if (condition) throw new Error(msg);});+ // Re-apply Sanitizer mock after resetAllMocks (aliased module factory+ // implementations do not survive a reset, unlike e.g. the `lodash` mock).+ (Sanitizer.sanitizeValue as jest.Mock).mockImplementation((v: string) => v);+// Re-apply insertCronLog mock(insertCronLog as jest.Mock).mockResolvedValue({ err: null });@@ -267,6 +272,56 @@ describe('setPricingForSpanId', () => {expect(result.err).toContain('Missing');});+ it('returns error mentioning only "model" when provider is present but model is missing', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({+ record: {+ SpanId: 'span-1',+ Timestamp: '2026-01-01',+ SpanAttributes: { 'gen_ai.system': 'openai' },+ },+ });++ const result = await setPricingForSpanId('span-1');++ expect(result.success).toBe(false);+ expect(result.err).toContain('Missing model');+ expect(result.err).not.toContain(' and ');+ });++ it('returns error mentioning only "provider" when model is present but provider is missing', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({+ record: {+ SpanId: 'span-1',+ Timestamp: '2026-01-01',+ SpanAttributes: { 'gen_ai.request.model': 'gpt-4o' },+ },+ });++ const result = await setPricingForSpanId('span-1');++ expect(result.success).toBe(false);+ expect(result.err).toContain('Missing provider');+ expect(result.err).not.toContain(' and ');+ });++ it('handles a trace whose SpanAttributes object is entirely absent', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({+ record: {+ SpanId: 'span-1',+ Timestamp: '2026-01-01',+ },+ });++ const result = await setPricingForSpanId('span-1');++ expect(result.success).toBe(false);+ expect(result.err).toContain('Missing');+ expect(result.err).toContain(' and ');+ });+it('throws when user is not authenticated', async () => {(getCurrentUser as jest.Mock).mockResolvedValue(null);@@ -323,6 +378,80 @@ describe('setPricingForSpanId', () => {expect(result.success).toBe(false);expect(result.err).toBe('DB config not found');});++ it('falls back to the user default DB config when no pricing config row exists', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: mockTrace });+ const prisma = require('@/lib/prisma').default;+ prisma.pricingConfigs.findFirst.mockResolvedValue(null);+ // The fallback uses asaw(getDBConfigByUser(true)) — return a real dbConfig+ (asaw as jest.Mock).mockResolvedValue([null, { id: 'fallback-db' }]);+ (ProviderRegistry.getModel as jest.Mock).mockResolvedValue({+ id: 'gpt-4o',+ inputPricePerMToken: 2.5,+ outputPricePerMToken: 10.0,+ });+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });++ const result = await setPricingForSpanId('span-1');++ expect(result.success).toBe(true);+ expect(ProviderRegistry.getModel).toHaveBeenCalledWith(+ 'openai',+ 'gpt-4o',+ 'fallback-db'+ );+ });++ it('passes environment and traceId from opts through to the routed lookup and logging', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: mockTrace });+ (ProviderRegistry.getModel as jest.Mock).mockResolvedValue({+ id: 'gpt-4o',+ inputPricePerMToken: 2.5,+ outputPricePerMToken: 10.0,+ });+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });++ const result = await setPricingForSpanId('span-1', {+ environment: 'prod',+ traceId: 'trace-99',+ });++ expect(result.success).toBe(true);+ const { resolveTelemetrySourceDescriptor } = require('@/lib/telemetry-source');+ expect(resolveTelemetrySourceDescriptor).toHaveBeenCalledWith(+ expect.objectContaining({ signal: 'traces', environment: 'prod' })+ );+ expect(getRequestViaSpanId).toHaveBeenCalledWith(+ 'span-1',+ expect.objectContaining({ environment: 'prod', traceId: 'trace-99' })+ );+ });++ it('reports the cost as unpersisted when routed to a non-clickhouse, non-builtin connector', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });+ (getRequestViaSpanId as jest.Mock).mockResolvedValue({ record: mockTrace });+ (ProviderRegistry.getModel as jest.Mock).mockResolvedValue({+ id: 'gpt-4o',+ inputPricePerMToken: 2.5,+ outputPricePerMToken: 10.0,+ });+ const { resolveTelemetrySourceDescriptor } = require('@/lib/telemetry-source');+ (resolveTelemetrySourceDescriptor as jest.Mock).mockResolvedValue({+ type: 'jaeger',+ id: 'src-1',+ isBuiltIn: false,+ });++ const result = await setPricingForSpanId('span-1');++ expect(result.success).toBe(true);+ expect(result.data!.persisted).toBe(false);+ expect(result.message).toContain('jaeger');+ // Read-only external connector: no ALTER TABLE / exec write+ expect(dataCollector).not.toHaveBeenCalled();+ });});describe('autoUpdatePricing', () => {@@ -541,6 +670,162 @@ describe('autoUpdatePricing', () => {);});+ it('computes lastRunIso from a Date instance and filters the SQL query by it', async () => {+ (getPricingConfigById as jest.Mock).mockResolvedValue({+ id: 'pc-1',+ databaseConfigId: 'db-1',+ });+ (asaw as jest.Mock).mockResolvedValue([null, { id: 'db-1' }]);+ const { getLastRunCronLogByCronId } = require('@/lib/platform/cron-log');+ (getLastRunCronLogByCronId as jest.Mock).mockResolvedValueOnce(+ new Date('2026-01-01T00:00:00.000Z')+ );+ (dataCollector as jest.Mock).mockResolvedValueOnce({ data: [] });++ const result = await autoUpdatePricing({+ pricingConfigId: 'pc-1',+ cronId: 'cron-1',+ });++ expect(result.success).toBe(true);+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).toContain(+ "parseDateTimeBestEffort('2026-01-01T00:00:00.000Z')"+ );+ });++ it('returns an empty trace list when the SELECT query resolves with no data and no error', async () => {+ (getPricingConfigById as jest.Mock).mockResolvedValue({+ id: 'pc-1',+ databaseConfigId: 'db-1',+ });+ (asaw as jest.Mock).mockResolvedValue([null, { id: 'db-1' }]);+ (dataCollector as jest.Mock).mockResolvedValueOnce({ data: undefined, err: null });++ const result = await autoUpdatePricing({+ pricingConfigId: 'pc-1',+ cronId: 'cron-1',+ });++ expect(result.success).toBe(true);+ expect(insertCronLog).toHaveBeenCalledWith(+ expect.objectContaining({+ meta: expect.objectContaining({ totalSpans: 0 }),+ }),+ 'db-1'+ );+ });++ it('records a caught error from fetchAutoPricingCandidateSpans when the routed connector lookup throws', async () => {+ (getPricingConfigById as jest.Mock).mockResolvedValue({+ id: 'pc-1',+ databaseConfigId: 'db-1',+ });+ (asaw as jest.Mock).mockResolvedValue([null, { id: 'db-1' }]);+ const { getTelemetryAdapterForDbConfig } = require('@/lib/telemetry-source');+ (getTelemetryAdapterForDbConfig as jest.Mock).mockRejectedValueOnce(+ new Error('adapter unavailable')+ );++ const result = await autoUpdatePricing({+ pricingConfigId: 'pc-1',+ cronId: 'cron-1',+ });++ expect(result.success).toBe(false);+ expect(result.err).toContain('adapter unavailable');+ expect(insertCronLog).toHaveBeenCalledWith(+ expect.objectContaining({ runStatus: 'FAILURE' }),+ 'db-1'+ );+ });++ it('counts an exception thrown while computing/writing cost as an error and still marks partial success', async () => {+ (getPricingConfigById as jest.Mock).mockResolvedValue({+ id: 'pc-1',+ databaseConfigId: 'db-1',+ });+ (asaw as jest.Mock).mockResolvedValue([null, { id: 'db-1' }]);+ (dataCollector as jest.Mock).mockResolvedValueOnce({+ data: [+ {+ SpanId: 'span-throws',+ Timestamp: '2026-01-01',+ SpanAttributes: {+ 'gen_ai.system': 'openai',+ 'gen_ai.request.model': 'gpt-4o',+ 'gen_ai.usage.input_tokens': '100',+ 'gen_ai.usage.output_tokens': '200',+ },+ },+ {+ SpanId: 'span-ok',+ Timestamp: '2026-01-01',+ SpanAttributes: {+ 'gen_ai.system': 'openai',+ 'gen_ai.request.model': 'gpt-4o',+ 'gen_ai.usage.input_tokens': '100',+ 'gen_ai.usage.output_tokens': '200',+ },+ },+ ],+ });+ (dataCollector as jest.Mock).mockResolvedValueOnce({ err: null }); // ALTER for span-ok++ (ProviderRegistry.getModel as jest.Mock)+ .mockRejectedValueOnce(new Error('model lookup failed'))+ .mockResolvedValueOnce({+ id: 'gpt-4o',+ inputPricePerMToken: 2.5,+ outputPricePerMToken: 10.0,+ });++ const result = await autoUpdatePricing({+ pricingConfigId: 'pc-1',+ cronId: 'cron-1',+ });++ expect(result.success).toBe(true);+ expect(insertCronLog).toHaveBeenCalledWith(+ expect.objectContaining({+ runStatus: 'PARTIAL_SUCCESS',+ errorStacktrace: expect.objectContaining({+ 'span-throws': 'model lookup failed',+ }),+ meta: expect.objectContaining({ totalUpdated: 1, totalFailed: 1 }),+ }),+ 'db-1'+ );+ });++ it('uses lastRunIso (not the 24h default) as the window start for the routed connector', async () => {+ const listSpans = jest.fn().mockResolvedValue({ rows: [] });+ const { getTelemetryAdapterForDbConfig } = require('@/lib/telemetry-source');+ (getTelemetryAdapterForDbConfig as jest.Mock).mockResolvedValue({+ isBuiltIn: false,+ descriptor: { type: 'jaeger', isBuiltIn: false },+ adapter: { listSpans },+ });+ (getPricingConfigById as jest.Mock).mockResolvedValue({+ id: 'pc-1',+ databaseConfigId: 'db-1',+ });+ (asaw as jest.Mock).mockResolvedValue([null, { id: 'db-1' }]);+ const { getLastRunCronLogByCronId } = require('@/lib/platform/cron-log');+ (getLastRunCronLogByCronId as jest.Mock).mockResolvedValueOnce(+ '2026-02-01T00:00:00.000Z'+ );++ const result = await autoUpdatePricing({+ pricingConfigId: 'pc-1',+ cronId: 'cron-1',+ });++ expect(result.success).toBe(true);+ const [{ timeRange }] = listSpans.mock.calls[0];+ expect(timeRange.start).toEqual(new Date('2026-02-01T00:00:00.000Z'));+ });+it('reads candidates from the routed traces connector and does not write otel_traces', async () => {const listSpans = jest.fn().mockResolvedValue({rows: [diff --git a/src/client/src/__tests__/lib/platform/prompt/prompt.test.ts b/src/client/src/__tests__/lib/platform/prompt/prompt.test.tsindex bd4663f4..83b75236 100644--- a/src/client/src/__tests__/lib/platform/prompt/prompt.test.ts+++ b/src/client/src/__tests__/lib/platform/prompt/prompt.test.ts@@ -146,6 +146,14 @@ describe('upsertPromptVersion', () => {upsertPromptVersion({ promptId: 'p1' } as any)).rejects.toThrow('Version object error');});++ it('defaults version, status, and promptId to empty strings in the alert signal when omitted', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null, data: { query_id: 'qid-1' } });+ // No version, status, or promptId supplied -> exercises the `|| ""` fallbacks+ // in the emitManagementAlertSignalSafe call.+ const result = await upsertPromptVersion({} as any);+ expect(result).toBe('Version saved!');+ });});describe('updateDownloadDetails', () => {diff --git a/src/client/src/__tests__/lib/platform/providers/config.test.ts b/src/client/src/__tests__/lib/platform/providers/config.test.tsindex d5672722..59431532 100644--- a/src/client/src/__tests__/lib/platform/providers/config.test.ts+++ b/src/client/src/__tests__/lib/platform/providers/config.test.ts@@ -176,6 +176,53 @@ describe('upsertOpenGroundConfig', () => {);});+ it('sets model_id to NULL in the UPDATE when modelId is provided during an update', async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [{ id: 'cfg-1' }] })+ .mockResolvedValueOnce({ err: null })+ .mockResolvedValueOnce({ data: [mockConfig] });++ await upsertOpenGroundConfig({+ provider: 'openai',+ vaultId: 'vault-2',+ modelId: 'gpt-4o-mini',+ userId: 'user-1',+ databaseConfigId: 'db-1',+ });++ const [{ query }] = (dataCollector as jest.Mock).mock.calls[1];+ expect(query).toContain("model_id = 'gpt-4o-mini'");+ });++ it('catches thrown exceptions during upsert', async () => {+ (dataCollector as jest.Mock).mockRejectedValue(new Error('boom'));++ const result = await upsertOpenGroundConfig({+ provider: 'openai',+ vaultId: 'v',+ userId: 'user-1',+ databaseConfigId: 'db-1',+ });++ expect(result.err).toBe('Operation failed');+ });++ it('returns "Config not found" when the post-update re-fetch (getOpenGroundConfigById) finds nothing', async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [{ id: 'cfg-1' }] }) // exists check+ .mockResolvedValueOnce({ err: null }) // update+ .mockResolvedValueOnce({ data: [] }); // getOpenGroundConfigById re-fetch finds nothing++ const result = await upsertOpenGroundConfig({+ provider: 'openai',+ vaultId: 'vault-2',+ userId: 'user-1',+ databaseConfigId: 'db-1',+ });++ expect(result.err).toBe('Config not found');+ });+it('returns error when insert fails', async () => {(dataCollector as jest.Mock).mockResolvedValueOnce({ data: [] })@@ -230,6 +277,14 @@ describe('deleteOpenGroundConfig', () => {expect(result.err).toBe('Operation failed');});++ it('catches thrown exceptions', async () => {+ (dataCollector as jest.Mock).mockRejectedValue(new Error('boom'));++ const result = await deleteOpenGroundConfig('cfg-1', 'user-1', 'db-1');++ expect(result.err).toBe('Operation failed');+ });});describe('toggleOpenGroundConfigStatus', () => {@@ -250,6 +305,14 @@ describe('toggleOpenGroundConfigStatus', () => {expect(result.err).toBe('Operation failed');});++ it('catches thrown exceptions', async () => {+ (dataCollector as jest.Mock).mockRejectedValue(new Error('boom'));++ const result = await toggleOpenGroundConfigStatus('cfg-1', 'user-1', 'db-1', true);++ expect(result.err).toBe('Operation failed');+ });});describe('getActiveProviders', () => {@@ -271,6 +334,14 @@ describe('getActiveProviders', () => {expect(result.data).toEqual([]);});+ it('returns empty array when data is undefined (no rows, no error)', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: undefined, err: null });++ const result = await getActiveProviders('user-1', 'db-1');++ expect(result.data).toEqual([]);+ });+it('returns error on DB failure', async () => {(dataCollector as jest.Mock).mockResolvedValue({ err: 'fail' });@@ -278,4 +349,12 @@ describe('getActiveProviders', () => {expect(result.err).toBe('Operation failed');});++ it('catches thrown exceptions', async () => {+ (dataCollector as jest.Mock).mockRejectedValue(new Error('boom'));++ const result = await getActiveProviders('user-1', 'db-1');++ expect(result.err).toBe('Operation failed');+ });});diff --git a/src/client/src/__tests__/lib/platform/providers/models-service.test.ts b/src/client/src/__tests__/lib/platform/providers/models-service.test.tsindex 7438a661..b7fa7a88 100644--- a/src/client/src/__tests__/lib/platform/providers/models-service.test.ts+++ b/src/client/src/__tests__/lib/platform/providers/models-service.test.ts@@ -75,6 +75,13 @@ describe('getCustomModels', () => {const result = await getCustomModels('user-1', 'db-1');expect(result.err).toBe('DB error');});++ it('defaults to an empty array when data is undefined (no rows, no error)', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: undefined, err: null });++ const result = await getCustomModels('user-1', 'db-1');+ expect(result.data).toEqual([]);+ });});describe('getCustomModelsGroupedByProvider', () => {@@ -227,6 +234,20 @@ describe('updateCustomModel', () => {);});+ it('includes cache pricing fields in the UPDATE when provided', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });++ const result = await updateCustomModel('user-1', 'db-1', 'id', {+ cacheReadPricePerMToken: 0.3,+ cacheCreationPricePerMToken: 3.75,+ });++ expect(result.data).toBe(true);+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).toContain('cache_read_price_per_m_token = 0.3');+ expect(query).toContain('cache_creation_price_per_m_token = 3.75');+ });+it('returns error when ALTER UPDATE fails', async () => {(dataCollector as jest.Mock).mockResolvedValue({ err: 'alter failed' });diff --git a/src/client/src/__tests__/lib/platform/providers/provider-registry.test.ts b/src/client/src/__tests__/lib/platform/providers/provider-registry.test.tsindex b7051209..a286c3bd 100644--- a/src/client/src/__tests__/lib/platform/providers/provider-registry.test.ts+++ b/src/client/src/__tests__/lib/platform/providers/provider-registry.test.ts@@ -100,6 +100,72 @@ describe('ProviderRegistry', () => {ProviderRegistry.getAvailableProviders('db-1')).rejects.toThrow('Failed to load provider metadata');});++ it('defaults description and configSchema when missing/invalid on the row', async () => {+ mockGetAvailableProviders(+ [+ {+ provider_id: 'bare',+ display_name: 'Bare Provider',+ description: undefined,+ requires_vault: false,+ config_schema: undefined,+ is_default: false,+ },+ ],+ []+ );++ const providers = await ProviderRegistry.getAvailableProviders('db-1');+ const bare = providers.find((p) => p.providerId === 'bare');+ expect(bare!.description).toBe('');+ expect(bare!.configSchema).toEqual({});+ });++ it('keeps configSchema empty when config_schema is invalid JSON', async () => {+ mockGetAvailableProviders(+ [+ {+ provider_id: 'broken',+ display_name: 'Broken Provider',+ description: 'desc',+ requires_vault: false,+ config_schema: '{not valid json',+ is_default: false,+ },+ ],+ []+ );++ const providers = await ProviderRegistry.getAvailableProviders('db-1');+ const broken = providers.find((p) => p.providerId === 'broken');+ expect(broken!.configSchema).toEqual({});+ });++ it('defaults to an empty provider list when data is undefined (no rows, no error)', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: undefined });++ const providers = await ProviderRegistry.getAvailableProviders('db-1');+ expect(providers).toEqual([]);+ });++ it('defaults numeric fields and capabilities when missing from model rows', async () => {+ mockGetAvailableProviders(mockProviderRows, [+ { provider: 'openai', id: 'gpt-min' },+ ]);++ const providers = await ProviderRegistry.getAvailableProviders('db-1');+ const openai = providers.find((p) => p.providerId === 'openai');+ const minModel = openai!.supportedModels.find((m) => m.id === 'gpt-min');+ expect(minModel).toMatchObject({+ contextWindow: 0,+ inputPricePerMToken: 0,+ outputPricePerMToken: 0,+ cacheReadPricePerMToken: 0,+ cacheCreationPricePerMToken: 0,+ capabilities: [],+ });+ });});describe('getProviderById', () => {@@ -128,6 +194,13 @@ describe('ProviderRegistry', () => {ProviderRegistry.getProviderById('openai', 'db-1')).rejects.toThrow('Failed to load provider openai');});++ it('defaults to an empty row list when data is undefined (no rows, no error)', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: undefined });++ const provider = await ProviderRegistry.getProviderById('openai', 'db-1');+ expect(provider).toBeNull();+ });});describe('getModel', () => {@@ -145,6 +218,30 @@ describe('ProviderRegistry', () => {const model = await ProviderRegistry.getModel('openai', 'gpt-99', 'db-1');expect(model).toBeNull();});++ it('propagates DB errors from the underlying models query', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: 'models query failed' });++ await expect(+ ProviderRegistry.getModel('openai', 'gpt-4o', 'db-1')+ ).rejects.toThrow('Failed to load models for provider openai');+ });++ it('defaults numeric fields and capabilities when missing from the row', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({+ data: [{ provider: 'openai', id: 'gpt-min' }],+ });++ const model = await ProviderRegistry.getModel('openai', 'gpt-min', 'db-1');+ expect(model).toMatchObject({+ contextWindow: 0,+ inputPricePerMToken: 0,+ outputPricePerMToken: 0,+ cacheReadPricePerMToken: 0,+ cacheCreationPricePerMToken: 0,+ capabilities: [],+ });+ });});describe('searchProviders', () => {@@ -179,5 +276,12 @@ describe('ProviderRegistry', () => {expect(models).toHaveLength(1);expect(models[0].id).toBe('gpt-4o');});++ it('defaults to an empty list when data is undefined (no rows, no error)', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ data: undefined });++ const models = await ProviderRegistry.getProviderModels('openai', 'db-1');+ expect(models).toEqual([]);+ });});});diff --git a/src/client/src/__tests__/lib/platform/rule-engine/evaluate.test.ts b/src/client/src/__tests__/lib/platform/rule-engine/evaluate.test.tsindex 2766b768..eea34d64 100644--- a/src/client/src/__tests__/lib/platform/rule-engine/evaluate.test.ts+++ b/src/client/src/__tests__/lib/platform/rule-engine/evaluate.test.ts@@ -122,6 +122,20 @@ describe('evaluateRules', () => {evaluateRules({ fields: { model: 'gpt-4' }, entity_type: 'context', include_entity_data: false })).rejects.toThrow('DB error');});++ it('stringifies a non-toStringable error object', async () => {+ const err = Object.create(null);+ (dataCollector as jest.Mock).mockResolvedValue({ err, data: null });+ await expect(+ evaluateRules({ fields: { model: 'gpt-4' }, entity_type: 'context', include_entity_data: false })+ ).rejects.toThrow();+ });++ it('defaults to an empty rows array when data is missing on success', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null, data: undefined });+ const result = await evaluateRules({ fields: { model: 'gpt-4' }, entity_type: 'context', include_entity_data: false });+ expect(result).toEqual({ matchingRuleIds: [], entities: [] });+ });});describe('include_entity_data = false', () => {diff --git a/src/client/src/__tests__/lib/platform/rule-engine/rule-engine.test.ts b/src/client/src/__tests__/lib/platform/rule-engine/rule-engine.test.tsindex bea742c4..3c58e015 100644--- a/src/client/src/__tests__/lib/platform/rule-engine/rule-engine.test.ts+++ b/src/client/src/__tests__/lib/platform/rule-engine/rule-engine.test.ts@@ -132,6 +132,17 @@ describe('getRuleById', () => {});});+ it('defaults groups/conditions to empty arrays when data is missing', async () => {+ const rule = { id: 'r1', name: 'Test Rule' };+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [rule], err: null })+ .mockResolvedValueOnce({ data: null, err: null })+ .mockResolvedValueOnce({ data: undefined, err: null });++ const result = await getRuleById('r1');+ expect(result.data).toMatchObject({ id: 'r1', condition_groups: [] });+ });+it('attaches conditions to their parent group', async () => {const rule = { id: 'r1', name: 'Rule' };const group1 = { id: 'g1', rule_id: 'r1' };@@ -189,6 +200,12 @@ describe('createRule', () => {await createRule({ name: 'r' }, { databaseConfigId: 'db-2' });expect(dataCollector).toHaveBeenCalledWith(expect.any(Object), 'exec', 'db-2');});++ it('falls back to the generated rule id in the alert message when name is missing', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null, data: {} });+ const result = await createRule({});+ expect(result).toMatchObject({ message: 'Rule created!' });+ });});// ---------------------------------------------------------------------------@@ -222,6 +239,26 @@ describe('updateRule', () => {const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];expect(query).toContain('rule-abc');});++ it('routes the update to the selected database config and skips the alert', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null, data: { query_id: 'q1' } });+ await updateRule(+ 'r1',+ { name: 'Updated', description: '', group_operator: 'OR', status: 'INACTIVE' },+ { databaseConfigId: 'db-2', emitAlert: false }+ );+ expect(dataCollector).toHaveBeenCalledWith(expect.any(Object), 'exec', 'db-2');+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).toContain("description = ''");+ expect(query).toContain("group_operator = 'OR'");+ expect(query).toContain("status = 'INACTIVE'");+ });++ it('falls back to the rule id in the alert message when name is missing', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null, data: { query_id: 'q1' } });+ const result = await updateRule('r1', {});+ expect(result).toEqual({ message: 'Rule updated!' });+ });});// ---------------------------------------------------------------------------@@ -255,6 +292,15 @@ describe('deleteRule', () => {expect(queries.some((q: string) => q.includes('openlit_rule_conditions'))).toBe(true);expect(queries.some((q: string) => q.includes('openlit_rule_entities'))).toBe(true);});++ it('routes all 4 parallel deletes to the selected database config', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });+ await deleteRule('r1', { databaseConfigId: 'db-9', emitAlert: false });+ expect(dataCollector).toHaveBeenCalledTimes(4);+ for (const call of (dataCollector as jest.Mock).mock.calls) {+ expect(call[2]).toBe('db-9');+ }+ });});// ---------------------------------------------------------------------------@@ -307,6 +353,47 @@ describe('addConditionGroupsToRule', () => {const result = await addConditionGroupsToRule('r1', [group as any]);expect(result).toEqual({ message: 'Group added!' });});++ it('routes every delete/insert query to the selected database config', async () => {+ const group = { condition_operator: 'AND', conditions: [{ field: 'f', operator: 'equals', value: 'v' }] };+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });+ await addConditionGroupsToRule('r1', [group as any], { databaseConfigId: 'db-7', emitAlert: false });+ expect(dataCollector).toHaveBeenCalledTimes(4);+ for (const call of (dataCollector as jest.Mock).mock.calls) {+ expect(call[2]).toBe('db-7');+ }+ });++ it('defaults the condition_operator to AND when the group omits it', async () => {+ const group = { conditions: [] as any[] };+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });+ await addConditionGroupsToRule('r1', [group as any]);+ const insertGroupCall = (dataCollector as jest.Mock).mock.calls.find((c: any[]) =>+ String(c[0].query).includes('INSERT INTO openlit_rule_condition_groups')+ );+ expect(insertGroupCall[0].query).toContain("'AND'");+ });++ it('treats a missing conditions array on the group as empty', async () => {+ const group = { condition_operator: 'AND' };+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });+ const result = await addConditionGroupsToRule('r1', [group as any]);+ expect(result).toEqual({ message: 'Group added!' });+ // Only the 2 deletes + 1 group insert — no conditions insert.+ expect(dataCollector).toHaveBeenCalledTimes(3);+ });++ it('throws when the conditions insert fails', async () => {+ const group = { condition_operator: 'AND', conditions: [{ field: 'f', operator: 'equals', value: 'v' }] };+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ err: null }) // delete groups+ .mockResolvedValueOnce({ err: null }) // delete conditions+ .mockResolvedValueOnce({ err: null }) // insert group+ .mockResolvedValueOnce({ err: new Error('cond insert error') }); // insert conditions fails+ await expect(addConditionGroupsToRule('r1', [group as any])).rejects.toThrow(+ 'cond insert error'+ );+ });});// ---------------------------------------------------------------------------@@ -340,6 +427,21 @@ describe('addRuleEntity', () => {const [{ table }] = (dataCollector as jest.Mock).mock.calls[0];expect(table).toBe('openlit_rule_entities');});++ it('routes the insert to the selected database config', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });+ await addRuleEntity(+ { rule_id: 'r1', entity_type: 'context', entity_id: 'e1' },+ { databaseConfigId: 'db-3' }+ );+ expect(dataCollector).toHaveBeenCalledWith(expect.any(Object), 'insert', 'db-3');+ });++ it('falls back to defaults in the alert payload when entity fields are missing', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });+ const result = await addRuleEntity({});+ expect(result).toEqual({ message: 'Entity associated!' });+ });});// ---------------------------------------------------------------------------@@ -368,7 +470,12 @@ describe('deleteRuleEntity', () => {await deleteRuleEntity('entity-xyz');const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];expect(query).toContain('entity-xyz');- expect(query).toContain('openlit_rule_entities');+ });++ it('routes the delete to the selected database config', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });+ await deleteRuleEntity('e1', { databaseConfigId: 'db-4', emitAlert: false });+ expect(dataCollector).toHaveBeenCalledWith(expect.any(Object), 'exec', 'db-4');});});diff --git a/src/client/src/__tests__/lib/platform/rule-engine/source.test.ts b/src/client/src/__tests__/lib/platform/rule-engine/source.test.tsindex 86b92e9a..9584b650 100644--- a/src/client/src/__tests__/lib/platform/rule-engine/source.test.ts+++ b/src/client/src/__tests__/lib/platform/rule-engine/source.test.ts@@ -102,4 +102,35 @@ describe("resolveRuleEngineDatabaseConfigId", () => {resolveRuleEngineDatabaseConfigId(requestWithContext({ environment: "staging" }))).rejects.toThrow("requires a ClickHouse datasource");});++ it("rejects a forged ClickHouse id when getDBConfigByUser does not return an array", async () => {+ (getDBConfigByUser as jest.Mock).mockResolvedValue(undefined);++ await expect(+ resolveRuleEngineDatabaseConfigId(requestWithContext({ databaseConfigId: "db-forged" }))+ ).rejects.toThrow("not available in the current project");+ });++ it("falls back to the project's default intelligence ClickHouse binding when nothing is selected", async () => {+ (resolveSignalSource as jest.Mock).mockResolvedValue({+ hasSource: true,+ descriptor: { type: "clickhouse", dbConfigId: "db-default" },+ });++ await expect(resolveRuleEngineDatabaseConfigId(requestWithContext())).resolves.toBe(+ "db-default"+ );+ expect(resolveSignalSource).toHaveBeenCalledWith("intelligence", {});+ });++ it("fails closed when no environment or header is set and there is no default ClickHouse", async () => {+ (resolveSignalSource as jest.Mock).mockResolvedValue({+ hasSource: false,+ descriptor: { type: "tempo", dbConfigId: undefined },+ });++ await expect(resolveRuleEngineDatabaseConfigId(requestWithContext())).rejects.toThrow(+ "requires a ClickHouse datasource"+ );+ });});diff --git a/src/client/src/__tests__/lib/platform/rule-engine/telemetry.test.ts b/src/client/src/__tests__/lib/platform/rule-engine/telemetry.test.tsindex fd162bb2..991da4ed 100644--- a/src/client/src/__tests__/lib/platform/rule-engine/telemetry.test.ts+++ b/src/client/src/__tests__/lib/platform/rule-engine/telemetry.test.ts@@ -38,4 +38,75 @@ describe("listRecentRuleTraces", () => {)).toBe("production");});++ it("throws when the underlying trace read reports an error", async () => {+ (listTraceRecords as jest.Mock).mockResolvedValue({+ err: "boom",+ records: [],+ });++ await expect(listRecentRuleTraces()).rejects.toThrow("boom");+ });++ it("defaults limit/environment and returns an empty list when records is missing", async () => {+ (listTraceRecords as jest.Mock).mockResolvedValue({ err: null });++ const records = await listRecentRuleTraces();+ expect(records).toEqual([]);+ const calls = (listTraceRecords as jest.Mock).mock.calls;+ const params = calls[calls.length - 1][0];+ expect(params.limit).toBe(100);+ expect(params.environment).toBeUndefined();+ });++ it("falls back to the span-level deployment.environment attribute when the resource attribute is missing", () => {+ expect(+ getRuleTraceFieldValue(+ { SpanAttributes: { "deployment.environment": "staging" } },+ "deployment.environment"+ )+ ).toBe("staging");+ });++ it("falls back to gen_ai.environment when no deployment.environment attribute exists", () => {+ expect(+ getRuleTraceFieldValue(+ { SpanAttributes: { "gen_ai.environment": "legacy-env" } },+ "deployment.environment"+ )+ ).toBe("legacy-env");+ });++ it("returns an empty string when no environment attribute is present at all", () => {+ expect(getRuleTraceFieldValue({}, "deployment.environment")).toBe("");+ });++ it("reads a mapped span-attribute field", () => {+ expect(+ getRuleTraceFieldValue(+ { SpanAttributes: { "gen_ai.system": "openai" } },+ "gen_ai.system"+ )+ ).toBe("openai");+ });++ it("returns an empty string for a mapped attribute field with no value present", () => {+ expect(getRuleTraceFieldValue({}, "gen_ai.request.model")).toBe("");+ });++ it("reads a mapped direct field", () => {+ expect(+ getRuleTraceFieldValue({ ServiceName: "checkout-api" }, "ServiceName")+ ).toBe("checkout-api");+ });++ it("falls back to indexing the trace by the raw field name when unmapped", () => {+ expect(getRuleTraceFieldValue({ CustomColumn: "value-1" }, "CustomColumn")).toBe(+ "value-1"+ );+ });++ it("returns an empty string when an unmapped field is absent", () => {+ expect(getRuleTraceFieldValue({}, "NotARealField")).toBe("");+ });});diff --git a/src/client/src/__tests__/lib/platform/telemetry-snapshot/index.test.ts b/src/client/src/__tests__/lib/platform/telemetry-snapshot/index.test.tsindex bab7f944..8b9eb558 100644--- a/src/client/src/__tests__/lib/platform/telemetry-snapshot/index.test.ts+++ b/src/client/src/__tests__/lib/platform/telemetry-snapshot/index.test.ts@@ -176,4 +176,64 @@ describe("captureInstanceSnapshot", () => {expect(result.properties?.spans_total).toBe(0);});++ it("falls back to the raw payload and treats a non-array result as zero when the response has no .data array", async () => {+ process.env.npm_package_version = "1.0.0";++ // No wrapping `.data` property at all: the `?.data ?? data` fallback+ // must use the raw payload, which here is itself an array.+ (dataCollector as jest.Mock).mockResolvedValueOnce([{ c: 8 }]);+ const arrayResult = await captureInstanceSnapshot();+ expect(arrayResult.properties?.spans_total).toBe(8);++ // `.data` is explicitly null (nullish): falls back to the raw+ // payload, which is a non-array object, so `first` stays undefined.+ (dataCollector as jest.Mock).mockResolvedValue({ data: null });+ const nonArrayResult = await captureInstanceSnapshot();+ expect(nonArrayResult.properties?.spans_total).toBe(0);+ });++ it("reads the version from package.json and falls back to unknown when the field is missing", async () => {+ (readFileSync as jest.Mock).mockReturnValue(JSON.stringify({}));++ const result = await captureInstanceSnapshot();++ expect(result.properties?.openlit_version).toBe("unknown");+ });++ it("defaults to an empty database config list and zero counts when the lookup fails", async () => {+ process.env.npm_package_version = "1.0.0";+ (prisma.databaseConfig.findMany as jest.Mock).mockRejectedValue(+ new Error("db down")+ );++ const result = await captureInstanceSnapshot();++ expect(result.success).toBe(true);+ expect(result.properties).toMatchObject({+ spans_total: 0,+ traces_total: 0,+ app_agents_total: 0,+ });+ expect(dataCollector).not.toHaveBeenCalled();+ });++ it("falls back to zero/false for aggregate counts when the underlying prisma queries fail to resolve", async () => {+ process.env.npm_package_version = "1.0.0";+ (prisma.user.count as jest.Mock).mockResolvedValue(undefined);+ (prisma.organisation.count as jest.Mock).mockResolvedValue(null);+ (prisma.project.count as jest.Mock).mockRejectedValue(new Error("boom"));+ (prisma.databaseConfig.count as jest.Mock).mockResolvedValue(undefined);+ (prisma.pricingConfigs.count as jest.Mock).mockResolvedValue(undefined);++ const result = await captureInstanceSnapshot();++ expect(result.properties).toMatchObject({+ users_total: 0,+ organisations_total: 0,+ projects_total: 0,+ db_configs_total: 0,+ pricing_auto_enabled: false,+ });+ });});diff --git a/src/client/src/__tests__/lib/platform/telemetry/rollups.test.ts b/src/client/src/__tests__/lib/platform/telemetry/rollups.test.tsindex b8b1f7ab..27793e2b 100644--- a/src/client/src/__tests__/lib/platform/telemetry/rollups.test.ts+++ b/src/client/src/__tests__/lib/platform/telemetry/rollups.test.ts@@ -9,7 +9,15 @@ jest.mock("@/lib/platform/agents/logger", () => ({agentsLogger: { error: (...args: unknown[]) => mockLogError(...args) },}));-import { materializeTelemetryRollups } from "@/lib/platform/telemetry/rollups";+import {+ materializeTelemetryRollups,+ readLlmRollup,+ readSignalBucketRollup,+ readSpanHotCache,+ writeSpanHotCache,+ SPAN_HOT_CACHE_MAX_ROWS,+} from "@/lib/platform/telemetry/rollups";+import type { OpenLITQuery } from "@/lib/platform/connectors/datasource/types";const rootSpan = {traceId: "trace-1",@@ -89,4 +97,477 @@ describe("external telemetry rollup materialization", () => {expect.any(Object));});++ it("falls back to an unscoped ('') service pass when no service can be discovered or sampled", async () => {+ const unnamedSpan = { ...rootSpan, serviceName: "", resourceAttributes: {} };+ const sampleTracesForGraph = jest.fn().mockResolvedValue([unnamedSpan]);+ const adapter = { sampleCacheKey: "rollup-unscoped", sampleTracesForGraph };++ const result = await materializeTelemetryRollups({+ adapter: adapter as never,+ sourceId: "tempo-1",+ });++ expect(result.buckets).toBeGreaterThan(0);+ const bucketCall = mockDataCollector.mock.calls.find((c) =>+ (c[0].query as string).includes("INSERT INTO openlit_signal_buckets")+ );+ expect(bucketCall?.[0].query).toContain("'tempo-1',\n\t\t\t\t\t\t'',");+ });++ it("logs and continues when the signal-bucket insert fails", async () => {+ mockDataCollector.mockImplementation((query: { query: string }) => {+ if (query.query.includes("INSERT INTO openlit_signal_buckets")) {+ return Promise.reject(new Error("bucket insert failed"));+ }+ return Promise.resolve({ data: [], err: null });+ });+ const sampleTracesForGraph = jest.fn().mockResolvedValue([rootSpan]);+ const adapter = { sampleCacheKey: "rollup-bucket-fail", sampleTracesForGraph };++ const result = await materializeTelemetryRollups({+ adapter: adapter as never,+ sourceId: "tempo-1",+ });++ expect(result.buckets).toBe(0);+ expect(result.llmRows).toBeGreaterThan(0);+ expect(mockLogError).toHaveBeenCalledWith(+ "telemetry_rollup_buckets_failed",+ expect.any(Object)+ );+ });++ it("logs and continues (per dimension) when an LLM rollup insert fails", async () => {+ mockDataCollector.mockImplementation((query: { query: string }) => {+ if (query.query.includes("INSERT INTO openlit_llm_rollups")) {+ return Promise.reject(new Error("llm insert failed"));+ }+ return Promise.resolve({ data: [], err: null });+ });+ const sampleTracesForGraph = jest.fn().mockResolvedValue([rootSpan]);+ const adapter = { sampleCacheKey: "rollup-llm-fail", sampleTracesForGraph };++ const result = await materializeTelemetryRollups({+ adapter: adapter as never,+ sourceId: "tempo-1",+ });++ expect(result.llmRows).toBe(0);+ expect(result.buckets).toBeGreaterThan(0);+ expect(mockLogError).toHaveBeenCalledWith(+ "telemetry_rollup_llm_failed",+ expect.objectContaining({ dimension: "model" })+ );+ });++ it("scopes buckets/dimensions per service when multiple services are sampled", async () => {+ const checkoutSpan = rootSpan;+ const billingSpan = {+ ...rootSpan,+ traceId: "trace-2",+ spanId: "span-2",+ serviceName: "billing",+ resourceAttributes: { ...rootSpan.resourceAttributes, "service.name": "billing" },+ };+ const sampleTracesForGraph = jest.fn().mockResolvedValue([checkoutSpan, billingSpan]);+ const adapter = { sampleCacheKey: "rollup-multi-service", sampleTracesForGraph };++ const result = await materializeTelemetryRollups({+ adapter: adapter as never,+ sourceId: "tempo-1",+ });++ expect(result.buckets).toBeGreaterThan(0);+ expect(result.llmRows).toBeGreaterThan(0);+ const bucketCalls = mockDataCollector.mock.calls.filter((c) =>+ (c[0].query as string).includes("INSERT INTO openlit_signal_buckets")+ );+ const services = bucketCalls.map((c) => (c[0].query as string).match(/'tempo-1',\n\t*'([^']*)'/)?.[1]);+ expect(services).toEqual(expect.arrayContaining(["checkout", "billing"]));+ });++ it("logs and continues when the hot-cache write fails", async () => {+ mockDataCollector.mockImplementation((query: { query: string }) => {+ if (query.query.includes("INSERT INTO openlit_external_span_cache")) {+ return Promise.reject(new Error("hot cache write failed"));+ }+ return Promise.resolve({ data: [], err: null });+ });+ const sampleTracesForGraph = jest.fn().mockResolvedValue([rootSpan]);+ const adapter = { sampleCacheKey: "rollup-hotcache-fail", sampleTracesForGraph };++ const result = await materializeTelemetryRollups({+ adapter: adapter as never,+ sourceId: "tempo-1",+ });++ expect(result.hotCacheRows).toBe(0);+ expect(mockLogError).toHaveBeenCalledWith(+ "telemetry_hot_cache_failed",+ expect.any(Object)+ );+ });+});++function baseQuery(overrides?: Partial<OpenLITQuery>): OpenLITQuery {+ return {+ signal: "traces",+ timeRange: {+ start: new Date("2026-01-01T00:00:00.000Z"),+ end: new Date("2026-01-02T00:00:00.000Z"),+ },+ ...overrides,+ };+}++describe("readSignalBucketRollup", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("returns null when the collector reports an error", async () => {+ mockDataCollector.mockResolvedValue({ data: null, err: "boom" });+ const result = await readSignalBucketRollup(baseQuery());+ expect(result).toBeNull();+ });++ it("returns null when data is not an array", async () => {+ mockDataCollector.mockResolvedValue({ data: { not: "an array" }, err: null });+ const result = await readSignalBucketRollup(baseQuery());+ expect(result).toBeNull();+ });++ it("returns null when data is empty", async () => {+ mockDataCollector.mockResolvedValue({ data: [], err: null });+ const result = await readSignalBucketRollup(baseQuery());+ expect(result).toBeNull();+ });++ it("returns null when no row has a finite updated_at (newest stays 0)", async () => {+ mockDataCollector.mockResolvedValue({+ data: [{ bucket: "b1", updated_at: "not-a-date" }],+ err: null,+ });+ const result = await readSignalBucketRollup(baseQuery());+ expect(result).toBeNull();+ });++ it("returns null when the freshest row is stale", async () => {+ mockDataCollector.mockResolvedValue({+ data: [{ bucket: "b1", updated_at: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString() }],+ err: null,+ });+ const result = await readSignalBucketRollup(baseQuery());+ expect(result).toBeNull();+ });++ it("returns a degraded frame with fresh rows, custom aggregation alias, and array/scalar filters", async () => {+ mockDataCollector.mockResolvedValue({+ data: [+ { bucket: "b1", count: 3, updated_at: new Date().toISOString() },+ { bucket: "b2", count: 1, updated_at: "garbage-timestamp" },+ ],+ err: null,+ });+ const result = await readSignalBucketRollup(+ baseQuery({+ aggregations: [{ fn: "count", as: "requests" }],+ filters: [+ { target: "attribute", scope: "resource", key: "service.name", op: "eq", value: ["svc-a", "svc-b"] },+ { target: "attribute", scope: "resource", key: "deployment.environment", op: "eq", value: "production" },+ { target: "attribute", scope: "resource", key: "deployment.environment", op: "eq", value: "" },+ { target: "attribute", scope: "resource", key: "deployment.environment", op: "eq", value: undefined as never },+ { target: "duration", scope: "span", op: "gt", value: 1 } as never,+ ],+ }),+ { sourceId: "tempo-1", dbConfigId: "db-9" }+ );+ expect(result).toMatchObject({ meta: { degraded: ["rollup"], freshness: "accelerated" } });+ expect(result?.rows).toHaveLength(2);+ expect(result?.rows.every((row) => !("updated_at" in (row as object)))).toBe(true);+ });++ it("returns null when the collector throws", async () => {+ mockDataCollector.mockRejectedValue(new Error("connection reset"));+ const result = await readSignalBucketRollup(baseQuery());+ expect(result).toBeNull();+ });++ it("defaults sourceId to an empty string when opts is omitted", async () => {+ mockDataCollector.mockResolvedValue({ data: [], err: null });+ await readSignalBucketRollup(baseQuery());+ const sql = mockDataCollector.mock.calls[0][0].query as string;+ expect(sql).toContain("source_id = ''");+ });+});++describe("readLlmRollup", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("defaults the dimension to the query's first groupBy entry, then to 'model'", async () => {+ mockDataCollector.mockResolvedValue({ data: [], err: null });+ await readLlmRollup(baseQuery({ groupBy: ["provider"] }));+ let sql = mockDataCollector.mock.calls[0][0].query as string;+ expect(sql).toContain("dimension = 'provider'");++ mockDataCollector.mockClear();+ await readLlmRollup(baseQuery());+ sql = mockDataCollector.mock.calls[0][0].query as string;+ expect(sql).toContain("dimension = 'model'");+ });++ it("uses the explicit opts.dimension over the query groupBy", async () => {+ mockDataCollector.mockResolvedValue({ data: [], err: null });+ await readLlmRollup(baseQuery({ groupBy: ["provider"] }), { dimension: "category" });+ const sql = mockDataCollector.mock.calls[0][0].query as string;+ expect(sql).toContain("dimension = 'category'");+ });++ it("defaults the limit to 100 when the query omits it", async () => {+ mockDataCollector.mockResolvedValue({ data: [], err: null });+ await readLlmRollup(baseQuery());+ const sql = mockDataCollector.mock.calls[0][0].query as string;+ expect(sql).toContain("LIMIT 100");+ });++ it("returns null when the collector reports an error", async () => {+ mockDataCollector.mockResolvedValue({ data: null, err: "boom" });+ expect(await readLlmRollup(baseQuery())).toBeNull();+ });++ it("returns null when data is empty", async () => {+ mockDataCollector.mockResolvedValue({ data: [], err: null });+ expect(await readLlmRollup(baseQuery())).toBeNull();+ });++ it("returns null when the freshest row is stale", async () => {+ mockDataCollector.mockResolvedValue({+ data: [{ group_value: "gpt-4o", updated_at: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString() }],+ err: null,+ });+ expect(await readLlmRollup(baseQuery())).toBeNull();+ });++ it("returns a degraded frame with fresh rows", async () => {+ mockDataCollector.mockResolvedValue({+ data: [{ group_value: "gpt-4o", count: 2, updated_at: new Date().toISOString() }],+ err: null,+ });+ const result = await readLlmRollup(baseQuery());+ expect(result).toMatchObject({ meta: { degraded: ["rollup"], freshness: "accelerated" } });+ });++ it("returns null when the collector throws", async () => {+ mockDataCollector.mockRejectedValue(new Error("boom"));+ expect(await readLlmRollup(baseQuery())).toBeNull();+ });+});++describe("readSpanHotCache", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("returns null when the collector reports an error", async () => {+ mockDataCollector.mockResolvedValue({ data: null, err: "boom" });+ const result = await readSpanHotCache(baseQuery(), { sourceId: "tempo-1" });+ expect(result).toBeNull();+ });++ it("returns null when data is empty", async () => {+ mockDataCollector.mockResolvedValue({ data: [], err: null });+ const result = await readSpanHotCache(baseQuery(), { sourceId: "tempo-1" });+ expect(result).toBeNull();+ });++ it("returns null when the freshest row is stale", async () => {+ mockDataCollector.mockResolvedValue({+ data: [{ trace_id: "t1", updated_at: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString() }],+ err: null,+ });+ const result = await readSpanHotCache(baseQuery(), { sourceId: "tempo-1" });+ expect(result).toBeNull();+ });++ it("caps the limit at SPAN_HOT_CACHE_MAX_ROWS even when opts.maxRows requests more", async () => {+ mockDataCollector.mockResolvedValue({ data: [], err: null });+ await readSpanHotCache(baseQuery(), {+ sourceId: "tempo-1",+ maxRows: SPAN_HOT_CACHE_MAX_ROWS + 500,+ });+ const sql = mockDataCollector.mock.calls[0][0].query as string;+ expect(sql).toContain(`LIMIT ${SPAN_HOT_CACHE_MAX_ROWS + 1}`);+ });++ it("falls back to the query limit, then to 100, when opts.maxRows is omitted", async () => {+ mockDataCollector.mockResolvedValue({ data: [], err: null });+ await readSpanHotCache(baseQuery({ limit: 42 }), { sourceId: "tempo-1" });+ const sql = mockDataCollector.mock.calls[0][0].query as string;+ expect(sql).toContain("LIMIT 43");+ });++ it("returns fresh spans, parses attribute JSON, and reports truncation when the extra probe row exists", async () => {+ const now = new Date().toISOString();+ mockDataCollector.mockResolvedValue({+ data: [+ {+ trace_id: "t1",+ span_id: "s1",+ parent_span_id: "",+ name: "chat",+ service_name: "checkout",+ timestamp: now,+ duration_ns: 100,+ status_code: "OK",+ status_message: "",+ span_kind: "",+ span_attributes: '{"a":"b"}',+ resource_attributes: { c: "d" },+ cost: 0,+ updated_at: now,+ },+ {+ trace_id: "t2",+ span_id: "s2",+ updated_at: now,+ },+ ],+ err: null,+ });+ const result = await readSpanHotCache(baseQuery({ limit: 1 }), { sourceId: "tempo-1" });+ expect(result?.truncated).toBe(true);+ expect(result?.spans).toHaveLength(1);+ expect(result?.spans[0].spanAttributes).toEqual({ a: "b" });+ expect(result?.spans[0].resourceAttributes).toEqual({ c: "d" });+ });++ it("parses malformed span_attributes JSON as an empty object", async () => {+ const now = new Date().toISOString();+ mockDataCollector.mockResolvedValue({+ data: [+ {+ trace_id: "t1",+ span_id: "s1",+ span_attributes: "{not-json",+ resource_attributes: "",+ updated_at: now,+ },+ ],+ err: null,+ });+ const result = await readSpanHotCache(baseQuery({ limit: 10 }), { sourceId: "tempo-1" });+ expect(result?.spans[0].spanAttributes).toEqual({});+ expect(result?.spans[0].resourceAttributes).toEqual({});+ expect(result?.truncated).toBe(false);+ });++ it("defaults every field on a bare row and drops null attribute values", async () => {+ const now = new Date().toISOString();+ mockDataCollector.mockResolvedValue({+ data: [+ {+ updated_at: now,+ span_attributes: { a: null },+ resource_attributes: '{"b":null}',+ },+ ],+ err: null,+ });+ const result = await readSpanHotCache(baseQuery({ limit: 10 }), { sourceId: "tempo-1" });+ const span = result?.spans[0];+ expect(span).toMatchObject({+ traceId: "",+ spanId: "",+ parentSpanId: "",+ name: "",+ serviceName: "",+ timestamp: "",+ durationNs: 0,+ statusCode: "",+ statusMessage: undefined,+ spanKind: undefined,+ cost: undefined,+ });+ expect(span?.spanAttributes).toEqual({ a: "" });+ expect(span?.resourceAttributes).toEqual({ b: "" });+ });++ it("returns null when the collector throws", async () => {+ mockDataCollector.mockRejectedValue(new Error("boom"));+ const result = await readSpanHotCache(baseQuery(), { sourceId: "tempo-1" });+ expect(result).toBeNull();+ });+});++describe("writeSpanHotCache", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockDataCollector.mockResolvedValue({ data: null, err: null });+ });++ it("returns 0 and skips the insert when there are no spans", async () => {+ const result = await writeSpanHotCache({ sourceId: "tempo-1", spans: [] });+ expect(result).toBe(0);+ expect(mockDataCollector).not.toHaveBeenCalled();+ });++ it("defaults spanAttributes/resourceAttributes to {} in the insert JSON when they are missing", async () => {+ const bareSpan = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "checkout",+ timestamp: "",+ durationNs: 0,+ statusCode: "OK",+ };+ const result = await writeSpanHotCache({+ sourceId: "tempo-1",+ spans: [bareSpan as never],+ });+ expect(result).toBe(1);+ const sql = mockDataCollector.mock.calls[0][0].query as string;+ expect(sql).toContain("'{}'");+ });++ it("caps spans at SPAN_HOT_CACHE_MAX_ROWS and falls back to resource/span environment or blank", async () => {+ const spanWithResourceEnv = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "checkout",+ timestamp: "",+ durationNs: 0,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: { "deployment.environment": "prod" },+ };+ const spanWithSpanAttrEnv = {+ ...spanWithResourceEnv,+ spanId: "s2",+ resourceAttributes: {},+ spanAttributes: { "deployment.environment": "staging" },+ };+ const spanWithNoEnv = {+ ...spanWithResourceEnv,+ spanId: "s3",+ resourceAttributes: {},+ spanAttributes: {},+ };+ const result = await writeSpanHotCache({+ sourceId: "tempo-1",+ dbConfigId: "db-1",+ spans: [spanWithResourceEnv, spanWithSpanAttrEnv, spanWithNoEnv] as never,+ });+ expect(result).toBe(3);+ const sql = mockDataCollector.mock.calls[0][0].query as string;+ expect(sql).toContain("'prod'");+ expect(sql).toContain("'staging'");+ expect(mockDataCollector.mock.calls[0][2]).toBe("db-1");+ });});diff --git a/src/client/src/__tests__/lib/platform/traces/read.test.ts b/src/client/src/__tests__/lib/platform/traces/read.test.tsindex 20a9f0ce..25c39ef8 100644--- a/src/client/src/__tests__/lib/platform/traces/read.test.ts+++ b/src/client/src/__tests__/lib/platform/traces/read.test.ts@@ -30,9 +30,11 @@ jest.mock("@/helpers/server/platform", () => ({getFilterWhereCondition: () => "1 = 1",}));+const mockGetSummaryBucket = jest.fn().mockReturnValue("hour");+jest.mock("@/lib/platform/observability", () => ({getSignalSummary: (...a: unknown[]) => mockGetSignalSummary(...a),- getSummaryBucket: () => "hour",+ getSummaryBucket: (...a: unknown[]) => mockGetSummaryBucket(...a),}));jest.mock("@/lib/telemetry-source", () => ({@@ -42,8 +44,9 @@ jest.mock("@/lib/telemetry-source", () => ({}));jest.mock("@/helpers/server/trace", () => ({- buildHierarchy: (rows: unknown[]) =>- rows.length ? { SpanId: (rows[0] as { SpanId: string }).SpanId, children: [] } : null,+ buildHierarchy: jest.fn((rows: unknown[]) =>+ rows.length ? { SpanId: (rows[0] as { SpanId: string }).SpanId, children: [] } : null+ ),}));jest.mock("@/lib/platform/connectors/datasource/http/cache", () => ({@@ -69,8 +72,11 @@ jest.mock("@/lib/platform/telemetry/rollups", () => ({}));import {+ getTraceAttributeKeys,getTraceAverageDuration,getTraceExist,+ getTraceFilterConfig,+ getTraceGrouped,getTraceHierarchy,getTraceRecordByTraceId,getTraceRequestPerTime,@@ -80,7 +86,9 @@ import {listTraceRecords,} from "@/lib/platform/traces/read";import { AdapterError } from "@openplait/adapter-sdk";+import { UnsupportedCapabilityError } from "@/lib/platform/connectors/datasource/types";import { fetchLoopHitsByTraceIds } from "@/lib/platform/agent-loop/clickhouse";+import { buildHierarchy } from "@/helpers/server/trace";const builtin = {type: "clickhouse",@@ -908,4 +916,1596 @@ describe("dashboard graph facades", () => {const res = await getTraceExist();expect(res.data).toEqual([{ total_requests: 1 }]);});++ it("reports no traces on empty listSpans result", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ listSpans: jest.fn().mockResolvedValue({ rows: [] }),+ });++ const res = await getTraceExist();+ expect(res.data).toEqual([{ total_requests: 0 }]);+ });++ it("uses intervalFromTimeRange when the summary bucket has no mapped interval", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetSummaryBucket.mockReturnValueOnce("unmapped-bucket");+ const traceTimeSeries = jest.fn().mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue({ traceTimeSeries });++ const res = await getTraceSummary(params as any);++ expect(res.err).toBeNull();+ expect(traceTimeSeries).toHaveBeenCalledWith(+ expect.objectContaining({ interval: "1h" })+ );+ });++ it("adds an error-status filter for the exceptions signal", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const traceTimeSeries = jest.fn().mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue({ traceTimeSeries });++ await getTraceSummary(params as any, "exceptions");++ expect(traceTimeSeries).toHaveBeenCalledWith(+ expect.objectContaining({+ filters: expect.arrayContaining([+ expect.objectContaining({ target: "status", op: "in" }),+ ]),+ })+ );+ });++ it("falls back to planAndSpanTimeSeries when the adapter has no traceTimeSeries", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const spanTimeSeries = jest.fn().mockResolvedValue({+ rows: [{ label: "00:00", count: 2 }],+ meta: { freshness: "sampled", truncated: true },+ });+ mockGetAdapter.mockResolvedValue({ spanTimeSeries });++ const res = await getTraceSummary(params as any);++ expect(spanTimeSeries).toHaveBeenCalled();+ expect(res).toMatchObject({ total: 2, peak: 2, freshness: "sampled", truncated: true });+ });++ it("returns an error payload when getTraceSummary fails", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ traceTimeSeries: jest.fn().mockRejectedValue(new Error("tempo boom")),+ });++ const res = await getTraceSummary(params as any);+ expect(res).toMatchObject({ err: "tempo boom", buckets: [], total: 0, peak: 0 });+ });++ it("rethrows AdapterError from getTraceSummary", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ traceTimeSeries: jest+ .fn()+ .mockRejectedValue(new AdapterError("EXECUTION_FAILED", "tempo down")),+ });++ await expect(getTraceSummary(params as any)).rejects.toBeInstanceOf(AdapterError);+ });++ it("returns an error payload when getTraceTotalRequests fails", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ aggregateSpans: jest.fn().mockRejectedValue(new Error("count boom")),+ });++ const res = await getTraceTotalRequests(params as any);+ expect(res).toEqual({ err: "count boom", data: [] });+ });++ it("returns an error payload when getTraceRequestPerTime fails", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ spanTimeSeries: jest.fn().mockRejectedValue(new Error("series boom")),+ });++ const res = await getTraceRequestPerTime(params as any);+ expect(res).toEqual({ err: "series boom", data: [] });+ });++ it("returns an error payload when getTraceAverageDuration fails", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ aggregateSpans: jest.fn().mockRejectedValue(new Error("avg boom")),+ });++ const res = await getTraceAverageDuration(params as any);+ expect(res).toEqual({ err: "avg boom", data: [] });+ });++ it("falls back to a count-only aggregation row and defaults to 0 for total requests", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ aggregateSpans: jest+ .fn()+ .mockResolvedValueOnce({ rows: [{ count: 7 }] })+ .mockResolvedValueOnce({ rows: [{}] }),+ });++ const res = await getTraceTotalRequests(params as any);+ expect(res.data).toEqual([{ total_requests: 7, previous_total_requests: 0 }]);+ });++ it("defaults total requests to 0 when the aggregation returns no rows", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ aggregateSpans: jest.fn().mockResolvedValue({ rows: [] }),+ });++ const res = await getTraceTotalRequests(params as any);+ expect(res.data).toEqual([{ total_requests: 0, previous_total_requests: 0 }]);+ });++ it("falls back to count/label/bucket fields for the request-per-time series", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ spanTimeSeries: jest.fn().mockResolvedValue({+ rows: [{ count: 5, bucket: "2026-07-01T00:00:00.000Z" }],+ }),+ });++ const res = await getTraceRequestPerTime(params as any);+ expect(res.data).toEqual([{ total: 5, request_time: "2026-07-01T00:00:00.000Z" }]);+ });++ it("defaults request-per-time fields to 0/empty-string when nothing matches", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ spanTimeSeries: jest.fn().mockResolvedValue({ rows: [{}] }),+ });++ const res = await getTraceRequestPerTime(params as any);+ expect(res.data).toEqual([{ total: 0, request_time: "" }]);+ });++ it("defaults average duration fields to 0 when the aggregation returns no matching field", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ aggregateSpans: jest+ .fn()+ .mockResolvedValueOnce({ rows: [{}] })+ .mockResolvedValueOnce({ rows: [] }),+ });++ const res = await getTraceAverageDuration(params as any);+ expect(res.data).toEqual([{ average_duration: 0, previous_average_duration: 0 }]);+ });++ it("falls back to request_time/bucket and defaults counts to 0 in the summary series", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const traceTimeSeries = jest.fn().mockResolvedValue({+ rows: [{ request_time: "2026-07-01T00:00:00.000Z" }],+ });+ mockGetAdapter.mockResolvedValue({ traceTimeSeries });++ const res = await getTraceSummary(params as any);+ expect(res.buckets).toEqual([+ {+ label: "2026-07-01T00:00:00.000Z",+ count: 0,+ avgDuration: 0,+ cost: 0,+ tokens: 0,+ },+ ]);+ expect(res.freshness).toBe("sampled");+ expect(res.truncated).toBe(false);+ });++ it("keeps the base filters unchanged for the non-exceptions traces signal", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const traceTimeSeries = jest.fn().mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue({ traceTimeSeries });++ await getTraceSummary({ ...params, selectedConfig: { models: ["gpt-4o"] } } as any, "traces");++ const [query] = traceTimeSeries.mock.calls[0];+ expect(query.filters.some((f: { target: string }) => f.target === "status")).toBe(false);+ });+});++describe("listTraceRecords total/truncation branches", () => {+ it("estimates total as records+offset+1 when truncated without a backend count", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const listSpans = jest.fn().mockResolvedValue({+ rows: [+ {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ },+ ],+ });+ mockGetAdapter.mockResolvedValue({ listSpans });++ const res = await listTraceRecords({ ...params, limit: 1, offset: 0 } as never);++ expect(res).toMatchObject({ total: 2, freshness: "sampled" });+ });++ it("uses frame.meta.rowsScanned as a live total when no backend count is available", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const listSpans = jest.fn().mockResolvedValue({+ rows: [+ {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ },+ ],+ meta: { rowsScanned: 42 },+ });+ mockGetAdapter.mockResolvedValue({ listSpans });++ const res = await listTraceRecords(params as never);++ expect(res).toMatchObject({ total: 42, freshness: "live" });+ });+});++describe("treesForListedTraces", () => {+ it("keeps the original summary rows when the adapter cannot fetch full traces", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const summaryRow = {+ traceId: "t-summary",+ spanId: "t-summary",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ const listSpans = jest.fn().mockResolvedValue({ rows: [summaryRow] });+ mockGetAdapter.mockResolvedValue({ listSpans });++ const res = await listTraceRecords(params as never);+ expect(res.records?.[0]).toMatchObject({ TraceId: "t-summary" });+ });++ it("falls back to the summary rows when every per-trace fetch throws", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const summaryRow = {+ traceId: "t-summary",+ spanId: "t-summary",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ const listSpans = jest.fn().mockResolvedValue({ rows: [summaryRow] });+ const getTraceSpans = jest.fn().mockRejectedValue(new Error("tree fetch boom"));+ mockGetAdapter.mockResolvedValue({ listSpans, getTraceSpans });++ const res = await listTraceRecords(params as never);+ expect(getTraceSpans).toHaveBeenCalledWith("t-summary");+ expect(res.records?.[0]).toMatchObject({ TraceId: "t-summary" });+ });+});++describe("getTraceSpanRecord tree lookup", () => {+ it("attaches the loop note computed from a non-empty trace tree via getSpan", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const span = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ mockGetAdapter.mockResolvedValue({+ getSpan: jest.fn().mockResolvedValue(span),+ getTraceSpans: jest.fn().mockResolvedValue([span]),+ });++ const res = await getTraceSpanRecord("s1");+ expect(res.err).toBeNull();+ expect(res.record).toMatchObject({ SpanId: "s1" });+ });+});++describe("getTraceSpanRecord empty tree fallback", () => {+ it("attaches the loop note from just the span when getTraceSpans resolves empty", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const span = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ mockGetAdapter.mockResolvedValue({+ getSpan: jest.fn().mockResolvedValue(span),+ getTraceSpans: jest.fn().mockResolvedValue([]),+ });++ const res = await getTraceSpanRecord("s1");+ expect(res.err).toBeNull();+ expect(res.record).toMatchObject({ SpanId: "s1" });+ });+});++describe("getTraceFilterConfig span-name fallback", () => {+ it("re-derives span names from the sample when the native lookup returns none", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const span = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat-completion",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ mockGetAdapter.mockResolvedValue({+ capabilities: () => ({}),+ discoverServices: jest.fn().mockResolvedValue([{ serviceName: "api" }]),+ sampleTracesForGraph: jest.fn().mockResolvedValue([span]),+ distinctValues: jest.fn().mockResolvedValue([]),+ });++ const res = await getTraceFilterConfig(params as never);+ expect(res.data?.[0]).toMatchObject({ spanNames: ["chat-completion"] });+ });+});++describe("getTraceExist error branch", () => {+ it("returns an error payload when listSpans fails", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ listSpans: jest.fn().mockRejectedValue(new Error("exist boom")),+ });++ const res = await getTraceExist();+ expect(res).toEqual({ err: "exist boom", data: [{ total_requests: 0 }] });+ });+});++describe("getTraceTotalRequests count fallback", () => {+ it("falls back to a bare count field when total_requests is absent", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ aggregateSpans: jest+ .fn()+ .mockResolvedValueOnce({ rows: [{ count: 9 }] })+ .mockResolvedValueOnce({ rows: [{ count: 3 }] }),+ });++ const res = await getTraceTotalRequests(params as any);+ expect(res.data).toEqual([{ total_requests: 9, previous_total_requests: 3 }]);+ });++ it("defaults both totals to 0 when the aggregate has no rows at all", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ aggregateSpans: jest.fn().mockResolvedValue({ rows: [] }),+ });++ const res = await getTraceTotalRequests(params as any);+ expect(res.data).toEqual([{ total_requests: 0, previous_total_requests: 0 }]);+ });+});++describe("attachLoopForDetail additional branches", () => {+ it("returns the row unchanged when the ClickHouse loop-hit lookup throws", async () => {+ mockResolveDescriptor.mockResolvedValue(builtin);+ (fetchLoopHitsByTraceIds as jest.Mock).mockRejectedValue(new Error("ch lookup boom"));+ mockGetAdapter.mockResolvedValue({+ getTraceSpans: jest.fn().mockResolvedValue([+ {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "execute_tool",+ serviceName: "agent",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {+ "gen_ai.conversation.id": "chat-1",+ "gen_ai.tool.name": "search",+ "gen_ai.tool.args": '{"q":"once"}',+ },+ resourceAttributes: {},+ },+ ]),+ });++ const res = await getTraceSpanRecord("s1", { traceId: "t1" });+ expect(res.err).toBeNull();+ expect(res.record?.agentLoop).toBeUndefined();+ });++ it("returns the row unchanged when sibling-trace sampling throws", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const call = (traceId: string, spanId: string) => ({+ traceId,+ spanId,+ parentSpanId: "",+ name: "execute_tool",+ serviceName: "agent",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {+ "gen_ai.conversation.id": "chat-1",+ "gen_ai.tool.name": "search",+ "gen_ai.tool.args": '{"q":"orders"}',+ },+ resourceAttributes: {},+ });+ mockGetAdapter.mockResolvedValue({+ getTraceSpans: jest.fn().mockResolvedValue([call("t1", "s1")]),+ sampleTracesForGraph: jest.fn().mockRejectedValue(new Error("sample boom")),+ });++ const res = await getTraceSpanRecord("s1", { traceId: "t1" });+ expect(res.err).toBeNull();+ expect(res.record?.agentLoop).toBeUndefined();+ });+});++describe("listedSpansForIssueSample", () => {+ it("keeps a row as-is when its trace expands to no spans", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const summaryRow = {+ traceId: "t-empty-tree",+ spanId: "t-empty-tree",+ parentSpanId: "",+ name: "GET /health",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ const listSpans = jest.fn().mockResolvedValue({ rows: [summaryRow] });+ const getTraceSpans = jest.fn().mockResolvedValue([]);+ mockGetAdapter.mockResolvedValue({ listSpans, getTraceSpans });++ const res = await listTraceRecords({+ ...params,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);++ expect(getTraceSpans).toHaveBeenCalledWith("t-empty-tree");+ expect(res.err).toBeNull();+ expect((res as { records?: unknown[] }).records).toEqual([]);+ });+});++describe("listTraceRecords combined issue filters", () => {+ it("keeps only rows that are both looping and generation-health-flagged", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const loopSwapSpan = (index: number) => ({+ traceId: "t-loop-swap",+ spanId: `tool-${index}`,+ parentSpanId: "",+ name: "execute_tool",+ serviceName: "agent",+ timestamp: `2026-07-01T00:00:0${index}.000Z`,+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {+ "gen_ai.conversation.id": "chat-1",+ "gen_ai.tool.name": "search",+ "gen_ai.tool.args": '{"q":"orders"}',+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ resourceAttributes: {},+ });+ const loopOnlySpan = (index: number) => ({+ traceId: "t-loop-only",+ spanId: `tool-only-${index}`,+ parentSpanId: "",+ name: "execute_tool",+ serviceName: "agent",+ timestamp: `2026-07-01T00:00:0${index}.000Z`,+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {+ "gen_ai.conversation.id": "chat-2",+ "gen_ai.tool.name": "search",+ "gen_ai.tool.args": '{"q":"invoices"}',+ },+ resourceAttributes: {},+ });+ const sampleTracesForGraph = jest.fn().mockResolvedValue([+ loopSwapSpan(0),+ loopSwapSpan(1),+ loopSwapSpan(2),+ loopOnlySpan(0),+ loopOnlySpan(1),+ loopOnlySpan(2),+ ]);+ mockGetAdapter.mockResolvedValue({ sampleTracesForGraph, listSpans: jest.fn() });++ const res = await listTraceRecords({+ ...params,+ selectedConfig: { generationHealth: ["swapped"], agentLoop: true },+ } as never);++ expect(res.err).toBeNull();+ const records = (res as { records?: Array<Record<string, unknown>> }).records;+ expect(records?.map((r) => r.TraceId)).toEqual(["t-loop-swap"]);+ });+});++describe("getTraceFilterConfig", () => {+ it("combines discovered services with an L1 sample for the remaining filters", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const span = (overrides: Record<string, unknown>) => ({+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ ...overrides,+ });+ mockGetAdapter.mockResolvedValue({+ capabilities: () => ({}),+ discoverServices: jest.fn().mockResolvedValue([+ { serviceName: "api" },+ { serviceName: "" },+ ]),+ sampleTracesForGraph: jest.fn().mockResolvedValue([+ span({+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.system": "openai",+ "gen_ai.operation.type": "chat",+ },+ }),+ ]),+ distinctValues: jest.fn().mockResolvedValue(["chat", "embeddings"]),+ sampleCacheKey: "tempo-filter-config",+ });++ const res = await getTraceFilterConfig(params as never);++ expect(res.err).toBeNull();+ expect(res.data?.[0]).toMatchObject({+ models: ["gpt-4o"],+ providers: ["openai"],+ spanNames: ["chat", "embeddings"],+ applicationNames: ["api"],+ traceTypes: ["chat"],+ });+ });++ it("falls back to sampled span names/applications when native lookups fail or are empty", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const span = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat-completion",+ serviceName: "worker",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ mockGetAdapter.mockResolvedValue({+ capabilities: () => ({}),+ discoverServices: jest.fn().mockRejectedValue(new Error("no discovery")),+ sampleTracesForGraph: jest.fn().mockResolvedValue([span]),+ distinctValues: jest.fn().mockRejectedValue(new Error("unsupported")),+ });++ const res = await getTraceFilterConfig(params as never);++ expect(res.err).toBeNull();+ expect(res.data?.[0]).toMatchObject({+ spanNames: ["chat-completion"],+ applicationNames: ["worker"],+ });+ });++ it("returns the empty filter row when getTraceFilterConfig fails", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ capabilities: () => ({}),+ discoverServices: jest.fn().mockRejectedValue(new Error("no discovery")),+ sampleTracesForGraph: jest.fn().mockRejectedValue(new Error("sample boom")),+ });++ const res = await getTraceFilterConfig(params as never);+ expect(res.err).toBe("sample boom");+ expect(res.data?.[0]).toMatchObject({ models: [], providers: [] });+ });+});++describe("getTraceAttributeKeys", () => {+ it("returns discovered span attribute keys", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ attributeKeys: jest.fn().mockResolvedValue(["gen_ai.request.model"]),+ });++ const res = await getTraceAttributeKeys(params as never);+ expect(res).toEqual({+ err: null,+ spanAttributeKeys: ["gen_ai.request.model"],+ resourceAttributeKeys: [],+ });+ });++ it("returns an empty payload when attribute discovery fails", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ attributeKeys: jest.fn().mockRejectedValue(new Error("boom")),+ });++ const res = await getTraceAttributeKeys(params as never);+ expect(res).toEqual({ err: null, spanAttributeKeys: [], resourceAttributeKeys: [] });+ });+});++describe("getTraceGrouped", () => {+ it("maps a friendly groupBy key to its attribute field", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const aggregateSpans = jest.fn().mockResolvedValue({+ rows: [{ group_value: "gpt-4o", count: 3, total_cost: 1.5, total_tokens: 400, avg_duration_seconds: 0.4 }],+ });+ mockGetAdapter.mockResolvedValue({ aggregateSpans });++ const res = await getTraceGrouped(params as never, "model");++ expect(aggregateSpans).toHaveBeenCalledWith(+ expect.objectContaining({ groupBy: ["gen_ai.request.model"] })+ );+ expect(res.data).toEqual([+ {+ group_value: "gpt-4o",+ count: 3,+ total_cost: 1.5,+ total_tokens: 400,+ avg_duration_seconds: 0.4,+ },+ ]);+ });++ it("passes through a scoped groupBy key that has no friendly mapping", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const aggregateSpans = jest.fn().mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue({ aggregateSpans });++ await getTraceGrouped(params as never, "custom:attribute.key");++ expect(aggregateSpans).toHaveBeenCalledWith(+ expect.objectContaining({ groupBy: ["attribute.key"] })+ );+ });++ it("passes through a plain groupBy key without a colon", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const aggregateSpans = jest.fn().mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue({ aggregateSpans });++ await getTraceGrouped(params as never, "custom_field");++ expect(aggregateSpans).toHaveBeenCalledWith(+ expect.objectContaining({ groupBy: ["custom_field"] })+ );+ });++ it("returns an error payload when getTraceGrouped fails", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ aggregateSpans: jest.fn().mockRejectedValue(new Error("group boom")),+ });++ const res = await getTraceGrouped(params as never, "model");+ expect(res).toEqual({ err: "group boom", data: [] });+ });++ it("falls back to the raw grouped field name when group_value is absent", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const aggregateSpans = jest.fn().mockResolvedValue({+ rows: [{ "gen_ai.request.model": "claude-3", count: 1 }],+ });+ mockGetAdapter.mockResolvedValue({ aggregateSpans });++ const res = await getTraceGrouped(params as never, "model");+ expect(res.data[0]).toMatchObject({ group_value: "claude-3" });+ });++ it("falls back to g0 and defaults numeric aggregates to 0 when nothing else matches", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const aggregateSpans = jest.fn().mockResolvedValue({+ rows: [{ g0: "gpt-4o" }],+ });+ mockGetAdapter.mockResolvedValue({ aggregateSpans });++ const res = await getTraceGrouped(params as never, "model");+ expect(res.data[0]).toEqual({+ group_value: "gpt-4o",+ count: 0,+ total_cost: 0,+ total_tokens: 0,+ avg_duration_seconds: 0,+ });+ });++ it("defaults the group value to an empty string when no candidate field is present", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const aggregateSpans = jest.fn().mockResolvedValue({ rows: [{}] });+ mockGetAdapter.mockResolvedValue({ aggregateSpans });++ const res = await getTraceGrouped(params as never, "model");+ expect(res.data[0].group_value).toBe("");+ });+});++describe("listTraceRecords issue-sample fallback (no sampleTracesForGraph)", () => {+ it("falls back to listSpans + per-trace expansion when the adapter cannot sample directly", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const swappedRow = {+ traceId: "t-swap",+ spanId: "root-swap",+ parentSpanId: "",+ name: "openai.chat.completions",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ resourceAttributes: {},+ };+ const listSpans = jest.fn().mockResolvedValue({ rows: [swappedRow] });+ const getTraceSpans = jest.fn().mockResolvedValue([swappedRow]);+ mockGetAdapter.mockResolvedValue({ listSpans, getTraceSpans });++ const res = await listTraceRecords({+ ...params,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);++ expect(listSpans).toHaveBeenCalled();+ expect(getTraceSpans).not.toHaveBeenCalled();+ expect(res).toMatchObject({ err: null, freshness: "sampled" });+ });++ it("expands per-trace when the initial rows do not already match the issue filter", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const summaryRow = {+ traceId: "t-summary",+ spanId: "t-summary",+ parentSpanId: "",+ name: "root",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ const swappedSpan = {+ ...summaryRow,+ spanId: "child",+ name: "openai.chat.completions",+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ };+ const listSpans = jest.fn().mockResolvedValue({ rows: [summaryRow] });+ const getTraceSpans = jest.fn().mockResolvedValue([summaryRow, swappedSpan]);+ mockGetAdapter.mockResolvedValue({ listSpans, getTraceSpans });++ const res = await listTraceRecords({+ ...params,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);++ expect(getTraceSpans).toHaveBeenCalledWith("t-summary");+ expect(res).toMatchObject({ err: null });+ const records = (res as { records?: Array<Record<string, unknown>> }).records;+ expect(records?.some((row) => row.SpanId === "child")).toBe(true);+ });++ it("falls back to the listSpans row when a trace expands to no spans", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const swappedRow = {+ traceId: "t-empty",+ spanId: "root",+ parentSpanId: "",+ name: "openai.chat.completions",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ resourceAttributes: {},+ };+ const other = { ...swappedRow, traceId: "t-other-blank", spanAttributes: {} };+ const listSpans = jest.fn().mockResolvedValue({ rows: [swappedRow, other] });+ const getTraceSpans = jest.fn().mockResolvedValue([]);+ mockGetAdapter.mockResolvedValue({ listSpans, getTraceSpans });++ const res = await listTraceRecords({+ ...params,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);++ expect(res.err).toBeNull();+ });++ it("continues sampling via listSpans+getTraceSpans when sampleTracesForGraph is unsupported", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const swappedRow = {+ traceId: "t-swap",+ spanId: "root",+ parentSpanId: "",+ name: "openai.chat.completions",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ resourceAttributes: {},+ };+ mockGetAdapter.mockResolvedValue({+ sampleTracesForGraph: jest+ .fn()+ .mockRejectedValue(new UnsupportedCapabilityError("sampleTracesForGraph", "tempo")),+ listSpans: jest.fn().mockResolvedValue({ rows: [swappedRow] }),+ });++ const res = await listTraceRecords({+ ...params,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);++ expect(res.err).toBeNull();+ });++ it("reports an error when sampleTracesForGraph fails with a non-capability error", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ sampleTracesForGraph: jest.fn().mockRejectedValue(new Error("graph boom")),+ listSpans: jest.fn(),+ });++ const res = await listTraceRecords({+ ...params,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);++ expect(res).toEqual({ err: "graph boom" });+ });+});++describe("listTraceRecords ClickHouse cross-trace loop hits", () => {+ it("attaches loop hits by TraceId when the built-in source has matches", async () => {+ mockResolveDescriptor.mockResolvedValue(builtin);+ (fetchLoopHitsByTraceIds as jest.Mock).mockResolvedValue(+ new Map([["t1", { toolName: "search", count: 2 }]])+ );+ mockGetAdapter.mockResolvedValue({+ listSpans: jest.fn().mockResolvedValue({+ rows: [+ {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ },+ ],+ }),+ });++ const res = await listTraceRecords(params as never);+ expect(res.records?.[0]).toMatchObject({+ TraceId: "t1",+ agentLoop: { toolName: "search", count: 2 },+ });+ });++ it("returns unmodified records when the loop-hit lookup throws", async () => {+ mockResolveDescriptor.mockResolvedValue(builtin);+ (fetchLoopHitsByTraceIds as jest.Mock).mockRejectedValue(new Error("ch down"));+ mockGetAdapter.mockResolvedValue({+ listSpans: jest.fn().mockResolvedValue({+ rows: [+ {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ },+ ],+ }),+ });++ const res = await listTraceRecords(params as never);+ expect(res.records?.[0]?.agentLoop).toBeUndefined();+ });++ it("returns records unchanged when there are no TraceIds to look up", async () => {+ mockResolveDescriptor.mockResolvedValue(builtin);+ mockGetAdapter.mockResolvedValue({+ listSpans: jest.fn().mockResolvedValue({ rows: [] }),+ });++ const res = await listTraceRecords(params as never);+ expect(res.records).toEqual([]);+ expect(fetchLoopHitsByTraceIds).not.toHaveBeenCalled();+ });+});++describe("getTraceSpanRecord additional branches", () => {+ it("reports span not found when getSpan misses without a traceId hint", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({ getSpan: jest.fn().mockResolvedValue(null) });++ const res = await getTraceSpanRecord("missing-span");+ expect(res).toEqual({+ err: "Span not found in the selected telemetry source",+ record: undefined,+ });+ });++ it("still attaches a loop note when the full-trace fetch throws", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const span = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "execute_tool",+ serviceName: "agent",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {+ "gen_ai.conversation.id": "chat-1",+ "gen_ai.tool.name": "search",+ "gen_ai.tool.args": "{}",+ },+ resourceAttributes: {},+ };+ mockGetAdapter.mockResolvedValue({+ getSpan: jest.fn().mockResolvedValue(span),+ getTraceSpans: jest.fn().mockRejectedValue(new Error("tree boom")),+ });++ const res = await getTraceSpanRecord("s1");+ expect(res.err).toBeNull();+ expect(res.record).toMatchObject({ SpanId: "s1" });+ });++ it("propagates a source-level error and reports the failure", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ getSpan: jest.fn().mockRejectedValue(new Error("adapter down")),+ });++ const res = await getTraceSpanRecord("s1");+ expect(res).toEqual({ err: "adapter down", record: undefined });+ });+});++describe("getTraceRecordByTraceId error branch", () => {+ it("returns an error payload when getTraceSpans throws", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ getTraceSpans: jest.fn().mockRejectedValue(new Error("fetch boom")),+ });++ const res = await getTraceRecordByTraceId("t1");+ expect(res).toEqual({ err: "fetch boom", record: undefined });+ });+});++describe("getTraceHierarchy additional branches", () => {+ it("expands cross-trace session spans when the adapter supports it", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const rootSpan = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "root",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: { "coding_agent.session.id": "sess-1" },+ };+ const sessionSpan = { ...rootSpan, traceId: "t2", spanId: "s2" };+ mockGetAdapter.mockResolvedValue({+ capabilities: () => ({ crossTraceSession: true }),+ getSpan: jest.fn().mockResolvedValue(rootSpan),+ getTraceSpans: jest.fn().mockResolvedValue([rootSpan]),+ getSpansBySession: jest.fn().mockResolvedValue([sessionSpan]),+ });++ const res = await getTraceHierarchy("s1");+ expect(res.err).toBeNull();+ });++ it("still builds a hierarchy when session expansion throws", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const rootSpan = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "root",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: { "coding_agent.session.id": "sess-1" },+ };+ mockGetAdapter.mockResolvedValue({+ capabilities: () => ({ crossTraceSession: true }),+ getSpan: jest.fn().mockResolvedValue(rootSpan),+ getTraceSpans: jest.fn().mockResolvedValue([rootSpan]),+ getSpansBySession: jest.fn().mockRejectedValue(new Error("session boom")),+ });++ const res = await getTraceHierarchy("s1");+ expect(res.err).toBeNull();+ expect(res.record).toMatchObject({ SpanId: "s1" });+ });++ it("reports a missing span when no traceId hint is given and getSpan misses", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({ getSpan: jest.fn().mockResolvedValue(null) });++ const res = await getTraceHierarchy("missing");+ expect(res).toEqual({ err: "Span not found", record: {} });+ });++ it("reports failure to fetch trace spans when getTraceSpans returns empty", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const span = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "root",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ mockGetAdapter.mockResolvedValue({+ capabilities: () => ({ crossTraceSession: false }),+ getSpan: jest.fn().mockResolvedValue(span),+ getTraceSpans: jest.fn().mockResolvedValue([]),+ });++ const res = await getTraceHierarchy("s1");+ expect(res).toEqual({ err: "Failed to fetch trace spans", record: {} });+ });++ it("propagates a source-level error from getTraceHierarchy", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ getSpan: jest.fn().mockRejectedValue(new Error("hierarchy boom")),+ });++ const res = await getTraceHierarchy("s1");+ expect(res).toEqual({ err: "hierarchy boom", record: {} });+ });++ it("accepts opts without a traceId hint (e.g. only an environment)", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const span = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ mockGetAdapter.mockResolvedValue({+ capabilities: () => ({ crossTraceSession: false }),+ getSpan: jest.fn().mockResolvedValue(span),+ getTraceSpans: jest.fn().mockResolvedValue([span]),+ });++ const res = await getTraceHierarchy("s1", { environment: "production" });+ expect(res.err).toBeNull();+ });++ it("reports a hierarchy build failure when the tree builder returns nothing", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ (buildHierarchy as jest.Mock).mockReturnValueOnce(null);+ const span = {+ traceId: "t1",+ spanId: "s1",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ mockGetAdapter.mockResolvedValue({+ capabilities: () => ({ crossTraceSession: false }),+ getSpan: jest.fn().mockResolvedValue(span),+ getTraceSpans: jest.fn().mockResolvedValue([span]),+ });++ const res = await getTraceHierarchy("s1");+ expect(res).toEqual({ err: "Error building hierarchy", record: {} });+ });+});++describe("externalTraceQuery environment filter edge cases", () => {+ it("keeps a multi-value deployment.environment filter instead of dropping it as the 'default' sentinel", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const listSpans = jest.fn().mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue({ listSpans });++ await listTraceRecords({+ ...params,+ selectedConfig: { environments: ["production", "staging"] },+ } as never);++ const [query] = listSpans.mock.calls[0];+ expect(query.filters).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ key: "deployment.environment", value: ["production", "staging"] }),+ ])+ );+ });++ it("keeps a single non-default deployment.environment filter", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const listSpans = jest.fn().mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue({ listSpans });++ await listTraceRecords({+ ...params,+ selectedConfig: { environments: ["production"] },+ } as never);++ const [query] = listSpans.mock.calls[0];+ expect(query.filters).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ key: "deployment.environment", value: ["production"] }),+ ])+ );+ });+});++describe("findSpanInTrace additional branches", () => {+ it("falls back to the raw (unnormalized) span id when it cannot be OTLP-normalized", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const span = {+ traceId: "t1",+ spanId: "",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ mockGetAdapter.mockResolvedValue({+ getTraceSpans: jest.fn().mockResolvedValue([span]),+ capabilities: () => ({}),+ });++ const res = await getTraceSpanRecord("", { traceId: "t1" });+ expect(res.err).toBeNull();+ });++ it("returns null when the trace has no root span to fall back to", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ getTraceSpans: jest.fn().mockResolvedValue([]),+ });++ const res = await getTraceSpanRecord("t-same-id", { traceId: "t-same-id" });+ expect(res).toEqual({+ err: "Span not found in the selected trace and telemetry source",+ record: undefined,+ });+ });+});++describe("getTraceSpanRecord opts without traceId", () => {+ it("reports not found using only an environment hint (no traceId)", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({ getSpan: jest.fn().mockResolvedValue(null) });++ const res = await getTraceSpanRecord("s1", { environment: "production" });+ expect(res).toEqual({+ err: "Span not found in the selected telemetry source",+ record: undefined,+ });+ });++ it("reports the underlying error using only an environment hint (no traceId)", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ getSpan: jest.fn().mockRejectedValue(new Error("lookup boom")),+ });++ const res = await getTraceSpanRecord("s1", { environment: "production" });+ expect(res).toEqual({ err: "lookup boom", record: undefined });+ });+});++describe("getTraceRecordByTraceId empty trace", () => {+ it("returns an undefined record when the trace has no spans", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ getTraceSpans: jest.fn().mockResolvedValue([]),+ });++ const res = await getTraceRecordByTraceId("t-empty");+ expect(res).toEqual({ err: null, record: undefined });+ });+});++describe("treesForListedTraces mixed results", () => {+ it("still returns every listed (summary) row when only some trace ids resolve full trees", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ // Tempo Explore-style summary rows: SpanId reuses TraceId, no attributes,+ // which is what triggers the `isTraceSummaryRow` -> treesForListedTraces path.+ const summaryRow = (traceId: string) => ({+ traceId,+ spanId: traceId,+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ });+ const fullSpan = { ...summaryRow("t-full"), spanId: "child", parentSpanId: "root" };+ const listSpans = jest.fn().mockResolvedValue({+ rows: [summaryRow("t-full"), summaryRow("t-empty")],+ });+ const getTraceSpans = jest.fn().mockImplementation((traceId: string) =>+ Promise.resolve(traceId === "t-full" ? [fullSpan] : [])+ );+ mockGetAdapter.mockResolvedValue({ listSpans, getTraceSpans });++ const res = await listTraceRecords(params as never);+ // treesForListedTraces only feeds loop-hit detection (withLoopHits); the+ // emitted records still mirror the originally listed summary rows.+ expect(res.err).toBeNull();+ expect(getTraceSpans).toHaveBeenCalledWith("t-full");+ expect(getTraceSpans).toHaveBeenCalledWith("t-empty");+ expect(res.records?.map((r) => r.TraceId)).toEqual(["t-full", "t-empty"]);+ });+});++describe("listedSpansForIssueSample additional branches", () => {+ it("returns an empty array immediately when there are no listed spans", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ listSpans: jest.fn().mockResolvedValue({ rows: [] }),+ });++ const res = await listTraceRecords({+ ...params,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);+ expect(res).toMatchObject({ err: null, records: [] });+ });++ it("returns the listed rows unchanged when the adapter cannot expand full traces", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const summaryRow = {+ traceId: "t-no-expand",+ spanId: "t-no-expand",+ parentSpanId: "",+ name: "GET /health",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ mockGetAdapter.mockResolvedValue({+ listSpans: jest.fn().mockResolvedValue({ rows: [summaryRow] }),+ });++ const res = await listTraceRecords({+ ...params,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);+ expect(res.err).toBeNull();+ });++ it("deduplicates repeated trace ids in the listed rows", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const summaryRow = {+ traceId: "t-dup",+ spanId: "t-dup",+ parentSpanId: "",+ name: "GET /health",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ const listSpans = jest.fn().mockResolvedValue({ rows: [summaryRow, { ...summaryRow }] });+ const getTraceSpans = jest.fn().mockResolvedValue([]);+ mockGetAdapter.mockResolvedValue({ listSpans, getTraceSpans });++ await listTraceRecords({+ ...params,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);+ expect(getTraceSpans).toHaveBeenCalledTimes(1);+ });+});++describe("attachClickHouseLoopHits additional branches", () => {+ it("skips a record whose TraceId does not have a matching loop hit", async () => {+ mockResolveDescriptor.mockResolvedValue(builtin);+ (fetchLoopHitsByTraceIds as jest.Mock).mockResolvedValue(+ new Map([["t-has-hit", { toolName: "search", count: 2 }]])+ );+ const rowFor = (traceId: string) => ({+ traceId,+ spanId: traceId,+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ });+ mockGetAdapter.mockResolvedValue({+ listSpans: jest.fn().mockResolvedValue({ rows: [rowFor("t-has-hit"), rowFor("t-no-hit")] }),+ });++ const res = await listTraceRecords(params as never);+ const byTrace = new Map((res.records || []).map((r: any) => [r.TraceId, r]));+ expect((byTrace.get("t-has-hit") as any)?.agentLoop).toBeDefined();+ expect((byTrace.get("t-no-hit") as any)?.agentLoop).toBeUndefined();+ });++ it("uses an empty selectedConfig default when params omit it", async () => {+ mockResolveDescriptor.mockResolvedValue(builtin);+ (fetchLoopHitsByTraceIds as jest.Mock).mockResolvedValue(new Map());+ mockGetAdapter.mockResolvedValue({+ listSpans: jest.fn().mockResolvedValue({+ rows: [+ {+ traceId: "t1",+ spanId: "t1",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ },+ ],+ }),+ });++ const { selectedConfig: _drop, ...rest } = params;+ const res = await listTraceRecords(rest as never);+ expect(res.err).toBeNull();+ });+});++describe("asErrorMessage additional branches", () => {+ // `rethrowIfSourceFailure` unconditionally rethrows AdapterError before+ // `asErrorMessage` ever runs, so its `err instanceof AdapterError` branch+ // (reading `err.details?.body`) is unreachable from every call site in+ // this file today; listSpans failing with an AdapterError propagates as a+ // rejection instead of a soft `{ err }` payload.+ it("rethrows an AdapterError instead of returning a soft error payload", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ listSpans: jest+ .fn()+ .mockRejectedValue(new AdapterError("EXECUTION_FAILED", "adapter died")),+ countTraces: undefined,+ });++ await expect(listTraceRecords(params as never)).rejects.toThrow("adapter died");+ });++ it("stringifies a plain string throw", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ listSpans: jest.fn().mockRejectedValue("plain string failure"),+ });++ const res = await listTraceRecords(params as never);+ expect(res).toEqual({ err: "plain string failure" });+ });++ it("falls back to the generic widget-run-failed message for a non-Error, non-string throw", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ mockGetAdapter.mockResolvedValue({+ listSpans: jest.fn().mockRejectedValue({ code: 42 }),+ });++ const res = await listTraceRecords(params as never);+ expect(res.err).toBeTruthy();+ });+});++describe("listTraceRecords countTraces failure branch", () => {+ it("falls back to the sampled total when countTraces rejects", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const row = {+ traceId: "t1",+ spanId: "t1",+ parentSpanId: "",+ name: "chat",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {},+ resourceAttributes: {},+ };+ mockGetAdapter.mockResolvedValue({+ listSpans: jest.fn().mockResolvedValue({ rows: [row] }),+ countTraces: jest.fn().mockRejectedValue(new Error("count boom")),+ });++ const res = await listTraceRecords(params as never);+ expect(res.err).toBeNull();+ expect(res.total).toBeGreaterThan(0);+ });+});++describe("listSampledIssueRecords param defaults", () => {+ it("defaults the page size to 25 when params omit limit", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const sampleTracesForGraph = jest.fn().mockResolvedValue([]);+ mockGetAdapter.mockResolvedValue({ sampleTracesForGraph, listSpans: jest.fn() });++ const { limit: _drop, ...rest } = params;+ const res = await listTraceRecords({+ ...rest,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);++ expect(res).toMatchObject({ err: null, records: [] });+ });++ it("treats a missing frame.rows as an empty sample in the listSpans fallback path", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const listSpans = jest.fn().mockResolvedValue({});+ mockGetAdapter.mockResolvedValue({ listSpans });++ const res = await listTraceRecords({+ ...params,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);+ expect(res).toMatchObject({ err: null, records: [] });+ });+});++describe("sampledIssueListResult page-boundary total", () => {+ it("adds one extra to the total when the page is exactly full and more may exist", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const swappedRow = (i: number) => ({+ traceId: `t-swap-${i}`,+ spanId: `t-swap-${i}`,+ parentSpanId: "",+ name: "openai.chat.completions",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ resourceAttributes: {},+ });+ // GENERATION_HEALTH_SAMPLE_TRACES (200) matching rows, all "swapped" —+ // budget never needs to grow, and truncated is true (unique >= budget).+ const rows = Array.from({ length: 200 }, (_, i) => swappedRow(i));+ const sampleTracesForGraph = jest.fn().mockResolvedValue(rows);+ mockGetAdapter.mockResolvedValue({ sampleTracesForGraph, listSpans: jest.fn() });++ const res = await listTraceRecords({+ ...params,+ limit: 200,+ offset: 0,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);++ expect(res.total).toBe(201);+ });});diff --git a/src/client/src/__tests__/lib/platform/vault/vault.test.ts b/src/client/src/__tests__/lib/platform/vault/vault.test.tsindex 98d6c32a..7019cd65 100644--- a/src/client/src/__tests__/lib/platform/vault/vault.test.ts+++ b/src/client/src/__tests__/lib/platform/vault/vault.test.ts@@ -61,6 +61,14 @@ jest.mock('@/utils/crypto', () => ({jest.mock('@/lib/platform/alerts/signals', () => ({emitManagementAlertSignalSafe: jest.fn(),}));+jest.mock('@/lib/prisma', () => ({+ __esModule: true,+ default: {+ telemetrySource: {+ findFirst: jest.fn(),+ },+ },+}));import { getSecretByName, checkNameValidity, deleteSecret, getSecrets, getSecretById, upsertSecret, getSecretsFromDatabaseId } from '@/lib/platform/vault/index';import { dataCollector } from '@/lib/platform/common';@@ -152,6 +160,20 @@ describe('getSecrets', () => {expect(query).toContain("v.key = 'a\\\\b\\'c'");});+ it('builds the owner condition with an empty string when the current user has no email', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'u1' });+ await getSecrets({});+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).toContain("v.created_by = ''");+ });++ it('uses the createdBy filter (not the owner condition) when there is no authenticated user', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue(null);+ await getSecrets({ createdBy: '[email protected]' });+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).toContain("v.created_by = '[email protected]'");+ });+it('adds hasAny tags filter when tags are provided (covers lines 133-135)', async () => {await getSecrets({ tags: ['tagA', 'tagB'] });const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];@@ -166,6 +188,14 @@ describe('getSecrets', () => {expect(query).not.toContain('EXCEPT value');});+ it('leaves non-string values untouched when decrypting selected secrets', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({+ data: [{ id: 'v1', key: 'k', value: null }],+ });+ const result = await getSecrets({}, { selectValue: true });+ expect((result.data as any[])[0].value).toBeNull();+ });+it('excludes value in SELECT by default', async () => {await getSecrets({});const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];@@ -220,6 +250,32 @@ describe('getSecretById', () => {(getCurrentUser as jest.Mock).mockResolvedValueOnce(null);await expect(getSecretById('v1')).rejects.toThrow('Unauthorized');});++ it('scopes the lookup to a project via secretRef when projectId is provided, without any owner condition', async () => {+ const prisma = require('@/lib/prisma').default;+ prisma.telemetrySource.findFirst.mockResolvedValue({ id: 'source-1' });+ (dataCollector as jest.Mock).mockResolvedValue({ data: [{ id: 'v1', key: 'k' }] });++ const result = await getSecretById('v1', undefined, true, { projectId: 'proj-1' });++ expect(prisma.telemetrySource.findFirst).toHaveBeenCalledWith(+ expect.objectContaining({ where: { secretRef: 'v1', projectId: 'proj-1' } })+ );+ expect(getCurrentUser).not.toHaveBeenCalled();+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).not.toContain('created_by');+ expect(result.data).toEqual([{ id: 'v1', key: 'k' }]);+ });++ it('returns an empty list when no telemetry source references the secret under the given project', async () => {+ const prisma = require('@/lib/prisma').default;+ prisma.telemetrySource.findFirst.mockResolvedValue(null);++ const result = await getSecretById('v1', undefined, true, { projectId: 'proj-missing' });++ expect(result).toEqual({ data: [] });+ expect(dataCollector).not.toHaveBeenCalled();+ });});describe('upsertSecret', () => {@@ -305,6 +361,46 @@ describe('upsertSecret', () => {const [insertParams] = (dataCollector as jest.Mock).mock.calls[1];expect(insertParams.values[0].created_by).toBe('[email protected]');});++ it('falls back to an empty string owner email and key when the user has no email and no key is given', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'u1' });+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [], err: null })+ .mockResolvedValueOnce({ err: null });+ await upsertSecret({ value: 'v' });+ // checkNameValidity's underlying query only has a key='' condition —+ // both the key and createdBy fallbacks resolved to falsy empty strings.+ const [nameCheckParams] = (dataCollector as jest.Mock).mock.calls[0];+ expect(nameCheckParams.query).toContain("key=''");+ expect(nameCheckParams.query).not.toContain('created_by');+ const [insertParams] = (dataCollector as jest.Mock).mock.calls[1];+ expect(insertParams.values[0].created_by).toBeUndefined();+ expect(insertParams.values[0].key).toBeUndefined();+ });++ it('stores an empty string value when no value is provided', async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [], err: null })+ .mockResolvedValueOnce({ err: null });+ await upsertSecret({ key: 'k' });+ const [insertParams] = (dataCollector as jest.Mock).mock.calls[1];+ expect(insertParams.values[0].value).toBe('');+ });++ it('falls back to an empty string key in the "created" alert message when no key is given', async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [], err: null })+ .mockResolvedValueOnce({ err: null });+ await upsertSecret({ value: 'v' });+ const { emitManagementAlertSignalSafe } = require('@/lib/platform/alerts/signals');+ expect(emitManagementAlertSignalSafe).toHaveBeenCalledWith(+ expect.objectContaining({+ event: 'vault_secret_created',+ message: 'Vault key was created.',+ fields: expect.objectContaining({ key: '' }),+ })+ );+ });});describe('UPDATE path (id provided)', () => {@@ -374,6 +470,34 @@ describe('upsertSecret', () => {(dataCollector as jest.Mock).mockResolvedValue({ err: null, data: null });await expect(upsertSecret({ id: 'sid', key: 'k' })).rejects.toThrow('Secret not saved');});++ it('falls back to empty/null defaults in the "updated" alert when the sanitized secret has no id or key', async () => {+ (dataCollector as jest.Mock).mockResolvedValue({ err: null, data: { query_id: 'qid-1' } });+ const Sanitizer = require('@/utils/sanitizer').default;+ // Force sanitizeObject to drop `id` for this call only, simulating a+ // defensive edge case where the sanitized secret ends up without an id.+ (Sanitizer.sanitizeObject as jest.Mock).mockImplementationOnce(+ (o: Record<string, unknown>) => {+ const { id, key, ...rest } = o;+ return rest;+ }+ );++ await upsertSecret({ id: 'sid', value: 'v' });++ const { emitManagementAlertSignalSafe } = require('@/lib/platform/alerts/signals');+ expect(emitManagementAlertSignalSafe).toHaveBeenCalledWith(+ expect.objectContaining({+ event: 'vault_secret_updated',+ message: 'Vault key was updated.',+ sourceId: null,+ fields: expect.objectContaining({ secret_id: '', key: '' }),+ })+ );+ // The UPDATE query's WHERE id clause also fell back to an empty string.+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).toContain("WHERE id = ''");+ });});});@@ -446,4 +570,30 @@ describe('getSecretsFromDatabaseId', () => {const [,, dbConfigId] = (dataCollector as jest.Mock).mock.calls[0];expect(dbConfigId).toBe('db-99');});++ it('prefers an explicit filters.databaseConfigId over the one derived from the API key', async () => {+ (getAPIKeyInfo as jest.Mock).mockResolvedValue([null, { databaseConfigId: 'db-from-key' }]);+ (dataCollector as jest.Mock).mockResolvedValue({ data: [{ key: 'K', value: 'V' }], err: null });+ (normalizeSecretDataForSDK as jest.Mock).mockReturnValue({ K: 'V' });++ await getSecretsFromDatabaseId({ apiKey: 'valid-key', databaseConfigId: 'db-explicit' });++ const [,, dbConfigId] = (dataCollector as jest.Mock).mock.calls[0];+ expect(dbConfigId).toBe('db-explicit');+ });++ it('scopes the secrets lookup to the API key owner via createdByUser.email', async () => {+ (getAPIKeyInfo as jest.Mock).mockResolvedValue([+ null,+ { databaseConfigId: 'db-1', createdByUser: { email: '[email protected]' } },+ ]);+ (getCurrentUser as jest.Mock).mockResolvedValue(null);+ (dataCollector as jest.Mock).mockResolvedValue({ data: [{ key: 'K', value: 'V' }], err: null });+ (normalizeSecretDataForSDK as jest.Mock).mockReturnValue({ K: 'V' });++ await getSecretsFromDatabaseId({ apiKey: 'valid-key' });++ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];+ expect(query).toContain("v.created_by = '[email protected]'");+ });});diff --git a/src/client/src/__tests__/lib/platform/vector/external.test.ts b/src/client/src/__tests__/lib/platform/vector/external.test.tsnew file mode 100644index 00000000..43d6748d--- /dev/null+++ b/src/client/src/__tests__/lib/platform/vector/external.test.ts@@ -0,0 +1,195 @@+const mockResolveDescriptor = jest.fn();+const mockGetAdapter = jest.fn();++jest.mock("@/lib/telemetry-source", () => ({+ resolveTelemetrySourceDescriptor: (...a: unknown[]) =>+ mockResolveDescriptor(...a),+ getTelemetryAdapter: (...a: unknown[]) => mockGetAdapter(...a),+}));++import {+ externalResultGenerationByOperation,+ externalResultGenerationBySystem,+ externalResultGenerationByEnvironment,+ externalResultGenerationByApplication,+} from "@/lib/platform/vector/external";++const tempo = {+ type: "tempo",+ id: "src-tempo",+ isBuiltIn: false,+ settings: {},+ signals: ["traces"],+ name: "Tempo",+ dbConfigId: "db-1",+};++const builtin = {+ type: "clickhouse",+ id: "builtin:db-1",+ isBuiltIn: true,+ settings: {},+ signals: ["traces"],+ name: "CH",+ dbConfigId: "db-1",+};++const params = {+ timeLimit: {+ start: new Date("2026-07-01T00:00:00.000Z"),+ end: new Date("2026-07-01T01:00:00.000Z"),+ type: "CUSTOM",+ },+ limit: 10,+ offset: 0,+ selectedConfig: {},+};++function adapterWith(aggregateSpans: jest.Mock) {+ return { capabilities: () => ({ serverAggregation: true }), aggregateSpans };+}++beforeEach(() => {+ jest.clearAllMocks();+ mockResolveDescriptor.mockResolvedValue(tempo);+});++describe("built-in ClickHouse routing", () => {+ it("returns null for every export on the built-in source", async () => {+ mockResolveDescriptor.mockResolvedValue(builtin);+ expect(await externalResultGenerationByOperation(params)).toBeNull();+ expect(await externalResultGenerationBySystem(params)).toBeNull();+ expect(await externalResultGenerationByEnvironment(params)).toBeNull();+ expect(await externalResultGenerationByApplication(params)).toBeNull();+ expect(mockGetAdapter).not.toHaveBeenCalled();+ });++ it("returns null when the resolved type is clickhouse even if not flagged built-in", async () => {+ mockResolveDescriptor.mockResolvedValue({ ...tempo, isBuiltIn: false, type: "clickhouse" });+ expect(await externalResultGenerationByOperation(params)).toBeNull();+ });++ it("resolves the traces adapter and scopes the query to vectordb operations", async () => {+ const aggregateSpans = jest.fn().mockResolvedValue({ rows: [] });+ mockGetAdapter.mockResolvedValue(adapterWith(aggregateSpans));++ await externalResultGenerationByOperation(params);++ expect(mockGetAdapter).toHaveBeenCalledWith({ signal: "traces", environment: undefined });+ const query = aggregateSpans.mock.calls[0][0];+ expect(query.filters).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ key: "gen_ai.operation.name",+ op: "eq",+ value: "vectordb",+ }),+ ])+ );+ expect(query.groupBy).toEqual(["db.operation"]);+ });+});++describe("externalResultGenerationByOperation", () => {+ it("groups by db.operation", async () => {+ const aggregateSpans = jest.fn().mockResolvedValue({+ rows: [{ group_value: "insert", count: 3 }],+ });+ mockGetAdapter.mockResolvedValue(adapterWith(aggregateSpans));++ const res = await externalResultGenerationByOperation(params);+ expect(res).toEqual({ err: null, data: [{ operation: "insert", count: 3 }] });+ });++ it("falls back to the raw field and zero count when absent", async () => {+ const aggregateSpans = jest.fn().mockResolvedValue({ rows: [{ "db.operation": "query" }] });+ mockGetAdapter.mockResolvedValue(adapterWith(aggregateSpans));++ const res = await externalResultGenerationByOperation(params);+ expect(res).toEqual({ err: null, data: [{ operation: "query", count: 0 }] });+ });++ it("defaults to an empty label when nothing is present", async () => {+ const aggregateSpans = jest.fn().mockResolvedValue({ rows: [{}] });+ mockGetAdapter.mockResolvedValue(adapterWith(aggregateSpans));++ const res = await externalResultGenerationByOperation(params);+ expect(res).toEqual({ err: null, data: [{ operation: "", count: 0 }] });+ });++ it("returns a stringified error when the adapter throws a non-Error value", async () => {+ const aggregateSpans = jest.fn().mockRejectedValue("boom");+ mockGetAdapter.mockResolvedValue(adapterWith(aggregateSpans));++ const res = await externalResultGenerationByOperation(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });++ it("returns the Error message when the adapter throws an Error", async () => {+ const aggregateSpans = jest.fn().mockRejectedValue(new Error("tempo down"));+ mockGetAdapter.mockResolvedValue(adapterWith(aggregateSpans));++ const res = await externalResultGenerationByOperation(params);+ expect(res).toEqual({ err: "tempo down", data: [] });+ });+});++describe("externalResultGenerationBySystem", () => {+ it("groups by db.system using the g0 alias", async () => {+ const aggregateSpans = jest.fn().mockResolvedValue({+ rows: [{ g0: "pinecone", count: 5 }],+ });+ mockGetAdapter.mockResolvedValue(adapterWith(aggregateSpans));++ const res = await externalResultGenerationBySystem(params);+ expect(res).toEqual({ err: null, data: [{ system: "pinecone", count: 5 }] });+ });++ it("returns an error payload on failure", async () => {+ const aggregateSpans = jest.fn().mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue(adapterWith(aggregateSpans));++ const res = await externalResultGenerationBySystem(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });+});++describe("externalResultGenerationByEnvironment", () => {+ it("groups by deployment.environment", async () => {+ const aggregateSpans = jest.fn().mockResolvedValue({+ rows: [{ "deployment.environment": "prod", count: 2 }],+ });+ mockGetAdapter.mockResolvedValue(adapterWith(aggregateSpans));++ const res = await externalResultGenerationByEnvironment(params);+ expect(res).toEqual({ err: null, data: [{ environment: "prod", count: 2 }] });+ });++ it("returns an error payload on failure", async () => {+ const aggregateSpans = jest.fn().mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue(adapterWith(aggregateSpans));++ const res = await externalResultGenerationByEnvironment(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });+});++describe("externalResultGenerationByApplication", () => {+ it("groups by service.name", async () => {+ const aggregateSpans = jest.fn().mockResolvedValue({+ rows: [{ group_value: "api", count: 7 }],+ });+ mockGetAdapter.mockResolvedValue(adapterWith(aggregateSpans));++ const res = await externalResultGenerationByApplication(params);+ expect(res).toEqual({ err: null, data: [{ applicationName: "api", count: 7 }] });+ });++ it("returns an error payload on failure", async () => {+ const aggregateSpans = jest.fn().mockRejectedValue(new Error("boom"));+ mockGetAdapter.mockResolvedValue(adapterWith(aggregateSpans));++ const res = await externalResultGenerationByApplication(params);+ expect(res).toEqual({ err: "boom", data: [] });+ });+});diff --git a/src/client/src/__tests__/lib/project-environment.test.ts b/src/client/src/__tests__/lib/project-environment.test.tsnew file mode 100644index 00000000..e9f8b3af--- /dev/null+++ b/src/client/src/__tests__/lib/project-environment.test.ts@@ -0,0 +1,145 @@+const mockFindMany = jest.fn();+const mockUpsert = jest.fn();+const mockGetCurrentOrganisation = jest.fn();+const mockGetCurrentProjectForOrganisation = jest.fn();++jest.mock("@/lib/prisma", () => ({+ __esModule: true,+ default: {+ projectEnvironment: {+ findMany: (...a: unknown[]) => mockFindMany(...a),+ upsert: (...a: unknown[]) => mockUpsert(...a),+ },+ },+}));++jest.mock("@/lib/organisation", () => ({+ getCurrentOrganisation: (...a: unknown[]) => mockGetCurrentOrganisation(...a),+ getCurrentProjectForOrganisation: (...a: unknown[]) =>+ mockGetCurrentProjectForOrganisation(...a),+}));++import {+ createProjectEnvironment,+ listProjectEnvironments,+ normalizeProjectEnvironment,+} from "@/lib/project-environment";+import prisma from "@/lib/prisma";++describe("normalizeProjectEnvironment", () => {+ it("lowercases and trims valid environment names", () => {+ expect(normalizeProjectEnvironment(" Prod-1 ")).toBe("prod-1");+ });++ it("accepts dots and underscores", () => {+ expect(normalizeProjectEnvironment("prod.eu_west")).toBe("prod.eu_west");+ });++ it("rejects empty input", () => {+ expect(() => normalizeProjectEnvironment("")).toThrow(+ "Environment must use lowercase letters, numbers, dots, hyphens, or underscores"+ );+ });++ it("rejects names starting with a disallowed character", () => {+ expect(() => normalizeProjectEnvironment("-prod")).toThrow();+ });++ it("rejects names with disallowed characters", () => {+ expect(() => normalizeProjectEnvironment("prod env")).toThrow();+ });++ it("rejects names over 63 characters", () => {+ expect(() => normalizeProjectEnvironment("a".repeat(64))).toThrow();+ });++ it("accepts names up to 63 characters", () => {+ const name = "a".repeat(63);+ expect(normalizeProjectEnvironment(name)).toBe(name);+ });++ it("coerces non-string values via String()", () => {+ expect(normalizeProjectEnvironment(123)).toBe("123");+ });++ it("rejects nullish input", () => {+ expect(() => normalizeProjectEnvironment(undefined)).toThrow();+ expect(() => normalizeProjectEnvironment(null)).toThrow();+ });+});++describe("listProjectEnvironments", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("lists environments scoped to the current project, ordered by name", async () => {+ mockGetCurrentOrganisation.mockResolvedValue({ id: "org-1" });+ mockGetCurrentProjectForOrganisation.mockResolvedValue({ id: "proj-1" });+ mockFindMany.mockResolvedValue([{ id: "e1", name: "prod" }]);++ const result = await listProjectEnvironments();++ expect(mockGetCurrentProjectForOrganisation).toHaveBeenCalledWith("org-1");+ expect(mockFindMany).toHaveBeenCalledWith({+ where: { projectId: "proj-1" },+ orderBy: { name: "asc" },+ });+ expect(result).toEqual([{ id: "e1", name: "prod" }]);+ });++ it("throws when there is no current organisation", async () => {+ mockGetCurrentOrganisation.mockResolvedValue(null);++ await expect(listProjectEnvironments()).rejects.toThrow(+ "Organisation is required"+ );+ expect(mockGetCurrentProjectForOrganisation).not.toHaveBeenCalled();+ });++ it("throws when the organisation has no project for the current context", async () => {+ mockGetCurrentOrganisation.mockResolvedValue({ id: "org-1" });+ mockGetCurrentProjectForOrganisation.mockResolvedValue(null);++ await expect(listProjectEnvironments()).rejects.toThrow(+ "Project is required"+ );+ });+});++describe("createProjectEnvironment", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockGetCurrentOrganisation.mockResolvedValue({ id: "org-1" });+ mockGetCurrentProjectForOrganisation.mockResolvedValue({ id: "proj-1" });+ });++ it("normalizes the name and upserts via prisma", async () => {+ mockUpsert.mockResolvedValue({ id: "e1", projectId: "proj-1", name: "prod" });++ const result = await createProjectEnvironment(" PROD ");++ expect(mockUpsert).toHaveBeenCalledWith({+ where: { projectId_name: { projectId: "proj-1", name: "prod" } },+ create: { projectId: "proj-1", name: "prod" },+ update: {},+ });+ expect(result).toEqual({ id: "e1", projectId: "proj-1", name: "prod" });+ });++ it("throws for an invalid environment name before touching prisma", async () => {+ await expect(createProjectEnvironment("bad env!")).rejects.toThrow();+ expect(mockUpsert).not.toHaveBeenCalled();+ });++ it("falls back to a stub record when the delegate lacks upsert (legacy CE mock)", async () => {+ const original = (prisma as any).projectEnvironment.upsert;+ (prisma as any).projectEnvironment.upsert = undefined;++ const result = await createProjectEnvironment("staging");++ expect(result).toEqual({ id: "", projectId: "proj-1", name: "staging" });++ (prisma as any).projectEnvironment.upsert = original;+ });+});diff --git a/src/client/src/__tests__/lib/telemetry-source-crud.test.ts b/src/client/src/__tests__/lib/telemetry-source-crud.test.tsindex 12d252a5..78eb362b 100644--- a/src/client/src/__tests__/lib/telemetry-source-crud.test.ts+++ b/src/client/src/__tests__/lib/telemetry-source-crud.test.ts@@ -19,6 +19,9 @@ const mockBindingUpsert = jest.fn();const mockBindingDeleteMany = jest.fn();const mockUpsertSecret = jest.fn();const mockGetSecretById = jest.fn();+const mockDatabaseConfigFindFirst = jest.fn();+const mockGetDBConfigByUser = jest.fn();+const mockGetDBConfigById = jest.fn();const mockTxBindingUpsert = jest.fn();@@ -52,6 +55,9 @@ jest.mock("@/lib/prisma", () => ({upsert: (...a: unknown[]) => mockBindingUpsert(...a),deleteMany: (...a: unknown[]) => mockBindingDeleteMany(...a),},+ databaseConfig: {+ findFirst: (...a: unknown[]) => mockDatabaseConfigFindFirst(...a),+ },$transaction: (fn: (tx: unknown) => unknown) => fn(txClient),},}));@@ -63,8 +69,8 @@ jest.mock("@/lib/organisation", () => ({}));jest.mock("@/lib/db-config", () => ({- getDBConfigByUser: jest.fn(),- getDBConfigById: jest.fn(),+ getDBConfigByUser: (...a: unknown[]) => mockGetDBConfigByUser(...a),+ getDBConfigById: (...a: unknown[]) => mockGetDBConfigById(...a),}));jest.mock("@/lib/platform/connectors/datasource/bootstrap", () => ({@@ -96,6 +102,7 @@ jest.mock("@/lib/project-environment", () => ({jest.mock("@/utils/log", () => ({ consoleLog: jest.fn() }));import {+ availableSourceTypeDescriptors,availableSourceTypes,createTelemetrySource,deleteTelemetrySource,@@ -103,6 +110,8 @@ import {healthCheckTelemetrySource,listTelemetrySources,listTelemetrySourceBindings,+ normalizeTelemetrySourceId,+ resolveProjectSignalCapabilities,setTelemetrySourceBinding,updateTelemetrySource,validateTelemetrySourceAISignal,@@ -133,6 +142,9 @@ beforeEach(() => {mockFindFirst.mockResolvedValue(null);mockBindingFindUnique.mockResolvedValue(null);mockBindingFindFirst.mockResolvedValue(null);+ mockDatabaseConfigFindFirst.mockReset().mockResolvedValue(null);+ mockGetDBConfigByUser.mockReset();+ mockGetDBConfigById.mockReset();mockConnectorUpsert.mockResolvedValue({});mockGetSourceTypeDescriptor.mockImplementation((type: string) => ({type,@@ -185,6 +197,28 @@ describe("listTelemetrySources", () => {await expect(listTelemetrySources()).rejects.toThrow();expect(mockFindMany).not.toHaveBeenCalled();});++ it("denies when there is no current organisation at all", async () => {+ mockGetCurrentOrganisation.mockResolvedValue(null);+ await expect(listTelemetrySources()).rejects.toThrow();+ expect(mockFindMany).not.toHaveBeenCalled();+ });+});++describe("normalizeTelemetrySourceId", () => {+ it("strips a single connector-registry prefix", () => {+ expect(normalizeTelemetrySourceId("telemetry:src-1")).toBe("src-1");+ });++ it("strips repeated connector-registry prefixes", () => {+ expect(normalizeTelemetrySourceId("telemetry:telemetry:src-1")).toBe(+ "src-1"+ );+ });++ it("leaves an unprefixed id untouched", () => {+ expect(normalizeTelemetrySourceId("src-1")).toBe("src-1");+ });});describe("availableSourceTypes", () => {@@ -193,6 +227,24 @@ describe("availableSourceTypes", () => {});});+describe("availableSourceTypeDescriptors", () => {+ it("fills in a description and icon for each registered type", () => {+ mockListSourceTypeDescriptors.mockReturnValue([+ { type: "tempo", displayName: "Tempo" },+ { type: "custom-vendor", displayName: "Custom", description: "Already described", icon: "/already.svg" },+ ]);+ const descriptors = availableSourceTypeDescriptors();+ expect(descriptors[0]).toMatchObject({ type: "tempo" });+ expect(typeof descriptors[0].description).toBe("string");+ expect(descriptors[0].description.length).toBeGreaterThan(0);+ // A descriptor that already supplies a description/icon keeps it as-is.+ expect(descriptors[1]).toMatchObject({+ description: "Already described",+ icon: "/already.svg",+ });+ });+});+describe("createTelemetrySource", () => {it("creates a project-scoped source and normalizes signals/settings", async () => {mockCreate.mockResolvedValue(row());@@ -251,6 +303,23 @@ describe("createTelemetrySource", () => {);});+ it("preserves an explicit environment on the synced connector instance", async () => {+ mockCreate.mockResolvedValue(+ row({ id: "src-stg", type: "loki", name: "staging-loki", signals: "logs", environment: "staging" })+ );+ await createTelemetrySource({+ name: "staging-loki",+ type: "loki",+ environment: "staging",+ });+ expect(mockConnectorUpsert).toHaveBeenCalledWith(+ expect.objectContaining({+ create: expect.objectContaining({ environment: "staging" }),+ update: expect.objectContaining({ environment: "staging" }),+ })+ );+ });+it("normalizes collapsed endpoint URLs before persist", async () => {mockCreate.mockResolvedValue(row({ id: "src-prom", type: "prometheus", name: "local-prometheus", signals: "metrics" }));await createTelemetrySource({@@ -271,12 +340,185 @@ describe("createTelemetrySource", () => {).rejects.toThrow();});+ it("rejects a blank source type", async () => {+ await expect(+ createTelemetrySource({ name: "X", type: "" })+ ).rejects.toThrow();+ expect(mockCreate).not.toHaveBeenCalled();+ });++ it("allows a registered type even when its descriptor is unavailable for the internal check", async () => {+ mockGetSourceTypeDescriptor.mockReturnValueOnce(undefined).mockImplementation((type: string) => ({+ type,+ displayName: type,+ declaredSignals: ["traces", "logs", "metrics"],+ capabilities: {+ traceTree: true,+ spanEvents: false,+ serverAggregation: true,+ spanMutation: false,+ distinctValues: true,+ crossTraceSession: false,+ rawQuery: false,+ },+ }));+ mockCreate.mockResolvedValue(row({ type: "mystery" }));+ await expect(+ createTelemetrySource({ name: "Mystery", type: "mystery" })+ ).resolves.toMatchObject({ type: "mystery" });+ });+it("rejects non-object settings", async () => {await expect(createTelemetrySource({ name: "X", type: "datadog", settings: "[1,2]" })).rejects.toThrow();});+ it("rejects malformed JSON settings", async () => {+ await expect(+ createTelemetrySource({ name: "X", type: "datadog", settings: "{not-json" })+ ).rejects.toThrow(/JSON object/);+ });++ it("rejects a non-object, non-string settings value", async () => {+ await expect(+ createTelemetrySource({ name: "X", type: "datadog", settings: 42 })+ ).rejects.toThrow(/JSON object/);+ });++ it("accepts settings passed as a valid JSON string and normalizes the endpoint URL", async () => {+ mockCreate.mockResolvedValue(row({ id: "src-prom2", type: "prometheus", signals: "metrics" }));+ await createTelemetrySource({+ name: "prom-str-settings",+ type: "prometheus",+ settings: '{"url":"http:/localhost:9090"}',+ });+ expect(mockCreate.mock.calls[0][0].data.settings).toContain(+ '"url":"http://localhost:9090"'+ );+ });++ it("accepts signals passed as a comma-separated string", async () => {+ mockCreate.mockResolvedValue(row({ signals: "traces,logs" }));+ await createTelemetrySource({+ name: "Prod DD",+ type: "datadog",+ signals: "traces, logs",+ });+ expect(mockCreate.mock.calls[0][0].data.signals).toBe("traces,logs");+ });++ it("falls back to all signals for a non-array, non-string signals value, then rejects one the type cannot serve", async () => {+ // rawSignals(42) falls back to parseSignals(undefined) -> every signal,+ // including "intelligence" which datadog's declared set does not cover.+ await expect(+ createTelemetrySource({+ name: "Prod DD",+ type: "datadog",+ signals: 42 as unknown as string,+ })+ ).rejects.toThrow(/cannot serve/);+ });++ it("defaults declared signals to traces/logs/metrics when the type descriptor is unavailable", async () => {+ // First call is validateType's `.internal` check; second is+ // normalizeSignalsForType's declared-signals lookup, which we want to+ // miss so the hard-coded fallback default applies.+ mockGetSourceTypeDescriptor+ .mockImplementationOnce((t: string) => ({ type: t, internal: false }))+ .mockReturnValueOnce(undefined);+ mockCreate.mockResolvedValue(row({ type: "mystery", signals: "traces,logs,metrics" }));+ await createTelemetrySource({ name: "Mystery", type: "mystery" });+ expect(mockCreate.mock.calls[0][0].data.signals).toBe("traces,logs,metrics");+ });++ it("rejects an internal-only registered type", async () => {+ mockGetSourceTypeDescriptor.mockReturnValue({+ type: "internal-type",+ internal: true,+ declaredSignals: ["traces"],+ });+ await expect(+ createTelemetrySource({ name: "X", type: "internal-type" })+ ).rejects.toThrow();+ expect(mockCreate).not.toHaveBeenCalled();+ });++ it("converts a unique-constraint P2002 transaction error into a friendly name-taken error", async () => {+ mockCreate.mockRejectedValue(+ Object.assign(new Error("unique violation"), { code: "P2002" })+ );+ await expect(+ createTelemetrySource({ name: "Prod DD", type: "datadog" })+ ).rejects.toThrow(/already exists/);+ });++ it("converts a raw 'Unique constraint failed' message into a friendly name-taken error", async () => {+ mockCreate.mockRejectedValue(new Error("Unique constraint failed on the fields: (`name`)"));+ await expect(+ createTelemetrySource({ name: "Prod DD", type: "datadog" })+ ).rejects.toThrow(/already exists/);+ });++ it("rethrows a non-unique-constraint transaction error unchanged", async () => {+ mockCreate.mockRejectedValue(new Error("connection reset"));+ await expect(+ createTelemetrySource({ name: "Prod DD", type: "datadog" })+ ).rejects.toThrow("connection reset");+ });++ it("rethrows a non-Error transaction rejection unchanged", async () => {+ mockCreate.mockRejectedValue("plain string failure");+ await expect(+ createTelemetrySource({ name: "Prod DD", type: "datadog" })+ ).rejects.toBe("plain string failure");+ });++ it("does not misclassify an error object with a falsy code as a unique-constraint violation", async () => {+ mockCreate.mockRejectedValue(+ Object.assign(new Error("some other failure"), { code: "" })+ );+ await expect(+ createTelemetrySource({ name: "Prod DD", type: "datadog" })+ ).rejects.toThrow("some other failure");+ });++ it("rethrows a falsy non-Error transaction rejection unchanged", async () => {+ mockCreate.mockRejectedValue("");+ await expect(+ createTelemetrySource({ name: "Prod DD", type: "datadog" })+ ).rejects.toBe("");+ });++ it("rejects a completely missing name", async () => {+ await expect(+ createTelemetrySource({ type: "datadog" })+ ).rejects.toThrow();+ expect(mockCreate).not.toHaveBeenCalled();+ });++ it("falls back to no secretRef when the vault returns a bare string instead of an object", async () => {+ mockCreate.mockResolvedValue(row());+ mockUpsertSecret.mockResolvedValueOnce("raw-secret-id" as unknown as { id?: string });+ await createTelemetrySource({+ name: "Prod DD",+ type: "datadog",+ credentials: { apiKey: "dd-key" },+ });+ expect(mockCreate.mock.calls[0][0].data.secretRef).toBeNull();+ });++ it("rejects an environment string with invalid characters", async () => {+ await expect(+ createTelemetrySource({+ name: "Prod DD",+ type: "datadog",+ environment: "bad env!",+ })+ ).rejects.toThrow(/Environment must use/);+ expect(mockCreate).not.toHaveBeenCalled();+ });+it("rejects a signal the source type cannot serve", async () => {await expect(createTelemetrySource({ name: "T", type: "tempo", signals: ["logs"] })@@ -378,6 +620,88 @@ describe("updateTelemetrySource", () => {});expect(mockUpdate.mock.calls[0][0].data.isDefault).toBe(true);});++ it("explicitly demotes a source from default without promoting another", async () => {+ mockFindFirst.mockResolvedValue(row({ isDefault: true }));+ mockUpdate.mockResolvedValue(row({ isDefault: false }));+ await updateTelemetrySource("src-1", { isDefault: false });+ expect(mockUpdateMany).not.toHaveBeenCalled();+ expect(mockUpdate.mock.calls[0][0].data.isDefault).toBe(false);+ });++ it("normalizes and persists an environment change, provisioning it first", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockUpdate.mockResolvedValue(row({ environment: "staging" }));+ await updateTelemetrySource("src-1", { environment: "Staging" });+ expect(mockUpdate.mock.calls[0][0].data.environment).toBe("staging");+ });++ it("re-validates the stored signals against the new type when the type changes without explicit signals", async () => {+ mockFindFirst.mockResolvedValue(row({ type: "datadog", signals: "traces" }));+ mockUpdate.mockResolvedValue(row({ type: "tempo", signals: "traces" }));+ await updateTelemetrySource("src-1", { type: "tempo" });+ expect(mockUpdate.mock.calls[0][0].data).toMatchObject({+ type: "tempo",+ signals: "traces",+ });+ });++ it("rejects a type change when the existing stored signals are no longer valid for the new type", async () => {+ mockFindFirst.mockResolvedValue(row({ type: "datadog", signals: "traces,logs,metrics" }));+ await expect(+ updateTelemetrySource("src-1", { type: "tempo" })+ ).rejects.toThrow(/cannot serve/);+ expect(mockUpdate).not.toHaveBeenCalled();+ });++ it("applies explicitly provided signals over the type's full declared set", async () => {+ mockFindFirst.mockResolvedValue(row({ type: "datadog", signals: "traces,logs,metrics" }));+ mockUpdate.mockResolvedValue(row({ signals: "logs" }));+ await updateTelemetrySource("src-1", { signals: ["logs"] });+ expect(mockUpdate.mock.calls[0][0].data.signals).toBe("logs");+ });++ it("repoints secretRef to a newly persisted vault credential", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockUpdate.mockResolvedValue(row({ secretRef: "vault-new" }));+ await updateTelemetrySource("src-1", { credentials: { apiKey: "new-key" } });+ expect(mockUpsertSecret).toHaveBeenCalledTimes(1);+ expect(mockUpdate.mock.calls[0][0].data.secretRef).toBe("vault-new");+ });++ it("applies an explicit secretRef update when no inline credentials are given", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockUpdate.mockResolvedValue(row({ secretRef: "explicit-ref" }));+ await updateTelemetrySource("src-1", { secretRef: "explicit-ref" });+ expect(mockUpsertSecret).not.toHaveBeenCalled();+ expect(mockUpdate.mock.calls[0][0].data.secretRef).toBe("explicit-ref");+ });++ it("clears secretRef when explicitly set to a non-string value", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockUpdate.mockResolvedValue(row({ secretRef: null }));+ await updateTelemetrySource("src-1", { secretRef: null });+ expect(mockUpdate.mock.calls[0][0].data.secretRef).toBeNull();+ });++ it("rejects an explicitly blank (but defined) name on update", async () => {+ mockFindFirst.mockResolvedValue(row());+ await expect(updateTelemetrySource("src-1", { name: "" })).rejects.toThrow(+ /name is required/i+ );+ expect(mockUpdate).not.toHaveBeenCalled();+ });++ it("normalizes and persists updated settings", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockUpdate.mockResolvedValue(row({ settings: '{"url":"http://localhost:9090"}' }));+ await updateTelemetrySource("src-1", {+ settings: { url: "http:/localhost:9090" },+ });+ expect(mockUpdate.mock.calls[0][0].data.settings).toContain(+ '"url":"http://localhost:9090"'+ );+ });});describe("deleteTelemetrySource", () => {@@ -409,6 +733,18 @@ describe("healthCheckTelemetrySource", () => {const res = await healthCheckTelemetrySource("src-1");expect(res.ok).toBe(false);});++ it("attaches the active database config id to the adapter descriptor when one is bound", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockGetDBConfigByUser.mockResolvedValue({ id: "db-active" });+ mockCreateAdapter.mockReturnValue({+ healthCheck: jest.fn().mockResolvedValue({ ok: true }),+ });+ await healthCheckTelemetrySource("src-1");+ expect(mockCreateAdapter.mock.calls[0][0]).toMatchObject({+ dbConfigId: "db-active",+ });+ });});describe("validateTelemetrySourceAISignal", () => {@@ -443,6 +779,92 @@ describe("validateTelemetrySourceAISignal", () => {expect(res.supported).toBe(false);expect(res.ok).toBe(true);});++ it("rethrows a non-capability error from the adapter", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockCreateAdapter.mockReturnValue({+ validateAISignal: jest.fn().mockRejectedValue(new Error("upstream 500")),+ });+ await expect(+ validateTelemetrySourceAISignal("src-1", {+ start: new Date("2026-07-01"),+ end: new Date("2026-07-02"),+ })+ ).rejects.toThrow("upstream 500");+ });++ it("returns not-supported when no adapter is registered for the type", async () => {+ mockFindFirst.mockResolvedValue(row({ type: "unknownvendor" }));+ mockCreateAdapter.mockReturnValue(undefined);+ const res = await validateTelemetrySourceAISignal("src-1", {+ start: new Date("2026-07-01"),+ end: new Date("2026-07-02"),+ });+ expect(res).toMatchObject({ ok: false, supported: false, sampleCount: 0 });+ });+});++describe("resolveProjectSignalCapabilities", () => {+ it("reports null capabilities for every signal when nothing is routed", async () => {+ mockCreateAdapter.mockReturnValue(undefined);+ const result = await resolveProjectSignalCapabilities();+ expect(Object.keys(result)).toEqual(["traces", "logs", "metrics", "intelligence"]);+ for (const signal of Object.keys(result)) {+ expect(result[signal as keyof typeof result]).toMatchObject({+ sourceType: "clickhouse",+ isBuiltIn: true,+ capabilities: null,+ });+ }+ });++ it("drops the per-instance signals list from resolved capabilities", async () => {+ mockCreateAdapter.mockReturnValue({+ capabilities: () => ({+ signals: ["traces"],+ traceTree: true,+ spanEvents: false,+ serverAggregation: true,+ spanMutation: false,+ distinctValues: true,+ crossTraceSession: false,+ rawQuery: false,+ }),+ });+ const result = await resolveProjectSignalCapabilities();+ const traces = result.traces;+ expect(traces?.capabilities).not.toHaveProperty("signals");+ expect(traces?.capabilities).toMatchObject({ traceTree: true });+ });++ it("reports null for a signal whose resolution throws, without failing the others", async () => {+ mockBindingFindUnique.mockRejectedValueOnce(new Error("db unavailable"));+ mockCreateAdapter.mockReturnValue(undefined);+ const result = await resolveProjectSignalCapabilities("production");+ expect(result.traces).toBeNull();+ expect(result.logs).toMatchObject({ sourceType: "clickhouse" });+ });++ it("treats a bound source explicitly typed clickhouse as built-in even when not flagged as such", async () => {+ mockBindingFindUnique.mockResolvedValue({+ sourceId: "src-ch",+ databaseConfigId: null,+ source: {+ id: "src-ch",+ name: "Weird CH",+ type: "clickhouse",+ signals: "traces,logs,metrics,intelligence",+ settings: "{}",+ secretRef: null,+ projectId: "proj-1",+ environment: "production",+ },+ databaseConfig: null,+ });+ mockCreateAdapter.mockReturnValue(undefined);+ const result = await resolveProjectSignalCapabilities();+ expect(result.traces).toMatchObject({ sourceType: "clickhouse", isBuiltIn: true });+ });});describe("telemetry source bindings", () => {@@ -469,6 +891,46 @@ describe("telemetry source bindings", () => {});});+ it("lists a builtin-bound signal without an external source", async () => {+ mockBindingFindMany.mockResolvedValue([+ {+ id: "b2",+ signal: "metrics",+ sourceId: null,+ databaseConfigId: "db-5",+ source: null,+ databaseConfig: { name: "Builtin CH" },+ },+ ]);+ const bindings = await listTelemetrySourceBindings();+ expect(bindings[0]).toMatchObject({+ signal: "metrics",+ sourceId: "builtin:db-5",+ sourceName: "Builtin CH",+ sourceType: "clickhouse",+ });+ });++ it("lists a signal binding with no source and no database config at all", async () => {+ mockBindingFindMany.mockResolvedValue([+ {+ id: "b3",+ signal: "logs",+ sourceId: null,+ databaseConfigId: null,+ source: null,+ databaseConfig: null,+ },+ ]);+ const bindings = await listTelemetrySourceBindings();+ expect(bindings[0]).toMatchObject({+ signal: "logs",+ sourceId: "",+ sourceName: null,+ sourceType: "clickhouse",+ });+ });+it("binds a signal to a source that serves it (project-scoped)", async () => {mockFindFirst.mockResolvedValue(row({ signals: "traces,logs,metrics" }));mockBindingFindUnique.mockResolvedValue({@@ -538,6 +1000,94 @@ describe("telemetry source bindings", () => {).rejects.toThrow();});+ it("rejects binding an external source whose environment does not match the requested one", async () => {+ mockFindFirst.mockResolvedValue(+ row({ signals: "traces", environment: "staging" })+ );+ await expect(+ setTelemetrySourceBinding("traces", "src-1", "production")+ ).rejects.toThrow(/does not match|environment/i);+ expect(mockBindingUpsert).not.toHaveBeenCalled();+ });++ it("binds a signal to a built-in ClickHouse database config via a builtin: source id", async () => {+ mockDatabaseConfigFindFirst.mockResolvedValue({+ id: "db-9",+ name: "Staging CH",+ projectId: "proj-1",+ environment: "staging",+ });+ mockBindingFindUnique.mockResolvedValue({+ sourceId: null,+ databaseConfigId: "db-old",+ source: null,+ });+ mockBindingUpsert.mockResolvedValue({ id: "b3", signal: "metrics" });+ const result = await setTelemetrySourceBinding(+ "metrics",+ "builtin:db-9",+ "staging"+ );+ expect(result).toMatchObject({+ signal: "metrics",+ sourceId: "builtin:db-9",+ environment: "staging",+ previousSourceId: "builtin:db-old",+ previousSourceType: "clickhouse",+ nextSourceType: "clickhouse",+ });+ expect(mockBindingUpsert).toHaveBeenCalledWith({+ where: {+ projectId_signal_environment: {+ projectId: "proj-1",+ signal: "metrics",+ environment: "staging",+ },+ },+ create: {+ projectId: "proj-1",+ signal: "metrics",+ environment: "staging",+ sourceId: null,+ databaseConfigId: "db-9",+ },+ update: { sourceId: null, databaseConfigId: "db-9" },+ });+ });++ it("rejects a builtin: source id that does not resolve to a project database config", async () => {+ mockDatabaseConfigFindFirst.mockResolvedValue(null);+ await expect(+ setTelemetrySourceBinding("metrics", "builtin:missing-db")+ ).rejects.toThrow();+ expect(mockBindingUpsert).not.toHaveBeenCalled();+ });++ it("rejects a builtin: database config whose environment does not match the requested one", async () => {+ mockDatabaseConfigFindFirst.mockResolvedValue({+ id: "db-9",+ name: "Staging CH",+ projectId: "proj-1",+ environment: "staging",+ });+ await expect(+ setTelemetrySourceBinding("metrics", "builtin:db-9", "production")+ ).rejects.toThrow(/does not match|environment/i);+ expect(mockBindingUpsert).not.toHaveBeenCalled();+ });++ it("treats a malformed existing binding (neither sourceId nor databaseConfigId) as having no previous source", async () => {+ mockBindingFindFirst.mockResolvedValue({+ sourceId: null,+ databaseConfigId: null,+ source: null,+ });+ mockBindingDeleteMany.mockResolvedValue({ count: 1 });+ await expect(deleteTelemetrySourceBinding("metrics")).resolves.toMatchObject(+ { previousSourceId: null, previousSourceType: null }+ );+ });+it("deletes a signal binding (project-scoped)", async () => {mockBindingFindFirst.mockResolvedValue({sourceId: "src-9",diff --git a/src/client/src/__tests__/lib/telemetry-source.test.ts b/src/client/src/__tests__/lib/telemetry-source.test.tsindex a619f518..786442c0 100644--- a/src/client/src/__tests__/lib/telemetry-source.test.ts+++ b/src/client/src/__tests__/lib/telemetry-source.test.ts@@ -49,6 +49,26 @@ jest.mock("@/utils/log", () => ({consoleLog: jest.fn(),}));+let headerValues: Record<string, string | null> = {};+jest.mock("next/headers", () => ({+ headers: jest.fn(async () => ({+ get: (key: string) => headerValues[key] ?? null,+ })),+}));++// Wrap the real adapter registry so most tests exercise genuine adapter+// construction (as before), while a couple of defensive-fallback tests can+// force a single `createAdapter` call to miss without disabling the registry.+jest.mock("@/lib/platform/connectors/datasource/registry", () => {+ const actual = jest.requireActual(+ "@/lib/platform/connectors/datasource/registry"+ );+ return { ...actual, createAdapter: jest.fn(actual.createAdapter) };+});++import { OPENLIT_CONTEXT_HEADERS, MIDDLEWARE_DATABASE_CONFIG_HEADER } from "@/constants/openlit-context";+import { createAdapter as mockedCreateAdapter } from "@/lib/platform/connectors/datasource/registry";+import { headers as mockedHeaders } from "next/headers";import {builtInDescriptor,getTelemetryAdapter,@@ -86,6 +106,22 @@ const dbConfig = {beforeEach(() => {jest.clearAllMocks();+ headerValues = {};+ // These mocks return real domain data (DatabaseConfig/TelemetrySource rows,+ // org/project ids) that several tests configure with a sticky+ // `mockResolvedValue`. `clearAllMocks` only clears call history, not that+ // configured value, so explicitly reset them here to avoid one test's+ // setup leaking into the next test's "no data configured" expectations.+ mockFindUnique.mockReset();+ mockFindFirst.mockReset();+ mockFindMany.mockReset();+ mockBindingFindUnique.mockReset();+ mockDatabaseConfigFindFirst.mockReset();+ mockGetDBConfigByUser.mockReset();+ mockGetDBConfigById.mockReset();+ mockGetDBConfigByIdInternal.mockReset();+ mockGetCurrentOrganisation.mockReset();+ mockGetCurrentProjectForOrganisation.mockReset();});describe("parseSignals", () => {@@ -161,6 +197,84 @@ describe("toDescriptor", () => {});});+describe("request-context header resolution (getCurrentProjectId)", () => {+ it("uses the x-openlit-project-id header directly, skipping org lookup", async () => {+ headerValues[OPENLIT_CONTEXT_HEADERS.projectId] = "proj-header";+ mockFindFirst.mockResolvedValue(null);+ mockGetDBConfigByUser.mockResolvedValue(dbConfig);++ await resolveTelemetrySourceDescriptor();++ expect(mockGetCurrentOrganisation).not.toHaveBeenCalled();+ expect(mockFindFirst).toHaveBeenCalledWith({+ where: { projectId: "proj-header", isDefault: true },+ orderBy: { createdAt: "asc" },+ });+ });++ it("resolves the project via the middleware database-config header when no project header is present", async () => {+ headerValues[MIDDLEWARE_DATABASE_CONFIG_HEADER] = "db-header";+ mockGetDBConfigByIdInternal.mockResolvedValue({+ id: "db-header",+ projectId: "proj-fromheader",+ });+ mockFindFirst.mockResolvedValue(null);+ mockGetDBConfigByUser.mockResolvedValue(dbConfig);++ await resolveTelemetrySourceDescriptor();++ expect(mockGetDBConfigByIdInternal).toHaveBeenCalledWith({ id: "db-header" });+ expect(mockFindFirst).toHaveBeenCalledWith({+ where: { projectId: "proj-fromheader", isDefault: true },+ orderBy: { createdAt: "asc" },+ });+ });++ it("falls through to org lookup when the header database config has no projectId", async () => {+ headerValues[MIDDLEWARE_DATABASE_CONFIG_HEADER] = "db-header";+ mockGetDBConfigByIdInternal.mockResolvedValue({ id: "db-header" });+ mockGetCurrentOrganisation.mockResolvedValue({ id: "org-1" });+ mockGetCurrentProjectForOrganisation.mockResolvedValue({ id: "proj-1" });+ mockFindFirst.mockResolvedValue(null);+ mockGetDBConfigByUser.mockResolvedValue(dbConfig);++ await resolveTelemetrySourceDescriptor();++ expect(mockFindFirst).toHaveBeenCalledWith({+ where: { projectId: "proj-1", isDefault: true },+ orderBy: { createdAt: "asc" },+ });+ });++ it("treats a request-context header read failure (e.g. outside a request scope) as no headers", async () => {+ (mockedHeaders as jest.Mock).mockRejectedValueOnce(new Error("no request context"));+ mockGetCurrentOrganisation.mockResolvedValue({ id: "org-1" });+ mockGetCurrentProjectForOrganisation.mockResolvedValue({ id: "proj-1" });+ mockFindFirst.mockResolvedValue(null);+ mockGetDBConfigByUser.mockResolvedValue(dbConfig);++ const d = await resolveTelemetrySourceDescriptor();++ expect(mockFindFirst).toHaveBeenCalledWith({+ where: { projectId: "proj-1", isDefault: true },+ orderBy: { createdAt: "asc" },+ });+ expect(d).toMatchObject({ type: "clickhouse", isBuiltIn: true });+ });++ it("returns a null project id when the organisation lookup throws", async () => {+ mockGetCurrentOrganisation.mockRejectedValue(new Error("org lookup down"));+ mockGetDBConfigByUser.mockResolvedValue(dbConfig);++ const d = await resolveTelemetrySourceDescriptor();++ // No project -> step 2 (project default) is skipped entirely, falling+ // straight through to the built-in ClickHouse source.+ expect(mockFindFirst).not.toHaveBeenCalled();+ expect(d).toMatchObject({ type: "clickhouse", isBuiltIn: true });+ });+});+describe("resolveTelemetrySourceDescriptor precedence", () => {it("1. resolves an explicit sourceId override within the current project", async () => {mockGetCurrentOrganisation.mockResolvedValue({ id: "org-1" });@@ -308,6 +422,36 @@ describe("resolveTelemetrySourceDescriptor precedence", () => {isBuiltIn: true,});});++ it("resolves a builtin: sourceId override for the non-signal-aware path", async () => {+ mockGetCurrentOrganisation.mockResolvedValue({ id: "org-1" });+ mockGetCurrentProjectForOrganisation.mockResolvedValue({ id: "proj-1" });+ mockDatabaseConfigFindFirst.mockResolvedValue({+ id: "db-9",+ name: "Staging CH",+ projectId: "proj-1",+ });++ const d = await resolveTelemetrySourceDescriptor({ sourceId: "builtin:db-9" });++ expect(d).toMatchObject({ id: "builtin:db-9", type: "clickhouse", dbConfigId: "db-9" });+ expect(mockDatabaseConfigFindFirst).toHaveBeenCalledWith({+ where: { id: "db-9", projectId: "proj-1" },+ });+ });++ it("uses an explicit projectId option instead of resolving the current project", async () => {+ mockFindFirst.mockResolvedValue(null);+ mockGetDBConfigByUser.mockResolvedValue(dbConfig);++ await resolveTelemetrySourceDescriptor({ projectId: "proj-explicit" });++ expect(mockGetCurrentOrganisation).not.toHaveBeenCalled();+ expect(mockFindFirst).toHaveBeenCalledWith({+ where: { projectId: "proj-explicit", isDefault: true },+ orderBy: { createdAt: "asc" },+ });+ });});describe("resolveSignalSource (signal-aware routing)", () => {@@ -433,6 +577,114 @@ describe("resolveSignalSource (signal-aware routing)", () => {},});});++ it("falls through to binding/built-in resolution when a builtin: sourceId is not found in the project", async () => {+ mockDatabaseConfigFindFirst.mockResolvedValue(null);+ mockBindingFindUnique.mockResolvedValue({+ source: srcRow({ id: "tempo-1", type: "tempo", signals: "traces" }),+ });++ const res = await resolveSignalSource("traces", {+ sourceId: "builtin:missing-db",+ });++ expect(res.via).toBe("binding");+ expect(res.descriptor.id).toBe("tempo-1");+ });++ it("resolves an explicit external sourceId override that serves the requested signal", async () => {+ mockFindFirst.mockResolvedValue(+ srcRow({ id: "tempo-1", type: "tempo", signals: "traces" })+ );++ const res = await resolveSignalSource("traces", { sourceId: "tempo-1" });++ expect(res.via).toBe("override");+ expect(res.hasSource).toBe(true);+ expect(res.servesSignal).toBe(true);+ expect(res.descriptor.id).toBe("tempo-1");+ });++ it("resolves an explicit external sourceId override that does NOT serve the requested signal", async () => {+ mockFindFirst.mockResolvedValue(+ srcRow({ id: "prom-1", type: "prometheus", signals: "metrics" })+ );++ const res = await resolveSignalSource("traces", { sourceId: "prom-1" });++ expect(res.via).toBe("override");+ expect(res.hasSource).toBe(true);+ expect(res.servesSignal).toBe(false);+ expect(res.descriptor.id).toBe("prom-1");+ });++ it("falls back to 'production' when an invalid environment string is supplied", async () => {+ mockBindingFindUnique.mockResolvedValue(null);+ mockGetDBConfigByUser.mockResolvedValue(dbConfig);++ const res = await resolveSignalSource("traces", { environment: "Not Valid!!" });++ expect(mockBindingFindUnique).toHaveBeenCalledWith({+ where: {+ projectId_signal_environment: {+ projectId: "proj-1",+ signal: "traces",+ environment: "production",+ },+ },+ include: { source: true, databaseConfig: true },+ });+ // An explicitly requested (if invalid) environment still fails closed+ // when nothing is routed for it, rather than silently using a default.+ expect(res.via).toBe("none");+ });++ it("scopes resolveActiveCredentialDatabase to null when an explicit projectId is given without a dbConfigId", async () => {+ mockBindingFindUnique.mockResolvedValue({+ source: srcRow({ id: "tempo-1", type: "tempo", signals: "traces" }),+ });+ // If resolveActiveCredentialDatabase fell through to the user-DB lookup+ // instead of short-circuiting on the explicit projectId, this value+ // would leak into the resolved descriptor's dbConfigId.+ mockGetDBConfigByUser.mockResolvedValue(dbConfig);++ const res = await resolveSignalSource("traces", { projectId: "proj-1" });++ expect(mockGetDBConfigByUser).not.toHaveBeenCalled();+ expect(res.descriptor.dbConfigId).toBeUndefined();+ });++ it("resolves the active vault database from the middleware header when no dbConfigId/projectId override is given", async () => {+ headerValues[MIDDLEWARE_DATABASE_CONFIG_HEADER] = "db-header";+ mockGetDBConfigByIdInternal.mockResolvedValue({+ ...dbConfig,+ id: "db-header",+ environment: "production",+ });+ mockBindingFindUnique.mockResolvedValue({+ source: srcRow({ id: "tempo-1", type: "tempo", signals: "traces" }),+ });++ const res = await resolveSignalSource("traces");++ expect(mockGetDBConfigByIdInternal).toHaveBeenCalledWith({ id: "db-header" });+ expect(res.descriptor).toMatchObject({ id: "tempo-1", dbConfigId: "db-header" });+ });++ it("treats a failed active-database lookup as no active database instead of throwing", async () => {+ // Only the first getDBConfigByUser call (inside+ // resolveActiveCredentialDatabase) should be affected by the failure;+ // the built-in fallback's own lookup resolves normally afterward.+ mockGetDBConfigByUser+ .mockRejectedValueOnce(new Error("db down"))+ .mockResolvedValueOnce(undefined);+ mockBindingFindUnique.mockResolvedValue(null);++ const res = await resolveSignalSource("traces");++ expect(res.hasSource).toBe(false);+ expect(res.via).toBe("none");+ });});describe("getTelemetryAdapter fail-closed", () => {@@ -457,6 +709,54 @@ describe("getTelemetryAdapter fail-closed", () => {/No adapter is registered/);});++ it("resolves via resolveSignalSource when called with a signal and no descriptor", async () => {+ mockGetCurrentOrganisation.mockResolvedValue({ id: "org-1" });+ mockGetCurrentProjectForOrganisation.mockResolvedValue({ id: "proj-1" });+ mockBindingFindUnique.mockResolvedValue({+ source: srcRow({ id: "tempo-1", type: "tempo", signals: "traces" }),+ });++ const adapter = await getTelemetryAdapter({ signal: "traces" });+ expect(adapter).toBeDefined();+ });++ it("throws the typed no-source error when the requested signal has no source", async () => {+ mockGetCurrentOrganisation.mockResolvedValue({ id: "org-1" });+ mockGetCurrentProjectForOrganisation.mockResolvedValue({ id: "proj-1" });+ mockBindingFindUnique.mockResolvedValue(null);+ mockGetDBConfigByUser.mockResolvedValue(undefined);++ await expect(getTelemetryAdapter({ signal: "traces" })).rejects.toThrow(+ /No connector is configured/+ );+ });++ it("falls back to a fresh built-in ClickHouse adapter when the resolved adapter transiently fails to construct", async () => {+ mockGetCurrentOrganisation.mockResolvedValue({ id: "org-1" });+ mockGetCurrentProjectForOrganisation.mockResolvedValue({ id: "proj-1" });+ mockFindFirst.mockResolvedValue(null);+ mockGetDBConfigByUser.mockResolvedValue(dbConfig);+ (mockedCreateAdapter as jest.Mock).mockReturnValueOnce(undefined);++ const adapter = await getTelemetryAdapter();+ expect(adapter).toBeDefined();+ expect(mockedCreateAdapter).toHaveBeenCalledTimes(2);+ });++ it("throws when even the built-in ClickHouse fallback factory is unavailable", async () => {+ mockGetCurrentOrganisation.mockResolvedValue({ id: "org-1" });+ mockGetCurrentProjectForOrganisation.mockResolvedValue({ id: "proj-1" });+ mockFindFirst.mockResolvedValue(null);+ mockGetDBConfigByUser.mockResolvedValue(dbConfig);+ (mockedCreateAdapter as jest.Mock)+ .mockReturnValueOnce(undefined)+ .mockReturnValueOnce(undefined);++ await expect(getTelemetryAdapter()).rejects.toThrow(+ /built-in ClickHouse factory missing/+ );+ });});describe("getTelemetryAdapterForDbConfig", () => {@@ -513,6 +813,94 @@ describe("getTelemetryAdapterForDbConfig", () => {});expect(mockGetDBConfigById).not.toHaveBeenCalled();});++ it("throws the typed no-source error when the DatabaseConfig's environment has no routed connector", async () => {+ mockGetDBConfigByIdInternal.mockResolvedValue({+ ...dbConfig,+ environment: "production",+ });+ mockBindingFindUnique.mockResolvedValue(null);++ await expect(+ getTelemetryAdapterForDbConfig("db-1", "traces")+ ).rejects.toThrow(/No connector is configured/);+ });++ it("resolves the isBuiltIn descriptor unchanged (no dbConfigId re-attachment) when the binding routes to the built-in store", async () => {+ mockGetDBConfigByIdInternal.mockResolvedValue({+ ...dbConfig,+ environment: "production",+ });+ mockBindingFindUnique.mockResolvedValue({ databaseConfig: dbConfig });++ const result = await getTelemetryAdapterForDbConfig("db-1", "traces");++ expect(result.isBuiltIn).toBe(true);+ expect(result.descriptor).toMatchObject({ id: "builtin:db-1", dbConfigId: "db-1" });+ });++ it("throws ADAPTER_UNAVAILABLE when the routed external source type has no registered factory", async () => {+ mockGetDBConfigByIdInternal.mockResolvedValue({+ ...dbConfig,+ environment: "production",+ });+ mockBindingFindUnique.mockResolvedValue({+ source: srcRow({ id: "mystery-1", type: "unknownvendor", signals: "traces" }),+ });++ await expect(+ getTelemetryAdapterForDbConfig("db-1", "traces")+ ).rejects.toThrow(/No adapter is registered/);+ });++ it("falls back to a fresh built-in ClickHouse adapter when the routed built-in adapter transiently fails to construct", async () => {+ mockGetDBConfigByIdInternal.mockResolvedValue({+ ...dbConfig,+ environment: "production",+ });+ mockBindingFindUnique.mockResolvedValue({ databaseConfig: dbConfig });+ (mockedCreateAdapter as jest.Mock).mockReturnValueOnce(undefined);++ const result = await getTelemetryAdapterForDbConfig("db-1", "traces");++ expect(result.isBuiltIn).toBe(true);+ expect(result.descriptor).toMatchObject({ id: "builtin:db-1" });+ expect(mockedCreateAdapter).toHaveBeenCalledTimes(2);+ });++ it("throws when even the built-in ClickHouse fallback factory is unavailable", async () => {+ mockGetDBConfigByIdInternal.mockResolvedValue({+ ...dbConfig,+ environment: "production",+ });+ mockBindingFindUnique.mockResolvedValue({ databaseConfig: dbConfig });+ (mockedCreateAdapter as jest.Mock)+ .mockReturnValueOnce(undefined)+ .mockReturnValueOnce(undefined);++ await expect(+ getTelemetryAdapterForDbConfig("db-1", "traces")+ ).rejects.toThrow(/built-in ClickHouse factory missing/);+ });++ it("re-resolves the built-in descriptor by id when the DatabaseConfig row itself could not be loaded", async () => {+ // `getDBConfigByIdInternal` (used for the outer DatabaseConfig lookup)+ // fails, but the signal still routes to a real built-in via a+ // different lookup (`getDBConfigById`) inside resolveBuiltInDescriptor.+ mockGetDBConfigByIdInternal.mockResolvedValue(null);+ mockGetDBConfigById.mockResolvedValue({+ id: "db-1",+ name: "Real CH",+ projectId: "proj-1",+ });+ (mockedCreateAdapter as jest.Mock).mockReturnValueOnce(undefined);++ const result = await getTelemetryAdapterForDbConfig("db-1", "traces");++ expect(result.isBuiltIn).toBe(true);+ expect(result.descriptor).toMatchObject({ id: "builtin:db-1", name: "Real CH" });+ expect(mockGetDBConfigById).toHaveBeenCalledWith({ id: "db-1" });+ });});describe("isSignalServedByBuiltInClickHouse", () => {@@ -577,6 +965,10 @@ describe("isNativeSqlChatAvailable", () => {updatedAt: new Date(),createdByUserId: null,});+ // A real, reachable built-in ClickHouse must be routed for the+ // "builtin" via-path check to even consider the legacy default-source+ // fallback below.+ mockGetDBConfigByUser.mockResolvedValue(dbConfig);const res = await isNativeSqlChatAvailable();expect(res).toMatchObject({diff --git a/src/client/src/__tests__/lib/user.test.ts b/src/client/src/__tests__/lib/user.test.tsindex 556398de..1f16ba51 100644--- a/src/client/src/__tests__/lib/user.test.ts+++ b/src/client/src/__tests__/lib/user.test.ts@@ -106,6 +106,13 @@ describe('getUserById', () => {const result = await getUserById({ id: 'u1' });expect((result as any).password).toBeUndefined();});++ it('includes password when selectPassword=true', async () => {+ const user = { id: 'u1', email: '[email protected]', password: 'hashed' };+ (prisma.user.findUnique as jest.Mock).mockResolvedValue(user);+ const result = await getUserById({ id: 'u1', selectPassword: true });+ expect((result as any).password).toBe('hashed');+ });});describe('createNewUser', () => {@@ -150,6 +157,27 @@ describe('createNewUser', () => {).rejects.toThrow('Email contains invalid characters');expect(prisma.user.create).not.toHaveBeenCalled();});++ it('rejects weak registration passwords before checking for an existing user', async () => {+ await expect(+ createNewUser({ email: '[email protected]', password: 'weak' })+ ).rejects.toThrow('Password must be at least 8 characters long');+ expect(asaw).not.toHaveBeenCalled();+ expect(prisma.user.create).not.toHaveBeenCalled();+ });++ it('includes the password when options.selectPassword is true', async () => {+ (asaw as jest.Mock).mockResolvedValue([null, null]);+ const createdUser = { id: 'u1', email: '[email protected]', password: 'hashed' };+ (prisma.user.create as jest.Mock).mockResolvedValue(createdUser);++ const result = await createNewUser(+ { email: '[email protected]', password: 'Pass1234' },+ { selectPassword: true }+ );++ expect((result as any).password).toBe('hashed');+ });});describe('updateUser', () => {@@ -209,6 +237,40 @@ describe('updateUserProfile', () => {updateUserProfile({ currentPassword: 'wrong', newPassword: 'Newpass1' })).rejects.toThrow('Wrong current password!');});++ it('throws when a new password is provided without the current password', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'u1', email: '[email protected]', password: 'hashed' });++ await expect(updateUserProfile({ newPassword: 'Newpass1' })).rejects.toThrow(+ 'Provide current password to update it to new one!'+ );+ });++ it('throws when the new password is too weak', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'u1', email: '[email protected]', password: 'hashed' });++ await expect(+ updateUserProfile({ currentPassword: 'old', newPassword: 'weak' })+ ).rejects.toThrow('Password must be at least 8 characters long');+ });++ it('compares against an empty stored password when the current user has none on record', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'u1', email: '[email protected]', password: undefined });+ (compare as jest.Mock).mockResolvedValue(false);++ await expect(+ updateUserProfile({ currentPassword: 'old', newPassword: 'Newpass1' })+ ).rejects.toThrow('Wrong current password!');+ expect(compare).toHaveBeenCalledWith('old', '');+ });++ it('throws when the new profile name is invalid', async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'u1', email: '[email protected]', password: 'hashed' });++ await expect(+ updateUserProfile({ name: '<script>alert(1)</script>' })+ ).rejects.toThrow('Name must not contain HTML tags');+ });});describe('doesPasswordMatches', () => {diff --git a/src/client/src/__tests__/middleware/check-auth.test.ts b/src/client/src/__tests__/middleware/check-auth.test.tsindex 2b142d3d..dbfba20b 100644--- a/src/client/src/__tests__/middleware/check-auth.test.ts+++ b/src/client/src/__tests__/middleware/check-auth.test.ts@@ -6,6 +6,10 @@ jest.mock('next/server', () => ({redirect: jest.fn((url) => ({ type: 'redirect', url: url.toString() })),json: jest.fn((body, init) => ({ type: 'json', body, init })),},+ NextRequest: jest.fn(function (this: any, base: any, init: any) {+ this.__base = base;+ this.headers = init?.headers;+ }),}));jest.mock('next-auth/middleware', () => ({@@ -35,7 +39,7 @@ const makeRequest = (const makeFetchEvent = () => ({} as any);describe('checkAuth', () => {- const nextHandler = jest.fn(() => ({ type: 'next' }));+ const nextHandler = jest.fn((..._args: unknown[]) => ({ type: 'next' }));let middleware: any;beforeEach(() => {@@ -69,6 +73,77 @@ describe('checkAuth', () => {expect(nextHandler).not.toHaveBeenCalled();});+ describe('Bearer token / API key auth', () => {+ afterEach(() => {+ delete (global as any).fetch;+ });++ it('rejects a Bearer token on a route that does not allow tokens', async () => {+ const req = makeRequest('GET', '/dashboard', '', { Authorization: 'Bearer abc123' });+ await middleware(req as any, makeFetchEvent());+ expect(NextResponse.json).toHaveBeenCalledWith(+ { error: 'Forbidden' },+ { status: 403 }+ );+ expect(nextHandler).not.toHaveBeenCalled();+ });++ it('rejects an empty API key', async () => {+ const req = makeRequest('GET', '/api/vault/get-secrets', '', { Authorization: 'Bearer ' });+ await middleware(req as any, makeFetchEvent());+ expect(NextResponse.json).toHaveBeenCalledWith(+ { error: 'Invalid API key' },+ { status: 401 }+ );+ });++ it('rejects the API key when verify-key responds with a non-ok status', async () => {+ (global as any).fetch = jest.fn().mockResolvedValue({ ok: false });+ const req = makeRequest('GET', '/api/vault/get-secrets', '', { Authorization: 'Bearer key-1' });+ await middleware(req as any, makeFetchEvent());+ expect((global as any).fetch).toHaveBeenCalled();+ expect(NextResponse.json).toHaveBeenCalledWith(+ { error: 'Invalid API key' },+ { status: 401 }+ );+ });++ it('rejects the API key when verify-key reports it as invalid', async () => {+ (global as any).fetch = jest.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ valid: false }),+ });+ const req = makeRequest('GET', '/api/vault/get-secrets', '', { Authorization: 'Bearer key-1' });+ await middleware(req as any, makeFetchEvent());+ expect(NextResponse.json).toHaveBeenCalledWith(+ { error: 'Invalid API key' },+ { status: 401 }+ );+ });++ it('forwards the request with the resolved database config id when the key is valid', async () => {+ (global as any).fetch = jest.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ valid: true, databaseConfigId: 'db-config-1' }),+ });+ const req = makeRequest('GET', '/api/vault/get-secrets', '', { Authorization: 'Bearer key-1' });+ await middleware(req as any, makeFetchEvent());+ expect(nextHandler).toHaveBeenCalled();+ const forwardedRequest = nextHandler.mock.calls[0][0] as { headers: Headers };+ expect(forwardedRequest.headers.get('x-database-config-id')).toBe('db-config-1');+ });++ it('returns 401 when the verify-key request throws', async () => {+ (global as any).fetch = jest.fn().mockRejectedValue(new Error('network down'));+ const req = makeRequest('GET', '/api/vault/get-secrets', '', { Authorization: 'Bearer key-1' });+ await middleware(req as any, makeFetchEvent());+ expect(NextResponse.json).toHaveBeenCalledWith(+ { error: 'Invalid API key' },+ { status: 401 }+ );+ });+ });+describe('auth page (/login)', () => {it('redirects authenticated user to default route', async () => {(getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true });@@ -148,6 +223,82 @@ describe('checkAuth', () => {});});+ describe('rate limiting sensitive API prefixes', () => {+ it('uses the x-real-ip header when x-forwarded-for is absent', async () => {+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true });+ const req = makeRequest('GET', '/api/organisation', '', { 'x-real-ip': '10.0.0.5' });+ await middleware(req as any, makeFetchEvent());+ expect(NextResponse.next).toHaveBeenCalled();+ });++ it('falls back to "unknown" when no client ip headers are present', async () => {+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true });+ const req = makeRequest('GET', '/api/organisation');+ await middleware(req as any, makeFetchEvent());+ expect(NextResponse.next).toHaveBeenCalled();+ });++ it('sweeps expired rate-limit windows on the periodic cleanup pass', async () => {+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true });+ const headers = { 'x-forwarded-for': '192.0.2.55' };++ // Seed a window for this key using the real clock.+ const realNow = Date.now();+ await middleware(makeRequest('GET', '/api/organisation', '', headers) as any, makeFetchEvent());++ // Jump far enough forward that both this key's window AND the global+ // cleanup timer are due, forcing the forEach sweep to delete it.+ const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(realNow + 10 * 60_000);+ try {+ (NextResponse.next as jest.Mock).mockClear();+ await middleware(makeRequest('GET', '/api/organisation', '', headers) as any, makeFetchEvent());+ expect(NextResponse.next).toHaveBeenCalled();+ } finally {+ nowSpy.mockRestore();+ }+ });++ it('returns 429 once the request count in the current window exceeds the limit', async () => {+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true });+ const headers = { 'x-forwarded-for': '203.0.113.9' };+ for (let i = 0; i < 1200; i++) {+ const req = makeRequest('GET', '/api/organisation', '', headers);+ await middleware(req as any, makeFetchEvent());+ }+ (NextResponse.json as jest.Mock).mockClear();+ const finalReq = makeRequest('GET', '/api/organisation', '', headers);+ await middleware(finalReq as any, makeFetchEvent());+ expect(NextResponse.json).toHaveBeenCalledWith(+ { error: 'Too many requests' },+ { status: 429 }+ );+ });+ });++ describe('onboarding whitelist method lookups', () => {+ it('treats a method with no configured prefix whitelist as having none', async () => {+ (getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true });+ const req = makeRequest('HEAD', '/api/some-endpoint');+ await middleware(req as any, makeFetchEvent());+ expect(NextResponse.next).toHaveBeenCalled();+ });+ });++ describe('unauthenticated request to a non-whitelisted API route', () => {+ it('returns 401 Unauthorized without redirecting', async () => {+ (getToken as jest.Mock).mockResolvedValue(null);+ const req = makeRequest('GET', '/api/some-restricted-endpoint', '', {+ 'x-forwarded-for': '198.51.100.1',+ });+ await middleware(req as any, makeFetchEvent());+ expect(NextResponse.json).toHaveBeenCalledWith(+ { error: 'Unauthorized' },+ { status: 401 }+ );+ expect(NextResponse.redirect).not.toHaveBeenCalled();+ });+ });+describe('unauthenticated access to protected pages', () => {it('redirects to login with callbackUrl', async () => {(getToken as jest.Mock).mockResolvedValue(null);diff --git a/src/client/src/__tests__/utils/active-app.test.ts b/src/client/src/__tests__/utils/active-app.test.tsindex ce196930..9336bc13 100644--- a/src/client/src/__tests__/utils/active-app.test.ts+++ b/src/client/src/__tests__/utils/active-app.test.ts@@ -46,4 +46,26 @@ describe('getActiveApp', () => {it('returns null for onboarding', () => {expect(getActiveApp('/onboarding')).toBeNull();});++ it('returns the chat title for chat routes', () => {+ expect(getActiveApp('/chat')).toEqual({+ title: 'Otter',+ href: '/chat',+ });+ });++ it('returns null when the pathname matches no sidebar app', () => {+ expect(getActiveApp('/this-route-does-not-exist')).toBeNull();+ });++ it('falls back to a default Agents entry when the sidebar has no /agents link', () => {+ jest.isolateModules(() => {+ jest.doMock('@/constants/sidebar', () => ({ SIDEBAR_ITEMS: [] }));+ const { getActiveApp: getActiveAppWithoutAgentsLink } =+ require('@/utils/active-app');+ expect(+ getActiveAppWithoutAgentsLink('/coding-agents/users/[email protected]')+ ).toEqual({ title: 'Agents', href: '/agents' });+ });+ });});diff --git a/src/client/src/__tests__/utils/api.test.ts b/src/client/src/__tests__/utils/api.test.tsindex 56348fa2..794eafdb 100644--- a/src/client/src/__tests__/utils/api.test.ts+++ b/src/client/src/__tests__/utils/api.test.ts@@ -1,6 +1,7 @@import { getData, postData, deleteData } from '@/utils/api';import { useRootStore } from '@/store';import { OPENLIT_CONTEXT_HEADERS } from '@/constants/openlit-context';+import { __clearTelemetryRequestCache } from '@/utils/telemetry-request-cache';jest.mock('@/store', () => ({useRootStore: {@@ -134,6 +135,58 @@ describe('getData', () => {await getData({ url: '/api/test', method: 'PUT', data: { x: 1 } });expect(global.fetch).toHaveBeenCalledWith('/api/test', expect.objectContaining({ method: 'PUT' }));});++ it('throws using the object error fallback fields when the failed response is JSON', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(+ makeFetchResponse(false, { error: 'invalid input' }, 422)+ );+ await expect(getData({ url: '/api/test', method: 'GET' })).rejects.toThrow(+ 'invalid input'+ );+ });++ it('falls back to a generic status message when the JSON error body has no known fields', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(+ makeFetchResponse(false, { unrelated: true }, 503)+ );+ await expect(getData({ url: '/api/test', method: 'GET' })).rejects.toThrow(+ 'Request failed (503)'+ );+ });++ it('throws when a successful response body is empty', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(true, ''));+ await expect(getData({ url: '/api/test', method: 'GET' })).rejects.toThrow(+ /empty response/i+ );+ });++ it('includes the environment header and cache key when a current environment is set', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(true, {}));+ (useRootStore.getState as jest.Mock).mockReturnValue({+ organisation: {},+ project: { currentEnvironment: 'staging' },+ databaseConfig: {},+ });++ await getData({ url: '/api/test', method: 'GET' });++ const [, options] = (global.fetch as jest.Mock).mock.calls[0];+ expect(options.headers).toEqual({+ [OPENLIT_CONTEXT_HEADERS.environment]: 'staging',+ });+ });++ it('caches cacheable telemetry URLs and issues a request signal via the abort controller', async () => {+ __clearTelemetryRequestCache();+ (global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(true, { ok: true }));++ await getData({ url: '/api/metrics/summary', method: 'GET' });++ const [, options] = (global.fetch as jest.Mock).mock.calls[0];+ expect(options.signal).toBeInstanceOf(AbortSignal);+ __clearTelemetryRequestCache();+ });});describe('postData', () => {@@ -179,6 +232,49 @@ describe('postData', () => {(global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(false, 'Bad Request'));await expect(postData({ url: '/api/items', data: {} })).rejects.toThrow();});++ it('throws using the object error fallback fields when the failed response is JSON', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(+ makeFetchResponse(false, { err: 'duplicate key' }, 409)+ );+ await expect(postData({ url: '/api/items', data: {} })).rejects.toThrow(+ 'duplicate key'+ );+ });++ it('falls back to the error field when err is absent', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(+ makeFetchResponse(false, { error: 'validation failed' }, 400)+ );+ await expect(postData({ url: '/api/items', data: {} })).rejects.toThrow(+ 'validation failed'+ );+ });++ it('falls back to the message field when err and error are absent', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(+ makeFetchResponse(false, { message: 'unauthorized' }, 401)+ );+ await expect(postData({ url: '/api/items', data: {} })).rejects.toThrow(+ 'unauthorized'+ );+ });++ it('falls back to a generic status message when the JSON error body has no known fields', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(+ makeFetchResponse(false, { unrelated: true }, 500)+ );+ await expect(postData({ url: '/api/items', data: {} })).rejects.toThrow(+ 'Request failed (500)'+ );+ });++ it('throws when a successful response body is empty', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(true, ''));+ await expect(postData({ url: '/api/items', data: {} })).rejects.toThrow(+ /empty response/i+ );+ });});describe('deleteData', () => {@@ -223,4 +319,38 @@ describe('deleteData', () => {(global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(false, 'Not Found'));await expect(deleteData({ url: '/api/items/1' })).rejects.toThrow();});++ it('throws using the object error fallback fields when the failed response is JSON', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(+ makeFetchResponse(false, { message: 'cannot delete in-use item' }, 409)+ );+ await expect(deleteData({ url: '/api/items/1' })).rejects.toThrow(+ 'cannot delete in-use item'+ );+ });++ it('falls back to the error field when err is absent', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(+ makeFetchResponse(false, { error: 'referenced elsewhere' }, 409)+ );+ await expect(deleteData({ url: '/api/items/1' })).rejects.toThrow(+ 'referenced elsewhere'+ );+ });++ it('falls back to a generic status message when the JSON error body has no known fields', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(+ makeFetchResponse(false, { unrelated: true }, 500)+ );+ await expect(deleteData({ url: '/api/items/1' })).rejects.toThrow(+ 'Request failed (500)'+ );+ });++ it('throws when a successful response body is empty', async () => {+ (global.fetch as jest.Mock).mockResolvedValue(makeFetchResponse(true, ''));+ await expect(deleteData({ url: '/api/items/1' })).rejects.toThrow(+ /empty response/i+ );+ });});diff --git a/src/client/src/__tests__/utils/date.test.ts b/src/client/src/__tests__/utils/date.test.tsindex e08d12b3..bf73506f 100644--- a/src/client/src/__tests__/utils/date.test.ts+++ b/src/client/src/__tests__/utils/date.test.ts@@ -95,4 +95,40 @@ describe('formatDatePartsValue', () => {})).toBeNull();});++ it('returns null for non-plain-object values', () => {+ expect(formatDatePartsValue(null)).toBeNull();+ expect(formatDatePartsValue(undefined)).toBeNull();+ expect(formatDatePartsValue('2024-01-01')).toBeNull();+ expect(formatDatePartsValue([2024, 1, 1])).toBeNull();+ });++ it('returns null when required year, month, or day parts are missing', () => {+ expect(formatDatePartsValue({ year: 2026, month: 8 })).toBeNull();+ });++ it('returns null when a required part is falsy after normalization', () => {+ expect(formatDatePartsValue({ year: 2026, month: 0, day: 17 })).toBeNull();+ });++ it('accepts numeric parts provided as strings', () => {+ const formatted = formatDatePartsValue({ year: '2026', month: '8', day: '17' });++ expect(formatted).toBe(new Date(2026, 7, 17, 0, 0, 0).toLocaleString());+ });++ it('ignores empty-string entries and defaults missing hour and minute parts to zero', () => {+ const formatted = formatDatePartsValue({+ year: 2026,+ month: 8,+ day: 17,+ timezone: '',+ });++ expect(formatted).toBe(new Date(2026, 7, 17, 0, 0, 0).toLocaleString());+ });++ it('returns null when the resulting date is out of range', () => {+ expect(formatDatePartsValue({ year: 300000, month: 1, day: 1 })).toBeNull();+ });});diff --git a/src/client/src/__tests__/utils/hooks/useSidebarPreferences.test.ts b/src/client/src/__tests__/utils/hooks/useSidebarPreferences.test.tsnew file mode 100644index 00000000..fdd7638f--- /dev/null+++ b/src/client/src/__tests__/utils/hooks/useSidebarPreferences.test.ts@@ -0,0 +1,140 @@+import { renderHook, act } from "@testing-library/react";+import { useSidebarPreferences } from "@/utils/hooks/useSidebarPreferences";++const STORAGE_PREFIX = "openlit:my-apps-hidden:";++describe("useSidebarPreferences", () => {+ beforeEach(() => {+ window.localStorage.clear();+ });++ it("starts unloaded with no hidden apps when userId is missing", () => {+ const { result } = renderHook(() => useSidebarPreferences());+ expect(result.current.hidden).toEqual([]);+ expect(result.current.loaded).toBe(false);+ });++ it("loads persisted hidden links for a user", () => {+ window.localStorage.setItem(+ `${STORAGE_PREFIX}user-1`,+ JSON.stringify({ hidden: ["/apps/a", "/apps/b"] })+ );+ const { result } = renderHook(() => useSidebarPreferences("user-1"));+ expect(result.current.loaded).toBe(true);+ expect(result.current.hidden).toEqual(["/apps/a", "/apps/b"]);+ });++ it("treats missing storage as an empty hidden list", () => {+ const { result } = renderHook(() => useSidebarPreferences("user-2"));+ expect(result.current.loaded).toBe(true);+ expect(result.current.hidden).toEqual([]);+ });++ it("ignores corrupted JSON and falls back to an empty list", () => {+ window.localStorage.setItem(`${STORAGE_PREFIX}user-3`, "not-json{{{");+ const { result } = renderHook(() => useSidebarPreferences("user-3"));+ expect(result.current.hidden).toEqual([]);+ });++ it("filters out non-string entries in the persisted hidden array", () => {+ window.localStorage.setItem(+ `${STORAGE_PREFIX}user-4`,+ JSON.stringify({ hidden: ["/apps/a", 42, null, "/apps/b"] })+ );+ const { result } = renderHook(() => useSidebarPreferences("user-4"));+ expect(result.current.hidden).toEqual(["/apps/a", "/apps/b"]);+ });++ it("falls back to an empty list when hidden is not an array", () => {+ window.localStorage.setItem(+ `${STORAGE_PREFIX}user-5`,+ JSON.stringify({ hidden: "not-an-array" })+ );+ const { result } = renderHook(() => useSidebarPreferences("user-5"));+ expect(result.current.hidden).toEqual([]);+ });++ it("hides a link and persists the update", () => {+ const { result } = renderHook(() => useSidebarPreferences("user-6"));+ act(() => {+ result.current.hide("/apps/a");+ });+ expect(result.current.hidden).toEqual(["/apps/a"]);+ expect(result.current.isHidden("/apps/a")).toBe(true);+ expect(+ JSON.parse(window.localStorage.getItem(`${STORAGE_PREFIX}user-6`) || "{}")+ ).toEqual({ hidden: ["/apps/a"] });+ });++ it("hiding an already-hidden link is a no-op", () => {+ const { result } = renderHook(() => useSidebarPreferences("user-7"));+ act(() => {+ result.current.hide("/apps/a");+ });+ act(() => {+ result.current.hide("/apps/a");+ });+ expect(result.current.hidden).toEqual(["/apps/a"]);+ });++ it("shows a previously hidden link", () => {+ const { result } = renderHook(() => useSidebarPreferences("user-8"));+ act(() => {+ result.current.hide("/apps/a");+ });+ act(() => {+ result.current.show("/apps/a");+ });+ expect(result.current.hidden).toEqual([]);+ expect(result.current.isHidden("/apps/a")).toBe(false);+ });++ it("showing a link that is not hidden does not persist a new write", () => {+ const { result } = renderHook(() => useSidebarPreferences("user-9"));+ act(() => {+ result.current.show("/apps/never-hidden");+ });+ expect(result.current.hidden).toEqual([]);+ });++ it("toggle hides a shown link and shows a hidden link", () => {+ const { result } = renderHook(() => useSidebarPreferences("user-10"));+ act(() => {+ result.current.toggle("/apps/a");+ });+ expect(result.current.hidden).toEqual(["/apps/a"]);++ act(() => {+ result.current.toggle("/apps/a");+ });+ expect(result.current.hidden).toEqual([]);+ });++ it("does not persist to storage when there is no userId", () => {+ const { result } = renderHook(() => useSidebarPreferences());+ act(() => {+ result.current.hide("/apps/a");+ });+ expect(result.current.hidden).toEqual(["/apps/a"]);+ expect(window.localStorage.getItem(`${STORAGE_PREFIX}undefined`)).toBeNull();+ });++ it("reloads preferences when the userId changes", () => {+ window.localStorage.setItem(+ `${STORAGE_PREFIX}user-11`,+ JSON.stringify({ hidden: ["/apps/a"] })+ );+ window.localStorage.setItem(+ `${STORAGE_PREFIX}user-12`,+ JSON.stringify({ hidden: ["/apps/b"] })+ );+ const { result, rerender } = renderHook(+ ({ userId }: { userId?: string }) => useSidebarPreferences(userId),+ { initialProps: { userId: "user-11" } }+ );+ expect(result.current.hidden).toEqual(["/apps/a"]);++ rerender({ userId: "user-12" });+ expect(result.current.hidden).toEqual(["/apps/b"]);+ });+});diff --git a/src/client/src/__tests__/utils/hooks/useSignalCapabilities.test.ts b/src/client/src/__tests__/utils/hooks/useSignalCapabilities.test.tsnew file mode 100644index 00000000..69662795--- /dev/null+++ b/src/client/src/__tests__/utils/hooks/useSignalCapabilities.test.ts@@ -0,0 +1,181 @@+import { renderHook, waitFor, act } from "@testing-library/react";+import {+ useSignalCapabilities,+ __clearSignalCapabilitiesCache,+ type SignalCapabilities,+} from "@/utils/hooks/useSignalCapabilities";++const sampleCapabilities: SignalCapabilities = {+ traces: {+ sourceType: "clickhouse",+ sourceName: "default",+ isBuiltIn: true,+ capabilities: { traceTree: true },+ },+ logs: null,+ metrics: null,+};++function mockFetchOnce(body: unknown, ok = true) {+ (global.fetch as jest.Mock).mockResolvedValueOnce({+ ok,+ json: async () => body,+ });+}++describe("useSignalCapabilities", () => {+ beforeEach(() => {+ __clearSignalCapabilitiesCache();+ global.fetch = jest.fn();+ });++ it("starts in a loading state with null capabilities when uncached", async () => {+ mockFetchOnce({ signalCapabilities: sampleCapabilities });+ const { result } = renderHook(() => useSignalCapabilities());+ expect(result.current.loading).toBe(true);+ expect(result.current.capabilities).toBeNull();++ await waitFor(() => expect(result.current.loading).toBe(false));+ });++ it("resolves capabilities from a successful fetch", async () => {+ mockFetchOnce({ signalCapabilities: sampleCapabilities });+ const { result } = renderHook(() => useSignalCapabilities());++ await waitFor(() => expect(result.current.loading).toBe(false));++ expect(result.current.capabilities).toEqual(sampleCapabilities);+ expect(global.fetch).toHaveBeenCalledWith("/api/telemetry-source");+ });++ it("appends the environment query param when provided", async () => {+ mockFetchOnce({ signalCapabilities: sampleCapabilities });+ const { result } = renderHook(() => useSignalCapabilities("prod"));++ await waitFor(() => expect(result.current.loading).toBe(false));++ expect(global.fetch).toHaveBeenCalledWith(+ "/api/telemetry-source?environment=prod"+ );+ expect(result.current.capabilities).toEqual(sampleCapabilities);+ });++ it("resolves to null capabilities when the response is not ok", async () => {+ mockFetchOnce({ signalCapabilities: sampleCapabilities }, false);+ const { result } = renderHook(() => useSignalCapabilities());++ await waitFor(() => expect(result.current.loading).toBe(false));++ expect(result.current.capabilities).toBeNull();+ });++ it("resolves to null when the fetch throws", async () => {+ (global.fetch as jest.Mock).mockRejectedValueOnce(new Error("network down"));+ const { result } = renderHook(() => useSignalCapabilities());++ await waitFor(() => expect(result.current.loading).toBe(false));++ expect(result.current.capabilities).toBeNull();+ });++ it("falls back to null when the body has no signalCapabilities field", async () => {+ mockFetchOnce({});+ const { result } = renderHook(() => useSignalCapabilities());++ await waitFor(() => expect(result.current.loading).toBe(false));++ expect(result.current.capabilities).toBeNull();+ });++ it("falls back to null when the response body itself is nullish", async () => {+ mockFetchOnce(null);+ const { result } = renderHook(() => useSignalCapabilities());++ await waitFor(() => expect(result.current.loading).toBe(false));++ expect(result.current.capabilities).toBeNull();+ });++ it("serves a second mount from the module cache without a new fetch", async () => {+ mockFetchOnce({ signalCapabilities: sampleCapabilities });+ const first = renderHook(() => useSignalCapabilities());+ await waitFor(() => expect(first.result.current.loading).toBe(false));+ expect(global.fetch).toHaveBeenCalledTimes(1);++ const second = renderHook(() => useSignalCapabilities());+ expect(second.result.current.loading).toBe(false);+ expect(second.result.current.capabilities).toEqual(sampleCapabilities);+ await waitFor(() => expect(global.fetch).toHaveBeenCalledTimes(1));+ });++ it("dedupes concurrent in-flight requests for the same environment", async () => {+ let resolveFetch: (value: unknown) => void = () => {};+ (global.fetch as jest.Mock).mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveFetch = resolve;+ })+ );++ const a = renderHook(() => useSignalCapabilities("dev"));+ const b = renderHook(() => useSignalCapabilities("dev"));++ expect(global.fetch).toHaveBeenCalledTimes(1);++ await act(async () => {+ resolveFetch({+ ok: true,+ json: async () => ({ signalCapabilities: sampleCapabilities }),+ });+ await Promise.resolve();+ await Promise.resolve();+ });++ await waitFor(() => expect(a.result.current.loading).toBe(false));+ await waitFor(() => expect(b.result.current.loading).toBe(false));+ expect(a.result.current.capabilities).toEqual(sampleCapabilities);+ expect(b.result.current.capabilities).toEqual(sampleCapabilities);+ });++ it("re-fetches when the environment argument changes", async () => {+ mockFetchOnce({ signalCapabilities: sampleCapabilities });+ const { result, rerender } = renderHook(+ ({ environment }: { environment?: string }) =>+ useSignalCapabilities(environment),+ { initialProps: { environment: undefined as string | undefined } }+ );+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(global.fetch).toHaveBeenCalledTimes(1);++ mockFetchOnce({ signalCapabilities: sampleCapabilities });+ rerender({ environment: "staging" });+ await waitFor(() => expect(global.fetch).toHaveBeenCalledTimes(2));+ expect(global.fetch).toHaveBeenLastCalledWith(+ "/api/telemetry-source?environment=staging"+ );+ });++ it("does not update state after unmount once the fetch resolves", async () => {+ let resolveFetch: (value: unknown) => void = () => {};+ (global.fetch as jest.Mock).mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveFetch = resolve;+ })+ );++ const { unmount } = renderHook(() => useSignalCapabilities("unmount-env"));+ unmount();++ await act(async () => {+ resolveFetch({+ ok: true,+ json: async () => ({ signalCapabilities: sampleCapabilities }),+ });+ await Promise.resolve();+ await Promise.resolve();+ });+ // No assertion beyond "did not throw" — the effect's cleanup flips+ // `active` to false so the late resolution is a no-op.+ });+});diff --git a/src/client/src/__tests__/utils/telemetry-request-cache.test.ts b/src/client/src/__tests__/utils/telemetry-request-cache.test.tsindex 710f867a..e171f494 100644--- a/src/client/src/__tests__/utils/telemetry-request-cache.test.ts+++ b/src/client/src/__tests__/utils/telemetry-request-cache.test.ts@@ -17,6 +17,85 @@ describe("telemetry-request-cache", () => {expect(isCacheableTelemetryUrl("/api/agents/foo")).toBe(false);});+ it("resolves absolute URLs against their pathname", () => {+ expect(+ isCacheableTelemetryUrl("https://app.example.com/api/metrics/summary")+ ).toBe(true);+ expect(+ isCacheableTelemetryUrl("https://app.example.com/api/agents/foo")+ ).toBe(false);+ });++ it("treats an unparsable absolute URL as not cacheable", () => {+ expect(isCacheableTelemetryUrl("http://")).toBe(false);+ });++ it("normalizes a CUSTOM range's start/end to ISO strings without quantizing", () => {+ const normalized = normalizeTelemetryCacheBody(+ JSON.stringify({+ timeLimit: {+ type: "CUSTOM",+ start: "2026-07-10T12:00:10.123Z",+ end: new Date("2026-07-11T12:00:25.456Z"),+ },+ })+ );+ expect(JSON.parse(normalized)).toEqual({+ timeLimit: {+ type: "CUSTOM",+ start: "2026-07-10T12:00:10.123Z",+ end: "2026-07-11T12:00:25.456Z",+ },+ });+ });++ it("leaves non-string/non-Date CUSTOM start/end values untouched", () => {+ const normalized = normalizeTelemetryCacheBody(+ JSON.stringify({+ timeLimit: { type: "CUSTOM", start: null, end: 12345 },+ })+ );+ expect(JSON.parse(normalized)).toEqual({+ timeLimit: { type: "CUSTOM", start: null, end: 12345 },+ });+ });++ it("leaves non-string/non-Date relative start/end values untouched", () => {+ const normalized = normalizeTelemetryCacheBody(+ JSON.stringify({ timeLimit: { type: "24HR", start: 123, end: null } })+ );+ expect(JSON.parse(normalized)).toEqual({+ timeLimit: { type: "24HR", start: 123, end: null },+ });+ });++ it("leaves an unparsable relative date string untouched", () => {+ const normalized = normalizeTelemetryCacheBody(+ JSON.stringify({+ timeLimit: { type: "24HR", start: "not-a-date", end: "2026-07-11T12:00:00.000Z" },+ })+ );+ expect(JSON.parse(normalized).timeLimit.start).toBe("not-a-date");+ });++ it("leaves the body untouched when timeLimit has no type", () => {+ const body = JSON.stringify({ timeLimit: { start: "a", end: "b" } });+ expect(normalizeTelemetryCacheBody(body)).toBe(body);+ });++ it("leaves the body untouched when there is no timeLimit field", () => {+ const body = JSON.stringify({ foo: "bar" });+ expect(normalizeTelemetryCacheBody(body)).toBe(body);+ });++ it("returns an empty string for an undefined body", () => {+ expect(normalizeTelemetryCacheBody(undefined)).toBe("");+ });++ it("returns the raw body unchanged when it is not valid JSON", () => {+ expect(normalizeTelemetryCacheBody("not-json{{")).toBe("not-json{{");+ });+it("quantizes relative timeLimit ends so remounts share a cache key", () => {const a = normalizeTelemetryCacheBody(JSON.stringify({@@ -68,4 +147,106 @@ describe("telemetry-request-cache", () => {expect(c).toEqual(ra);expect(loads).toBe(1);});++ it("bypasses the cache entirely for non-cacheable URLs", async () => {+ let loads = 0;+ const loader = async () => {+ loads += 1;+ return { ok: true };+ };+ await withTelemetryRequestCache("/api/agents/foo", "{}", loader);+ await withTelemetryRequestCache("/api/agents/foo", "{}", loader);+ expect(loads).toBe(2);+ expect(peekTelemetryRequestCache("/api/agents/foo", "{}")).toBeNull();+ });++ it("peek returns null for non-cacheable URLs and cache misses", () => {+ expect(peekTelemetryRequestCache("/api/agents/foo", "{}")).toBeNull();+ expect(+ peekTelemetryRequestCache("/api/telemetry/request", "{}")+ ).toBeNull();+ });++ it("re-runs the loader once a TTL-expired entry is re-requested", async () => {+ let loads = 0;+ const loader = async () => {+ loads += 1;+ return { ok: true, loads };+ };+ await withTelemetryRequestCache("/api/telemetry/request", "{}", loader, 1);+ await new Promise((resolve) => setTimeout(resolve, 5));+ const second = await withTelemetryRequestCache(+ "/api/telemetry/request",+ "{}",+ loader,+ 1+ );+ expect(loads).toBe(2);+ expect(second).toEqual({ ok: true, loads: 2 });+ });++ it("evicts the oldest entries once the store exceeds MAX_ENTRIES", async () => {+ for (let i = 0; i < 85; i += 1) {+ await withTelemetryRequestCache(+ "/api/telemetry/request",+ JSON.stringify({ i }),+ async () => ({ i })+ );+ }+ expect(+ peekTelemetryRequestCache("/api/telemetry/request", JSON.stringify({ i: 0 }))+ ).toBeNull();+ expect(+ peekTelemetryRequestCache(+ "/api/telemetry/request",+ JSON.stringify({ i: 84 })+ )+ ).toEqual({ i: 84 });+ });++ it("prunes expired entries before enforcing the MAX_ENTRIES cap", async () => {+ await withTelemetryRequestCache(+ "/api/telemetry/request",+ JSON.stringify({ tag: "expiring" }),+ async () => ({ tag: "expiring" }),+ 1+ );+ await new Promise((resolve) => setTimeout(resolve, 5));+ await withTelemetryRequestCache(+ "/api/telemetry/request",+ JSON.stringify({ tag: "fresh" }),+ async () => ({ tag: "fresh" })+ );+ expect(+ peekTelemetryRequestCache(+ "/api/telemetry/request",+ JSON.stringify({ tag: "expiring" })+ )+ ).toBeNull();+ expect(+ peekTelemetryRequestCache(+ "/api/telemetry/request",+ JSON.stringify({ tag: "fresh" })+ )+ ).toEqual({ tag: "fresh" });+ });++ it("propagates loader rejections without caching the failure", async () => {+ const loader = jest+ .fn()+ .mockRejectedValueOnce(new Error("boom"))+ .mockResolvedValueOnce({ ok: true });++ await expect(+ withTelemetryRequestCache("/api/telemetry/request", "{}", loader)+ ).rejects.toThrow("boom");+ expect(peekTelemetryRequestCache("/api/telemetry/request", "{}")).toBeNull();++ const result = await withTelemetryRequestCache(+ "/api/telemetry/request",+ "{}",+ loader+ );+ expect(result).toEqual({ ok: true });+ });});diff --git a/src/client/src/__tests__/utils/validation.test.ts b/src/client/src/__tests__/utils/validation.test.tsindex 9b6a015f..09355f18 100644--- a/src/client/src/__tests__/utils/validation.test.ts+++ b/src/client/src/__tests__/utils/validation.test.ts@@ -33,6 +33,39 @@ describe("validateEmail", () => {expect(validateEmail("[email protected]").valid).toBe(false);expect(validateEmail("[email protected]").valid).toBe(false);});++ it("rejects missing or non-string emails", () => {+ expect(validateEmail("")).toEqual({+ valid: false,+ error: "Email is required",+ });+ expect(validateEmail(undefined as unknown as string)).toEqual({+ valid: false,+ error: "Email is required",+ });+ });++ it("rejects emails that are too long", () => {+ const longEmail = `${"a".repeat(260)}@example.com`;++ expect(validateEmail(longEmail)).toEqual({+ valid: false,+ error: "Email is too long",+ });+ });++ it("rejects emails without exactly one @ sign", () => {+ expect(validateEmail("userexample.com").valid).toBe(false);+ expect(validateEmail("user@[email protected]").valid).toBe(false);+ });++ it("rejects local parts with disallowed characters", () => {+ expect(validateEmail("user,[email protected]").valid).toBe(false);+ });++ it("rejects domains with consecutive dots", () => {+ expect(validateEmail("[email protected]").valid).toBe(false);+ });});describe("validateDatabaseHost", () => {@@ -73,6 +106,41 @@ describe("validateDatabaseHost", () => {expect(validateDatabaseHost("[fc00::1]").valid).toBe(false);expect(validateDatabaseHost("host$name").valid).toBe(false);});++ it("rejects unique-local IPv6 addresses identified only by the fd prefix", () => {+ expect(validateDatabaseHost("[fd00::1]")).toEqual({+ valid: false,+ error: "Private, loopback, and link-local IP addresses are not allowed",+ });+ });++ it("allows an explicitly configured private IPv6 host, but not link-local", () => {+ expect(validateDatabaseHost("[fc00::1]", { allowPrivateNetwork: true }).valid).toBe(true);+ expect(validateDatabaseHost("[fd00::1]", { allowPrivateNetwork: true }).valid).toBe(true);+ expect(validateDatabaseHost("[fe80::1]", { allowPrivateNetwork: true }).valid).toBe(false);+ });++ it("rejects the unspecified IPv4 address", () => {+ expect(validateDatabaseHost("0.0.0.0")).toEqual({+ valid: false,+ error: "Private, loopback, and link-local IP addresses are not allowed",+ });+ });++ it("does not apply IPv4-only private-range checks to public, unbracketed IPv6 addresses", () => {+ expect(validateDatabaseHost("2001:4860:4860::88ff").valid).toBe(true);+ });++ it("rejects a missing or non-string host", () => {+ expect(validateDatabaseHost("")).toEqual({+ valid: false,+ error: "Host is required",+ });+ expect(validateDatabaseHost(null as unknown as string)).toEqual({+ valid: false,+ error: "Host is required",+ });+ });});describe("validateProfileName", () => {@@ -143,6 +211,10 @@ describe("sanitizeErrorMessage", () => {);});+ it("returns the fallback when an Error has an empty message", () => {+ expect(sanitizeErrorMessage(new Error(""))).toBe("An unexpected error occurred");+ });+it("keeps safe user-facing messages", () => {expect(sanitizeErrorMessage("Invalid input")).toBe("Invalid input");expect(diff --git a/src/client/src/lib/platform/telemetry/rollups.ts b/src/client/src/lib/platform/telemetry/rollups.tsindex ea97136f..41fef28e 100644--- a/src/client/src/lib/platform/telemetry/rollups.ts+++ b/src/client/src/lib/platform/telemetry/rollups.ts@@ -83,9 +83,9 @@ function inListSql(column: string, values: string[]): string {return `AND ${column} IN (${values.map((v) => `'${escape(v)}'`).join(", ")})`;}-function isFresh(updatedAt: unknown): boolean {- const t = new Date(String(updatedAt || 0)).getTime();- return Number.isFinite(t) && Date.now() - t <= ROLLUP_FRESHNESS_MS;+/** `updatedAtMs` is already a resolved epoch-ms timestamp (see the `newest` reducers below). */+function isFresh(updatedAtMs: number): boolean {+ return Number.isFinite(updatedAtMs) && Date.now() - updatedAtMs <= ROLLUP_FRESHNESS_MS;}/**