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
feat: memory connectors with Ask Otter, writes, and env scoping (#1490)
Aman Agarwale6993e43f5a7
diff --git a/src/client/public/images/connectors/claude.svg b/src/client/public/images/connectors/claude.svgnew file mode 100644index 00000000..a2ac8e86--- /dev/null+++ b/src/client/public/images/connectors/claude.svg@@ -0,0 +1 @@+<svg fill="#D97757" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Claude</title><path d="M17.3041 3.541h-3.6723l6.5766 16.918H24Zm-10.608 0L0 20.459h3.7442l1.3698-3.5527h7.0056l1.3698 3.5527h3.7443L10.5362 3.541Zm-.8167 10.1554 2.2721-5.8959 2.272 5.8959Z"/></svg>diff --git a/src/client/public/images/connectors/mem0.svg b/src/client/public/images/connectors/mem0.svgnew file mode 100644index 00000000..2425490a--- /dev/null+++ b/src/client/public/images/connectors/mem0.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" role="img" viewBox="0 0 100 100" fill="none"><title>Mem0</title><rect width="100" height="100" fill="#CBB2FF" rx="12"/><g fill="#09090B" clip-path="url(#mem0-a)"><path d="M50.004 41.547a8.446 8.446 0 0 0-8.45 8.449 8.446 8.446 0 0 0 8.45 8.449 8.447 8.447 0 0 0 8.449-8.45 8.446 8.446 0 0 0-8.45-8.448m.042-16.531a2.513 2.513 0 0 0 2.463-2.553A2.486 2.486 0 0 0 49.955 20a2.486 2.486 0 0 0-2.462 2.553 2.486 2.486 0 0 0 2.552 2.463m-.089 49.963a2.486 2.486 0 0 0-2.463 2.552 2.486 2.486 0 0 0 2.552 2.463 2.513 2.513 0 0 0 2.463-2.552 2.486 2.486 0 0 0-2.553-2.463M32.372 32.3a2.513 2.513 0 0 0-.065-3.547 2.487 2.487 0 0 0-3.548.065 2.487 2.487 0 0 0 .065 3.548 2.487 2.487 0 0 0 3.548-.065m35.262 35.394a2.487 2.487 0 0 0 .065 3.548 2.487 2.487 0 0 0 3.548-.065 2.513 2.513 0 0 0-.065-3.548 2.487 2.487 0 0 0-3.548.065m.065-35.329c.98.944 2.572.946 3.548-.065a2.487 2.487 0 0 0-.065-3.548 2.487 2.487 0 0 0-3.548.065 2.487 2.487 0 0 0 .065 3.548M32.307 67.63a2.487 2.487 0 0 0-3.548.065 2.487 2.487 0 0 0 .065 3.548c.98.944 2.572.946 3.548-.065a2.487 2.487 0 0 0-.065-3.548m45.046-20.136a2.487 2.487 0 0 0-2.364 2.647 2.514 2.514 0 0 0 2.646 2.364 2.487 2.487 0 0 0 2.364-2.646 2.484 2.484 0 0 0-2.646-2.362zM22.65 52.501a2.487 2.487 0 0 0 2.365-2.646 2.485 2.485 0 0 0-2.646-2.362 2.487 2.487 0 0 0-2.365 2.646 2.515 2.515 0 0 0 2.646 2.364zm23.463-16.915a4.37 4.37 0 0 0 6.053 1.152c1.125-.765 1.819-2.005 1.904-3.403.062-.908.261-2.196 1.268-2.89 1.03-.655 2.293-.335 3.154-.04 1.32.467 2.732.313 3.875-.425a4.32 4.32 0 0 0 1.894-2.743 4.32 4.32 0 0 0-.597-3.28l-.174-.26a4.37 4.37 0 0 0-6.053-1.152c-1.126.764-1.82 2.003-1.904 3.402-.063.908-.262 2.196-1.269 2.89-1.029.655-2.293.335-3.154.04-1.317-.467-2.731-.313-3.874.425a4.36 4.36 0 0 0-1.3 6.022l.175.262zm-9.602 40.709a4.37 4.37 0 0 0 6.053 1.152c1.126-.765 1.82-2.005 1.904-3.403.063-.908.262-2.197 1.269-2.89 1.029-.655 2.292-.335 3.154-.04 1.32.467 2.731.313 3.874-.425a4.32 4.32 0 0 0 1.895-2.743 4.32 4.32 0 0 0-.597-3.28l-.175-.26a4.37 4.37 0 0 0-6.053-1.152c-1.125.764-1.819 2.003-1.904 3.401-.062.909-.261 2.197-1.268 2.89-1.03.656-2.293.336-3.154.041-1.318-.468-2.732-.313-3.875.425a4.36 4.36 0 0 0-1.3 6.022l.175.262zM57.42 37.048q-.08.434-.076.872a4.37 4.37 0 0 0 3.548 4.217c1.338.252 2.705-.137 3.75-1.067.686-.6 1.735-1.372 2.939-1.15 1.19.261 1.86 1.38 2.261 2.199.604 1.261 1.714 2.15 3.045 2.434a4.33 4.33 0 0 0 3.28-.604 4.32 4.32 0 0 0 1.892-2.745l.062-.309q.082-.435.076-.872a4.37 4.37 0 0 0-3.548-4.217c-1.337-.253-2.702.137-3.749 1.067-.687.6-1.738 1.371-2.94 1.15-1.19-.262-1.86-1.38-2.26-2.2-.605-1.26-1.714-2.149-3.043-2.433a4.36 4.36 0 0 0-5.172 3.349l-.062.309zm-35.539 22.05q-.08.435-.076.873a4.37 4.37 0 0 0 3.548 4.216c1.338.253 2.704-.136 3.75-1.067.686-.6 1.735-1.37 2.938-1.15 1.19.262 1.862 1.38 2.262 2.2.604 1.261 1.714 2.15 3.045 2.433A4.33 4.33 0 0 0 40.627 66a4.32 4.32 0 0 0 1.892-2.744l.063-.31q.081-.433.076-.871a4.37 4.37 0 0 0-3.548-4.217c-1.337-.253-2.702.136-3.749 1.067-.686.6-1.738 1.371-2.94 1.15-1.19-.262-1.86-1.38-2.26-2.2-.605-1.261-1.714-2.149-3.043-2.433a4.36 4.36 0 0 0-5.172 3.349l-.062.308zm42.525-13.01a4.5 4.5 0 0 0-.671.563 4.37 4.37 0 0 0-.472 5.49c.767 1.125 2.009 1.816 3.404 1.897.909.06 2.197.26 2.893 1.264.657 1.027.34 2.29.045 3.154-.466 1.32-.31 2.731.431 3.874a4.33 4.33 0 0 0 2.745 1.89 4.33 4.33 0 0 0 3.28-.601l.261-.175q.365-.25.671-.563a4.37 4.37 0 0 0 .472-5.49c-.767-1.123-2.006-1.816-3.404-1.897-.909-.06-2.2-.26-2.893-1.264-.657-1.026-.34-2.29-.044-3.154.465-1.32.308-2.731-.432-3.872a4.36 4.36 0 0 0-6.024-1.288l-.262.174zM23.687 36.55a4.5 4.5 0 0 0-.671.564 4.37 4.37 0 0 0-.472 5.49c.767 1.125 2.009 1.816 3.405 1.897.908.06 2.196.26 2.892 1.264.658 1.026.34 2.29.045 3.154-.465 1.32-.309 2.731.432 3.874a4.32 4.32 0 0 0 2.744 1.89 4.33 4.33 0 0 0 3.28-.601l.261-.175q.365-.25.672-.563a4.37 4.37 0 0 0 .472-5.49c-.768-1.123-2.007-1.816-3.405-1.897-.908-.06-2.2-.26-2.892-1.264-.658-1.027-.34-2.29-.045-3.154.465-1.32.308-2.731-.432-3.872a4.36 4.36 0 0 0-6.024-1.289l-.262.175zm39.268 20.868a4.4 4.4 0 0 0-.873-.076 4.37 4.37 0 0 0-4.217 3.548c-.252 1.338.137 2.705 1.067 3.75.6.686 1.372 1.735 1.15 2.939-.261 1.19-1.38 1.86-2.199 2.261-1.261.604-2.15 1.714-2.433 3.045a4.33 4.33 0 0 0 .603 3.28 4.32 4.32 0 0 0 2.745 1.892l.309.062q.435.082.872.076a4.37 4.37 0 0 0 4.217-3.547c.253-1.338-.136-2.703-1.067-3.75-.6-.686-1.371-1.738-1.15-2.94.262-1.19 1.38-1.86 2.2-2.26 1.26-.605 2.149-1.714 2.433-3.043a4.36 4.36 0 0 0-3.349-5.172l-.308-.062zM40.9 21.88a4.4 4.4 0 0 0-.872-.077 4.37 4.37 0 0 0-4.217 3.548c-.253 1.338.136 2.704 1.067 3.75.6.686 1.371 1.735 1.15 2.939-.262 1.19-1.38 1.86-2.2 2.261-1.26.604-2.149 1.714-2.433 3.045a4.33 4.33 0 0 0 .604 3.28 4.32 4.32 0 0 0 2.745 1.892l.308.062q.435.081.873.076a4.37 4.37 0 0 0 4.216-3.548c.253-1.337-.136-2.702-1.067-3.749-.6-.687-1.37-1.738-1.15-2.94.262-1.19 1.38-1.86 2.2-2.26 1.261-.605 2.15-1.714 2.433-3.043a4.36 4.36 0 0 0-3.348-5.172l-.31-.062z"/></g><defs><clipPath id="mem0-a"><path fill="#fff" d="M20 20h60v59.998H20z"/></clipPath></defs></svg>diff --git a/src/client/public/images/connectors/zep.svg b/src/client/public/images/connectors/zep.svgnew file mode 100644index 00000000..4426d9b9--- /dev/null+++ b/src/client/public/images/connectors/zep.svg@@ -0,0 +1 @@+<svg fill="#4226AA" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Zep</title><g transform="translate(1.15 1.05) scale(0.0935)"><path fill-rule="evenodd" d="m231.34,108.7l-1.48-1.55h-10.26l3.59-75.86-14.8-.45-2.77,49.31c-59.6-3.24-119.33-3.24-178.92-.02l-1.73-64.96-14.8.45,2.5,91.53H2.16l-1.41,1.47c-1.55,16.23-.66,32.68,2.26,48.89h10.83l.18,1.27c.67,19.34,16.1,34.68,35.9,34.68s44.86-.92,66.12-.92,46.56.92,65.95.92,35.19-15.29,35.9-34.61l.16-1.34h11.02c2.91-16.19,3.81-32.61,2.26-48.81Zm-158.23,58.01c-17.27,0-30.25-13.78-30.25-29.78s12.99-29.78,30.25-29.78,29.62,13.94,29.62,29.94-12.35,29.62-29.62,29.62Zm86.51,0c-17.27,0-30.25-13.78-30.25-29.78s12.99-29.78,30.25-29.78,29.62,13.94,29.62,29.94-12.35,29.62-29.62,29.62Z"/><polygon points="111.77 22.4 93.39 49.97 93.52 50.48 185.88 38.51 190.95 27.68 114.32 36.55 117.7 31.48 117.7 31.47 138.38 .49 138.25 0 47.67 11.6 42.85 22.27 118.34 12.61 111.77 22.4"/><path d="m72.97,121.47c-8.67,0-15.73,6.93-15.73,15.46s7.06,15.46,15.73,15.46,15.37-6.75,15.37-15.37-6.75-15.55-15.37-15.55Z"/><path d="m159.48,121.47c-8.67,0-15.73,6.93-15.73,15.46s7.06,15.46,15.73,15.46,15.37-6.75,15.37-15.37-6.75-15.55-15.37-15.55Z"/></g></svg>diff --git a/src/client/src/__tests__/app/api/memory/[id]/feedback/route.test.ts b/src/client/src/__tests__/app/api/memory/[id]/feedback/route.test.tsnew file mode 100644index 00000000..65175498--- /dev/null+++ b/src/client/src/__tests__/app/api/memory/[id]/feedback/route.test.ts@@ -0,0 +1,112 @@+jest.mock("@/lib/session", () => ({+ getCurrentUser: jest.fn(),+}));+jest.mock("@/lib/platform/connectors/memory/read", () => ({+ submitProjectMemoryFeedback: jest.fn(),+}));+jest.mock("@/utils/asaw", () =>+ jest.fn(async (promise: Promise<unknown>) => {+ try {+ return [null, await promise];+ } catch (error) {+ return [error, null];+ }+ })+);++import { POST } from "@/app/api/memory/[id]/feedback/route";+import { getCurrentUser } from "@/lib/session";+import { submitProjectMemoryFeedback } from "@/lib/platform/connectors/memory/read";+import {+ MEMORY_FEEDBACK_INVALID,+ MEMORY_INVALID_FILTER,+ MEMORY_INVALID_JSON,+} from "@/constants/messages/en";++(globalThis as unknown as { Response: { json: unknown } }).Response = {+ json: (body: unknown, init?: ResponseInit) => ({+ status: init?.status ?? 200,+ json: async () => body,+ }),+};++function makeRequest(body: unknown, query = "") {+ const url = `http://localhost/api/memory/mem-1/feedback${query}`;+ return {+ url,+ nextUrl: { searchParams: new URL(url).searchParams },+ json: async () => {+ if (body === "__invalid__") throw new SyntaxError("Unexpected token");+ return body;+ },+ } as any;+}++describe("POST /api/memory/[id]/feedback", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "user-1" });+ });++ it("requires authentication", async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue(null);+ const response = await POST(makeRequest({ rating: "positive" }), {+ params: { id: "mem-1" },+ });+ expect(response.status).toBe(401);+ expect(submitProjectMemoryFeedback).not.toHaveBeenCalled();+ });++ it("rejects malformed JSON", async () => {+ const response = await POST(makeRequest("__invalid__"), {+ params: { id: "mem-1" },+ });+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toBe(MEMORY_INVALID_JSON);+ expect(submitProjectMemoryFeedback).not.toHaveBeenCalled();+ });++ it("rejects an invalid rating", async () => {+ const response = await POST(makeRequest({ rating: "meh" }), {+ params: { id: "mem-1" },+ });+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toBe(MEMORY_FEEDBACK_INVALID);+ expect(submitProjectMemoryFeedback).not.toHaveBeenCalled();+ });++ it("rejects a control-character id", async () => {+ const response = await POST(makeRequest({ rating: "positive" }), {+ params: { id: "mem\u0000-1" },+ });+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toBe(MEMORY_INVALID_FILTER);+ expect(submitProjectMemoryFeedback).not.toHaveBeenCalled();+ });++ it("submits vendor-neutral feedback", async () => {+ (submitProjectMemoryFeedback as jest.Mock).mockResolvedValue({+ feedback: { rating: "very_negative", reason: "Wrong person" },+ memory: { id: "mem-1", feedback: { rating: "very_negative" } },+ connector: { id: "memory:abc", name: "Mem0" },+ capabilities: { feedback: true },+ });+ const response = await POST(+ makeRequest(+ { rating: "very_negative", reason: "Wrong person" },+ "?connectorId=memory:abc"+ ),+ { params: { id: "mem-1" } }+ );+ expect(response.status).toBe(200);+ const body = await response.json();+ expect(body.feedback.rating).toBe("very_negative");+ expect(JSON.stringify(body)).not.toContain("secretRef");+ expect(submitProjectMemoryFeedback).toHaveBeenCalledWith({+ id: "mem-1",+ connectorId: "memory:abc",+ rating: "very_negative",+ reason: "Wrong person",+ });+ });+});diff --git a/src/client/src/__tests__/app/api/memory/[id]/route.test.ts b/src/client/src/__tests__/app/api/memory/[id]/route.test.tsnew file mode 100644index 00000000..c7e47da9--- /dev/null+++ b/src/client/src/__tests__/app/api/memory/[id]/route.test.ts@@ -0,0 +1,184 @@+jest.mock("@/lib/session", () => ({+ getCurrentUser: jest.fn(),+}));+jest.mock("@/lib/platform/connectors/memory/read", () => ({+ getProjectMemory: jest.fn(),+}));+jest.mock("@/lib/platform/connectors/memory/write", () => ({+ updateProjectMemory: jest.fn(),+ deleteProjectMemory: jest.fn(),+ parseMemoryMetadata: (value: unknown) => value,+}));+jest.mock("@/utils/asaw", () =>+ jest.fn(async (promise: Promise<unknown>) => {+ try {+ return [null, await promise];+ } catch (error) {+ return [error, null];+ }+ })+);++import { DELETE, GET, PATCH } from "@/app/api/memory/[id]/route";+import { getCurrentUser } from "@/lib/session";+import { getProjectMemory } from "@/lib/platform/connectors/memory/read";+import {+ deleteProjectMemory,+ updateProjectMemory,+} from "@/lib/platform/connectors/memory/write";+import {+ MEMORY_DETAIL_NOT_FOUND,+ MEMORY_INVALID_FILTER,+ MEMORY_INVALID_JSON,+} from "@/constants/messages/en";++(globalThis as unknown as { Response: { json: unknown } }).Response = {+ json: (body: unknown, init?: ResponseInit) => ({+ status: init?.status ?? 200,+ json: async () => body,+ }),+};++function makeRequest(query = "") {+ const url = `http://localhost/api/memory/mem-1${query}`;+ return {+ url,+ nextUrl: { searchParams: new URL(url).searchParams },+ } as any;+}++function makeBodyRequest(body: unknown, query = "") {+ const url = `http://localhost/api/memory/mem-1${query}`;+ return {+ url,+ nextUrl: { searchParams: new URL(url).searchParams },+ json: async () => {+ if (body === "__invalid__") throw new SyntaxError("Unexpected token");+ return body;+ },+ } as any;+}++describe("GET /api/memory/[id]", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "user-1" });+ });++ it("requires authentication", async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue(null);+ const response = await GET(makeRequest(), { params: { id: "mem-1" } });+ expect(response.status).toBe(401);+ expect(getProjectMemory).not.toHaveBeenCalled();+ });++ it("rejects a control-character id", async () => {+ const response = await GET(makeRequest(), { params: { id: "mem\u0000-1" } });+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toBe(MEMORY_INVALID_FILTER);+ expect(getProjectMemory).not.toHaveBeenCalled();+ });++ it("returns the memory without secretRef", async () => {+ (getProjectMemory as jest.Mock).mockResolvedValue({+ connector: { id: "memory:abc", name: "Mem0", hasSecret: true },+ capabilities: { get: true },+ memory: { id: "mem-1", content: "hello", kind: "profile", userId: "alex" },+ });+ const response = await GET(makeRequest("?connectorId=memory:abc"), {+ params: { id: "mem-1" },+ });+ expect(response.status).toBe(200);+ const body = await response.json();+ expect(body.memory.id).toBe("mem-1");+ expect(JSON.stringify(body)).not.toContain("secretRef");+ expect(getProjectMemory).toHaveBeenCalledWith(+ expect.objectContaining({ id: "mem-1", connectorId: "memory:abc" })+ );+ });++ it("returns 404 when the memory is missing", async () => {+ (getProjectMemory as jest.Mock).mockRejectedValue(new Error(MEMORY_DETAIL_NOT_FOUND));+ const response = await GET(makeRequest(), { params: { id: "mem-1" } });+ expect(response.status).toBe(404);+ });+});++describe("PATCH /api/memory/[id]", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "user-1" });+ });++ it("requires authentication", async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue(null);+ const response = await PATCH(makeBodyRequest({ content: "updated" }), {+ params: { id: "mem-1" },+ });+ expect(response.status).toBe(401);+ expect(updateProjectMemory).not.toHaveBeenCalled();+ });++ it("rejects malformed JSON", async () => {+ const response = await PATCH(makeBodyRequest("__invalid__"), {+ params: { id: "mem-1" },+ });+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toBe(MEMORY_INVALID_JSON);+ expect(updateProjectMemory).not.toHaveBeenCalled();+ });++ it("updates the memory", async () => {+ (updateProjectMemory as jest.Mock).mockResolvedValue({+ memory: { id: "mem-1", content: "updated", kind: "profile" },+ connector: { id: "memory:abc", name: "Mem0" },+ capabilities: { update: true },+ });+ const response = await PATCH(+ makeBodyRequest({ content: "updated" }, "?connectorId=memory:abc"),+ { params: { id: "mem-1" } }+ );+ expect(response.status).toBe(200);+ const body = await response.json();+ expect(body.memory.content).toBe("updated");+ expect(updateProjectMemory).toHaveBeenCalledWith({+ id: "mem-1",+ connectorId: "memory:abc",+ content: "updated",+ metadata: undefined,+ });+ });+});++describe("DELETE /api/memory/[id]", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "user-1" });+ });++ it("requires authentication", async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue(null);+ const response = await DELETE(makeRequest(), { params: { id: "mem-1" } });+ expect(response.status).toBe(401);+ expect(deleteProjectMemory).not.toHaveBeenCalled();+ });++ it("deletes the memory", async () => {+ (deleteProjectMemory as jest.Mock).mockResolvedValue({+ ok: true,+ connector: { id: "memory:abc" },+ capabilities: { delete: true },+ });+ const response = await DELETE(makeRequest("?connectorId=memory:abc"), {+ params: { id: "mem-1" },+ });+ expect(response.status).toBe(200);+ await expect(response.json()).resolves.toEqual(+ expect.objectContaining({ ok: true })+ );+ expect(deleteProjectMemory).toHaveBeenCalledWith({+ id: "mem-1",+ connectorId: "memory:abc",+ });+ });+});diff --git a/src/client/src/__tests__/app/api/memory/copy/route.test.ts b/src/client/src/__tests__/app/api/memory/copy/route.test.tsnew file mode 100644index 00000000..46b665b8--- /dev/null+++ b/src/client/src/__tests__/app/api/memory/copy/route.test.ts@@ -0,0 +1,108 @@+jest.mock("@/lib/session", () => ({+ getCurrentUser: jest.fn(),+}));+jest.mock("@/lib/platform/connectors/memory/port", () => ({+ copyProjectMemories: jest.fn(),+}));+jest.mock("@/utils/asaw", () =>+ jest.fn(async (promise: Promise<unknown>) => {+ try {+ return [null, await promise];+ } catch (error) {+ return [error, null];+ }+ })+);++import { POST } from "@/app/api/memory/copy/route";+import { getCurrentUser } from "@/lib/session";+import { copyProjectMemories } from "@/lib/platform/connectors/memory/port";+import {+ MEMORY_COPY_SAME_CONNECTOR,+ MEMORY_INVALID_JSON,+} from "@/constants/messages/en";++(globalThis as unknown as { Response: { json: unknown } }).Response = {+ json: (body: unknown, init?: ResponseInit) => ({+ status: init?.status ?? 200,+ json: async () => body,+ }),+};++function makePostRequest(body: unknown) {+ const url = "http://localhost/api/memory/copy";+ return {+ url,+ nextUrl: { searchParams: new URL(url).searchParams },+ json: async () => {+ if (body === "__invalid__") throw new SyntaxError("Unexpected token");+ return body;+ },+ } as any;+}++describe("POST /api/memory/copy", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "user-1" });+ });++ it("requires authentication", async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue(null);+ const response = await POST(+ makePostRequest({+ sourceConnectorId: "memory:src",+ targetConnectorId: "memory:dst",+ })+ );+ expect(response.status).toBe(401);+ expect(copyProjectMemories).not.toHaveBeenCalled();+ });++ it("rejects malformed JSON", async () => {+ const response = await POST(makePostRequest("__invalid__"));+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toBe(MEMORY_INVALID_JSON);+ });++ it("copies without leaking secretRef", async () => {+ (copyProjectMemories as jest.Mock).mockResolvedValue({+ source: { id: "memory:src", name: "Mem0", type: "mem0" },+ target: { id: "memory:dst", name: "Zep", type: "zep" },+ copied: 1,+ failed: [],+ memories: [{ id: "z1", content: "Prefers tabs", port: { sourceMemoryId: "m1" } }],+ });+ const response = await POST(+ makePostRequest({+ sourceConnectorId: "memory:src",+ targetConnectorId: "memory:dst",+ memoryIds: ["m1"],+ })+ );+ expect(response.status).toBe(200);+ const body = await response.json();+ expect(body.copied).toBe(1);+ expect(JSON.stringify(body)).not.toContain("secretRef");+ expect(copyProjectMemories).toHaveBeenCalledWith(+ expect.objectContaining({+ sourceConnectorId: "memory:src",+ targetConnectorId: "memory:dst",+ memoryIds: ["m1"],+ })+ );+ });++ it("returns 400 when source and destination are the same", async () => {+ (copyProjectMemories as jest.Mock).mockRejectedValue(+ new Error(MEMORY_COPY_SAME_CONNECTOR)+ );+ const response = await POST(+ makePostRequest({+ sourceConnectorId: "memory:src",+ targetConnectorId: "memory:src",+ })+ );+ expect(response.status).toBe(400);+ });+});diff --git a/src/client/src/__tests__/app/api/memory/route.test.ts b/src/client/src/__tests__/app/api/memory/route.test.tsnew file mode 100644index 00000000..63f85fab--- /dev/null+++ b/src/client/src/__tests__/app/api/memory/route.test.ts@@ -0,0 +1,151 @@+jest.mock("@/lib/session", () => ({+ getCurrentUser: jest.fn(),+}));+jest.mock("@/lib/platform/connectors/memory/read", () => ({+ queryProjectMemories: jest.fn(),+}));+jest.mock("@/lib/platform/connectors/memory/write", () => ({+ addProjectMemories: jest.fn(),+ parseMemoryMessages: (value: unknown) => value,+ parseMemoryMetadata: (value: unknown) => value,+}));+jest.mock("@/utils/asaw", () =>+ jest.fn(async (promise: Promise<unknown>) => {+ try {+ return [null, await promise];+ } catch (error) {+ return [error, null];+ }+ })+);++import { GET, POST } from "@/app/api/memory/route";+import { getCurrentUser } from "@/lib/session";+import { queryProjectMemories } from "@/lib/platform/connectors/memory/read";+import { addProjectMemories } from "@/lib/platform/connectors/memory/write";+import {+ MEMORY_CONNECTOR_NOT_FOUND,+ MEMORY_INVALID_JSON,+ MEMORY_INVALID_LIMIT,+} from "@/constants/messages/en";++(globalThis as unknown as { Response: { json: unknown } }).Response = {+ json: (body: unknown, init?: ResponseInit) => ({+ status: init?.status ?? 200,+ json: async () => body,+ }),+};++function makeRequest(query = "") {+ const url = `http://localhost/api/memory${query}`;+ return {+ url,+ nextUrl: { searchParams: new URL(url).searchParams },+ } as any;+}++function makePostRequest(body: unknown) {+ const url = "http://localhost/api/memory";+ return {+ url,+ nextUrl: { searchParams: new URL(url).searchParams },+ json: async () => {+ if (body === "__invalid__") throw new SyntaxError("Unexpected token");+ return body;+ },+ } as any;+}++describe("GET /api/memory", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "user-1" });+ });++ it("requires authentication", async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue(null);+ const response = await GET(makeRequest());+ expect(response.status).toBe(401);+ expect(queryProjectMemories).not.toHaveBeenCalled();+ });++ it("rejects an invalid limit", async () => {+ const response = await GET(makeRequest("?limit=999"));+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toBe(MEMORY_INVALID_LIMIT);+ expect(queryProjectMemories).not.toHaveBeenCalled();+ });++ it("returns memories without secretRef", async () => {+ (queryProjectMemories as jest.Mock).mockResolvedValue({+ connectors: [{ id: "memory:abc", name: "Mem0", hasSecret: true }],+ connector: { id: "memory:abc", name: "Mem0", hasSecret: true },+ memories: [{ id: "m1", content: "hello", kind: "summary" }],+ stats: { total: 1 },+ graph: { nodes: [], edges: [] },+ });+ const response = await GET(makeRequest("?connectorId=memory:abc"));+ expect(response.status).toBe(200);+ const body = await response.json();+ expect(body.memories[0].id).toBe("m1");+ expect(JSON.stringify(body)).not.toContain("secretRef");+ expect(queryProjectMemories).toHaveBeenCalledWith(+ expect.objectContaining({ connectorId: "memory:abc" })+ );+ });++ it("returns 404 when the connector is missing", async () => {+ (queryProjectMemories as jest.Mock).mockRejectedValue(+ new Error(MEMORY_CONNECTOR_NOT_FOUND)+ );+ const response = await GET(makeRequest("?connectorId=memory:missing"));+ expect(response.status).toBe(404);+ });+});++describe("POST /api/memory", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "user-1" });+ });++ it("requires authentication", async () => {+ (getCurrentUser as jest.Mock).mockResolvedValue(null);+ const response = await POST(makePostRequest({ content: "hello" }));+ expect(response.status).toBe(401);+ expect(addProjectMemories).not.toHaveBeenCalled();+ });++ it("rejects malformed JSON", async () => {+ const response = await POST(makePostRequest("__invalid__"));+ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toBe(MEMORY_INVALID_JSON);+ expect(addProjectMemories).not.toHaveBeenCalled();+ });++ it("creates a memory without leaking secretRef", async () => {+ (addProjectMemories as jest.Mock).mockResolvedValue({+ connector: { id: "memory:abc", name: "Mem0", hasSecret: true },+ capabilities: { add: true },+ memories: [{ id: "m1", content: "Prefers tabs", kind: "profile" }],+ });+ const response = await POST(+ makePostRequest({+ connectorId: "memory:abc",+ content: "Prefers tabs",+ userId: "ada",+ })+ );+ expect(response.status).toBe(200);+ const body = await response.json();+ expect(body.memories[0].id).toBe("m1");+ expect(JSON.stringify(body)).not.toContain("secretRef");+ expect(addProjectMemories).toHaveBeenCalledWith(+ expect.objectContaining({+ connectorId: "memory:abc",+ content: "Prefers tabs",+ userId: "ada",+ })+ );+ });+});diff --git a/src/client/src/__tests__/app/api/route-access-wraps.test.ts b/src/client/src/__tests__/app/api/route-access-wraps.test.tsindex 1a44e75d..e9214590 100644--- a/src/client/src/__tests__/app/api/route-access-wraps.test.ts+++ b/src/client/src/__tests__/app/api/route-access-wraps.test.ts@@ -37,6 +37,23 @@ describe("new implementation route access wraps", () => {}});+ it("wraps memory routes with memory access/audit hooks", () => {+ const files = [+ "memory/route.ts",+ "memory/copy/route.ts",+ "memory/[id]/route.ts",+ "memory/[id]/feedback/route.ts",+ ];+ for (const rel of files) {+ const source = readFileSync(join(API_ROOT, rel), "utf8");+ expect(source).toMatch(/withMemoryAccess/);+ expect(source).not.toMatch(/"[a-z_]+:[a-z_]+"/);+ if (rel.includes("[id]") || rel === "memory/route.ts" || rel === "memory/copy/route.ts") {+ expect(source).toMatch(/withMemoryAudit/);+ }+ }+ });+it("wraps telemetry query routes with withRouteAccess", () => {const roots = ["metrics", "telemetry", "observability"].map((d) =>join(API_ROOT, d)diff --git a/src/client/src/__tests__/components/ask-otter-panel.test.tsx b/src/client/src/__tests__/components/ask-otter-panel.test.tsxnew file mode 100644index 00000000..d084ce0f--- /dev/null+++ b/src/client/src/__tests__/components/ask-otter-panel.test.tsx@@ -0,0 +1,80 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import AskOtterPanel from "@/components/(playground)/chat/ask-otter-panel";++jest.mock("react-markdown", () => ({+ __esModule: true,+ default: ({ children }: { children: string }) => <div>{children}</div>,+}));++jest.mock("@/utils/api", () => ({+ getRequestHeaders: () => ({ "Content-Type": "application/json" }),+}));++Object.defineProperty(HTMLElement.prototype, "scrollTo", {+ writable: true,+ value: jest.fn(),+});++describe("AskOtterPanel", () => {+ const copy = {+ title: "Ask Otter",+ empty: "Ask about this page.",+ placeholder: "Ask anything…",+ hint: "Answers stay on this page.",+ send: "Ask Otter",+ conversationTitle: "Ask Otter",+ };++ beforeEach(() => {+ global.fetch = jest.fn((input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (url === "/api/chat/config") {+ return Promise.resolve({+ ok: true,+ json: async () => ({ data: { provider: "openai" } }),+ });+ }+ if (url === "/api/chat/conversation") {+ return Promise.resolve({+ ok: true,+ json: async () => ({ data: "conv-1" }),+ });+ }+ if (url === "/api/chat/message") {+ const body = JSON.parse(String(init?.body || "{}")) as { content?: string };+ expect(body.content).toContain("PROMPT:hello");+ return Promise.resolve({+ ok: true,+ body: {+ getReader: () => ({+ read: async () => ({ done: true, value: undefined }),+ }),+ },+ });+ }+ return Promise.reject(new Error(`unexpected fetch ${url}`));+ }) as unknown as typeof fetch;+ });++ it("renders page copy and selected context, then prompts with the question", async () => {+ const buildPrompt = jest.fn((question: string) => `PROMPT:${question}`);+ render(+ <AskOtterPanel+ copy={copy}+ buildPrompt={buildPrompt}+ contextLabel="Selected: User visited New York"+ />+ );++ expect(screen.getByText("Ask about this page.")).toBeInTheDocument();+ expect(screen.getByText("Selected: User visited New York")).toBeInTheDocument();+ await waitFor(() =>+ expect(screen.getByPlaceholderText("Ask anything…")).not.toBeDisabled()+ );+ fireEvent.change(screen.getByPlaceholderText("Ask anything…"), {+ target: { value: "hello" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Ask Otter" }));+ await waitFor(() => expect(buildPrompt).toHaveBeenCalledWith("hello"));+ });+});diff --git a/src/client/src/__tests__/components/data-sources-page-filters.test.ts b/src/client/src/__tests__/components/data-sources-page-filters.test.tsnew file mode 100644index 00000000..25a6fc0a--- /dev/null+++ b/src/client/src/__tests__/components/data-sources-page-filters.test.ts@@ -0,0 +1,54 @@+import { configuredConnectorMatches } from "@/lib/platform/connectors/list-filters";++const base = {+ query: "",+ typeFilter: "all",+ categoryFilter: "all",+ signalFilter: "all",+ type: "mem0",+ category: "memory",+ signals: [] as string[],+ searchText: "Prod Mem0 mem0 memory",+};++describe("configuredConnectorMatches", () => {+ it("matches every connector when search and filters are empty", () => {+ expect(configuredConnectorMatches(base)).toBe(true);+ });++ it("matches by name search", () => {+ expect(configuredConnectorMatches({ ...base, query: "mem0" })).toBe(true);+ expect(configuredConnectorMatches({ ...base, query: "tempo" })).toBe(false);+ });++ it("filters by type, category, and signal", () => {+ expect(configuredConnectorMatches({ ...base, typeFilter: "mem0" })).toBe(true);+ expect(configuredConnectorMatches({ ...base, typeFilter: "zep" })).toBe(false);+ expect(+ configuredConnectorMatches({ ...base, categoryFilter: "memory" })+ ).toBe(true);+ expect(+ configuredConnectorMatches({ ...base, categoryFilter: "datasource" })+ ).toBe(false);+ expect(+ configuredConnectorMatches({+ ...base,+ type: "tempo",+ category: "datasource",+ signals: ["traces"],+ searchText: "Tempo tempo traces",+ signalFilter: "traces",+ })+ ).toBe(true);+ expect(+ configuredConnectorMatches({+ ...base,+ type: "tempo",+ category: "datasource",+ signals: ["traces"],+ searchText: "Tempo tempo traces",+ signalFilter: "logs",+ })+ ).toBe(false);+ });+});diff --git a/src/client/src/__tests__/components/memory-copy-dialog.test.tsx b/src/client/src/__tests__/components/memory-copy-dialog.test.tsxnew file mode 100644index 00000000..3c59f8aa--- /dev/null+++ b/src/client/src/__tests__/components/memory-copy-dialog.test.tsx@@ -0,0 +1,175 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import MemoryCopyDialog from "@/components/(playground)/memory/memory-copy-dialog";++jest.mock("@/utils/api", () => ({+ getRequestHeaders: (headers?: Record<string, string>) => headers || {},+}));++class ResizeObserverMock {+ observe() {}+ unobserve() {}+ disconnect() {}+}+Object.defineProperty(global, "ResizeObserver", {+ writable: true,+ value: ResizeObserverMock,+});+Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {+ writable: true,+ value: jest.fn(),+});++const zepTarget = {+ id: "memory:zep",+ name: "prod-zep",+ type: "zep",+ environment: "production",+ capabilities: { add: true },+ filterFields: [+ { key: "userId" as const, label: "User", required: true, allowCustom: true },+ {+ key: "sessionId" as const,+ label: "Session",+ writeRequired: true,+ allowCustom: true,+ },+ ],+};++const mem0Target = {+ id: "memory:mem0",+ name: "prod-mem0",+ type: "mem0",+ environment: "production",+ capabilities: { add: true },+ filterFields: [+ { key: "userId" as const, label: "User", allowCustom: true },+ { key: "sessionId" as const, label: "Session", allowCustom: true },+ { key: "agentId" as const, label: "Agent", allowCustom: true },+ ],+};++function jsonResponse(body: unknown) {+ return {+ ok: true,+ json: async () => body,+ };+}++describe("MemoryCopyDialog", () => {+ beforeEach(() => {+ (global.fetch as jest.Mock | undefined) = jest.fn((url: string) => {+ const href = String(url);+ if (href.includes("connectorId=memory%3Azep")) {+ return Promise.resolve(+ jsonResponse({+ filters: {+ users: [{ id: "ada", label: "[email protected]" }],+ sessions: [{ id: "thread-1", label: "thread-1", userId: "ada" }],+ agents: [],+ },+ filterFields: zepTarget.filterFields,+ })+ );+ }+ if (href.includes("connectorId=memory%3Amem0")) {+ return Promise.resolve(+ jsonResponse({+ filters: {+ users: [{ id: "mem0-user", label: "mem0-user" }],+ sessions: [{ id: "mem0-session", label: "mem0-session" }],+ agents: [{ id: "mem0-agent", label: "mem0-agent" }],+ },+ filterFields: mem0Target.filterFields,+ })+ );+ }+ return Promise.resolve(+ jsonResponse({+ filters: {+ users: [],+ sessions: [+ {+ id: "memstore_016B8h7mS5FdSxfz92reXzKb",+ label: "OpenLIT connector",+ },+ ],+ agents: [],+ },+ })+ );+ });+ });++ afterEach(() => {+ (global.fetch as jest.Mock).mockReset();+ });++ it("does not repeat the User and Session labels in the empty combobox", async () => {+ render(+ <MemoryCopyDialog+ open+ count={1}+ targets={[zepTarget]}+ onOpenChange={jest.fn()}+ onSubmit={jest.fn()}+ />+ );+ await waitFor(() => expect(global.fetch).toHaveBeenCalled());+ expect(screen.getByLabelText("User")).toHaveTextContent("Select");+ expect(screen.getByLabelText("User")).not.toHaveTextContent("User User");+ expect(screen.getByLabelText("Session")).toHaveTextContent("Select");+ });++ it("loads user and session options for the selected destination connector", async () => {+ render(+ <MemoryCopyDialog+ open+ count={1}+ targets={[zepTarget]}+ onOpenChange={jest.fn()}+ onSubmit={jest.fn()}+ />+ );+ await waitFor(() =>+ expect(global.fetch).toHaveBeenCalledWith(+ "/api/memory?connectorId=memory%3Azep&limit=1",+ expect.objectContaining({ signal: expect.any(AbortSignal) })+ )+ );+ await waitFor(() =>+ expect(screen.getByLabelText("User")).not.toBeDisabled()+ );+ fireEvent.click(screen.getByLabelText("User"));+ expect(screen.getByRole("option", { name: /[email protected]/i })).toBeInTheDocument();+ expect(+ screen.queryByRole("option", { name: /OpenLIT connector/i })+ ).not.toBeInTheDocument();+ });++ it("shows the destination vendor fields and options, not Claude stores", async () => {+ render(+ <MemoryCopyDialog+ open+ count={1}+ targets={[mem0Target]}+ onOpenChange={jest.fn()}+ onSubmit={jest.fn()}+ />+ );+ await waitFor(() =>+ expect(global.fetch).toHaveBeenCalledWith(+ "/api/memory?connectorId=memory%3Amem0&limit=1",+ expect.objectContaining({ signal: expect.any(AbortSignal) })+ )+ );+ await waitFor(() =>+ expect(screen.getByLabelText("Agent")).not.toBeDisabled()+ );+ fireEvent.click(screen.getByLabelText("Agent"));+ expect(screen.getByRole("option", { name: /mem0-agent/i })).toBeInTheDocument();+ expect(+ screen.queryByRole("option", { name: /OpenLIT connector/i })+ ).not.toBeInTheDocument();+ });+});diff --git a/src/client/src/__tests__/components/memory-detail-sheet.test.tsx b/src/client/src/__tests__/components/memory-detail-sheet.test.tsxnew file mode 100644index 00000000..562beb98--- /dev/null+++ b/src/client/src/__tests__/components/memory-detail-sheet.test.tsx@@ -0,0 +1,252 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import MemoryDetailSheet from "@/components/(playground)/memory/memory-detail-sheet";+import type { MemoryListItem } from "@/lib/platform/connectors/memory/read";++jest.mock("sonner", () => ({+ toast: { success: jest.fn(), error: jest.fn() },+}));++jest.mock("@/utils/api", () => ({+ getRequestHeaders: (headers?: Record<string, string>) => headers || {},+}));++class ResizeObserverMock {+ observe() {}+ unobserve() {}+ disconnect() {}+}+Object.defineProperty(global, "ResizeObserver", {+ writable: true,+ value: ResizeObserverMock,+});++const preview: MemoryListItem = {+ id: "mem-1",+ content: "Prefers tabs",+ kind: "profile",+ userId: "ada",+};++describe("MemoryDetailSheet writes", () => {+ beforeEach(() => {+ global.fetch = jest.fn().mockResolvedValue({+ ok: true,+ json: async () => ({+ memory: preview,+ capabilities: { get: true, update: true, delete: true, feedback: false },+ connector: { name: "Mem0" },+ }),+ }) as unknown as typeof fetch;+ });++ it("shows edit and delete when the connector can write", async () => {+ render(+ <MemoryDetailSheet+ open+ memoryId="mem-1"+ connectorId="memory:abc"+ capabilities={{+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: false,+ }}+ preview={preview}+ onClose={jest.fn()}+ />+ );+ await waitFor(() => expect(screen.getByTitle("Edit")).toBeInTheDocument());+ expect(screen.getByTitle("Delete")).toBeInTheDocument();+ });++ it("hides edit and delete when the connector is read-only", async () => {+ (global.fetch as jest.Mock).mockResolvedValue({+ ok: true,+ json: async () => ({+ memory: preview,+ capabilities: { get: true, update: false, delete: false, feedback: false },+ connector: { name: "Zep" },+ }),+ });+ render(+ <MemoryDetailSheet+ open+ memoryId="mem-1"+ capabilities={{+ add: false,+ search: true,+ get: true,+ list: true,+ update: false,+ delete: false,+ feedback: false,+ }}+ preview={preview}+ onClose={jest.fn()}+ />+ );+ await waitFor(() => expect(screen.getByText("Zep")).toBeInTheDocument());+ expect(screen.queryByTitle("Edit")).not.toBeInTheDocument();+ expect(screen.queryByTitle("Delete")).not.toBeInTheDocument();+ });++ it("deletes a memory after confirmation", async () => {+ const onClose = jest.fn();+ const onChanged = jest.fn();+ (global.fetch as jest.Mock).mockImplementation(async (url: string, init?: RequestInit) => {+ if (init?.method === "DELETE") {+ return { ok: true, json: async () => ({ ok: true }) };+ }+ return {+ ok: true,+ json: async () => ({+ memory: preview,+ capabilities: { get: true, update: true, delete: true, feedback: false },+ connector: { name: "Mem0" },+ }),+ };+ });+ render(+ <MemoryDetailSheet+ open+ memoryId="mem-1"+ connectorId="memory:abc"+ capabilities={{+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: false,+ }}+ preview={preview}+ onClose={onClose}+ onChanged={onChanged}+ />+ );+ await waitFor(() => expect(screen.getByTitle("Delete")).toBeInTheDocument());+ fireEvent.click(screen.getByTitle("Delete"));+ fireEvent.click(screen.getByRole("button", { name: "Delete memory" }));+ await waitFor(() => expect(onClose).toHaveBeenCalled());+ expect(onChanged).toHaveBeenCalled();+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining("/api/memory/mem-1"),+ expect.objectContaining({ method: "DELETE" })+ );+ });++ it("keeps the detail sheet open when edit is clicked", async () => {+ const onClose = jest.fn();+ render(+ <MemoryDetailSheet+ open+ memoryId="mem-1"+ connectorId="memory:abc"+ capabilities={{+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: false,+ }}+ preview={preview}+ onClose={onClose}+ />+ );+ await waitFor(() => expect(screen.getByTitle("Edit")).toBeInTheDocument());+ fireEvent.click(screen.getByTitle("Edit"));+ expect(await screen.findByText("Edit memory")).toBeInTheDocument();+ expect(onClose).not.toHaveBeenCalled();+ expect(screen.getByTitle("Edit")).toBeInTheDocument();+ });++ it("shows the source connector and copy action for ported memories", async () => {+ const onCopy = jest.fn();+ const onOpenSource = jest.fn();+ render(+ <MemoryDetailSheet+ open+ memoryId="mem-1"+ connectorId="memory:abc"+ capabilities={{+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: false,+ }}+ preview={{+ ...preview,+ port: {+ sourceConnectorId: "memory:src",+ sourceConnectorName: "Prod Mem0",+ sourceMemoryId: "src-1",+ copiedAt: "2026-08-18T12:00:00.000Z",+ contentFingerprint: "abc",+ },+ }}+ onClose={jest.fn()}+ onCopy={onCopy}+ onOpenSource={onOpenSource}+ />+ );+ expect(await screen.findByText("Copied from")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Prod Mem0" }));+ expect(onOpenSource).toHaveBeenCalledWith("memory:src", "src-1");+ fireEvent.click(screen.getByTitle("Copy to connector"));+ expect(onCopy).toHaveBeenCalledWith("mem-1");+ });++ it("renders date-part attributes as a single datetime", async () => {+ const dateParts = {+ Day: 17,+ Hour: 11,+ Year: 2026,+ Month: 8,+ Minute: 28,+ Quarter: 3,+ "Is weekend": "No",+ "Day of week": "monday",+ "Day of year": 229,+ "Week of year": 34,+ };+ (global.fetch as jest.Mock).mockResolvedValue({+ ok: true,+ json: async () => ({+ memory: { ...preview, structuredAttributes: dateParts },+ capabilities: { get: true, update: true, delete: true, feedback: false },+ connector: { name: "Zep" },+ }),+ });+ render(+ <MemoryDetailSheet+ open+ memoryId="mem-1"+ capabilities={{+ add: false,+ search: true,+ get: true,+ list: true,+ update: false,+ delete: false,+ feedback: false,+ }}+ preview={preview}+ onClose={jest.fn()}+ />+ );+ expect(+ await screen.findByText(new Date(2026, 7, 17, 11, 28, 0).toLocaleString())+ ).toBeInTheDocument();+ expect(screen.queryByText("Day of week")).not.toBeInTheDocument();+ expect(screen.queryByText("Is weekend")).not.toBeInTheDocument();+ });+});diff --git a/src/client/src/__tests__/components/memory-filter-combobox.test.tsx b/src/client/src/__tests__/components/memory-filter-combobox.test.tsxnew file mode 100644index 00000000..f7b28e06--- /dev/null+++ b/src/client/src/__tests__/components/memory-filter-combobox.test.tsx@@ -0,0 +1,52 @@+import { fireEvent, render, screen } from "@testing-library/react";+import MemoryFilterCombobox from "@/components/(playground)/memory/memory-filter-combobox";++class ResizeObserverMock {+ observe() {}+ unobserve() {}+ disconnect() {}+}++Object.defineProperty(global, "ResizeObserver", {+ writable: true,+ value: ResizeObserverMock,+});+Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {+ writable: true,+ value: jest.fn(),+});++describe("MemoryFilterCombobox", () => {+ it("uses a generic placeholder in dialogs instead of repeating the field label", () => {+ render(+ <MemoryFilterCombobox+ label="User"+ value=""+ options={[]}+ onChange={jest.fn()}+ allowCustom+ required+ inDialog+ />+ );+ expect(screen.getByRole("button", { name: "User" })).toHaveTextContent("Select");+ expect(screen.getByRole("button", { name: "User" })).not.toHaveTextContent(+ "User User"+ );+ });++ it("lists the current custom value even when the vendor has no options", () => {+ render(+ <MemoryFilterCombobox+ label="User"+ value="aman"+ options={[]}+ onChange={jest.fn()}+ allowCustom+ required+ />+ );+ fireEvent.click(screen.getByRole("button", { name: "User" }));+ expect(screen.getByRole("option", { name: /aman/i })).toBeInTheDocument();+ });+});diff --git a/src/client/src/__tests__/components/memory-list.test.tsx b/src/client/src/__tests__/components/memory-list.test.tsxnew file mode 100644index 00000000..c515853c--- /dev/null+++ b/src/client/src/__tests__/components/memory-list.test.tsx@@ -0,0 +1,70 @@+import { fireEvent, render, screen } from "@testing-library/react";+import MemoryList from "@/components/(playground)/memory/memory-list";+import type { MemoryListItem } from "@/lib/platform/connectors/memory/read";++function memories(count: number): MemoryListItem[] {+ return Array.from({ length: count }, (_, index) => ({+ id: `mem-${index + 1}`,+ content: `Memory ${index + 1}`,+ kind: "temporal" as const,+ createdAt: "2026-08-17T00:00:00Z",+ }));+}++describe("MemoryList pagination", () => {+ it("pages long memory lists", () => {+ const onSelect = jest.fn();+ render(+ <MemoryList+ memories={memories(21)}+ search=""+ onSearchChange={jest.fn()}+ onSelect={onSelect}+ />+ );+ expect(screen.getByText("Memory 1")).toBeInTheDocument();+ expect(screen.queryByText("Memory 21")).not.toBeInTheDocument();+ expect(screen.getByText("1 of 2")).toBeInTheDocument();+ fireEvent.click(screen.getByLabelText("Next page"));+ expect(screen.getByText("Memory 21")).toBeInTheDocument();+ expect(screen.queryByText("Memory 1")).not.toBeInTheDocument();+ });++ it("shows the source connector for copied memories", () => {+ render(+ <MemoryList+ memories={[+ {+ ...memories(1)[0],+ port: {+ sourceConnectorId: "memory:src",+ sourceConnectorName: "Prod Mem0",+ sourceMemoryId: "src-1",+ copiedAt: "2026-08-18T12:00:00.000Z",+ contentFingerprint: "abc",+ },+ },+ ]}+ search=""+ onSearchChange={jest.fn()}+ onSelect={jest.fn()}+ />+ );+ expect(screen.getByText(/Copied from/)).toBeInTheDocument();+ expect(screen.getByText(/Prod Mem0/)).toBeInTheDocument();+ });++ it("opens the page that contains the selected memory", () => {+ render(+ <MemoryList+ memories={memories(21)}+ search=""+ onSearchChange={jest.fn()}+ selectedId="mem-21"+ onSelect={jest.fn()}+ />+ );+ expect(screen.getByText("Memory 21")).toBeInTheDocument();+ expect(screen.getByText("2 of 2")).toBeInTheDocument();+ });+});diff --git a/src/client/src/__tests__/components/memory-page.test.tsx b/src/client/src/__tests__/components/memory-page.test.tsxnew file mode 100644index 00000000..3167dc02--- /dev/null+++ b/src/client/src/__tests__/components/memory-page.test.tsx@@ -0,0 +1,540 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import MemoryPage from "@/components/(playground)/memory/memory-page";++const replaceMock = jest.fn();+let searchParams = "";++jest.mock("next/navigation", () => ({+ usePathname: () => "/memory",+ useRouter: () => ({ replace: replaceMock }),+ useSearchParams: () => new URLSearchParams(searchParams),+}));++jest.mock("posthog-js/react", () => ({+ usePostHog: () => ({ capture: jest.fn() }),+}));++jest.mock("@/store", () => ({+ useRootStore: (selector: (state: unknown) => unknown) => selector({}),+}));++jest.mock("@/utils/api", () => ({+ getRequestHeaders: (headers?: Record<string, string>) => headers || {},+}));++jest.mock("@/selectors/project", () => ({+ getCurrentProject: () => ({ id: "proj-1" }),+ getCurrentProjectEnvironment: () => "production",+}));++jest.mock("@/components/(playground)/feature-page-header", () => ({+ __esModule: true,+ default: ({ title, actions }: { title: string; actions?: ReactNode }) => (+ <div>+ <h1>{title}</h1>+ {actions}+ </div>+ ),+}));++jest.mock("@/components/(playground)/telemetry-source/data-sources-page", () => ({+ SourceFormDialog: ({+ onClose,+ onSaved,+ }: {+ onClose: () => void;+ onSaved: () => void;+ }) => (+ <div data-testid="source-form-dialog">+ <button type="button" onClick={onClose}>+ close connector+ </button>+ <button type="button" data-testid="source-form-saved" onClick={onSaved}>+ saved+ </button>+ </div>+ ),+}));++jest.mock("@/components/(playground)/memory/memory-graph", () => ({+ __esModule: true,+ default: ({ selectedId, onSelect }: { selectedId?: string | null; onSelect: (id: string) => void }) => (+ <button type="button" data-testid="graph-select" onClick={() => onSelect("mem-1")}>+ graph {selectedId || "none"}+ </button>+ ),+}));++jest.mock("@/components/(playground)/memory/memory-list", () => ({+ __esModule: true,+ default: ({+ memories,+ selectedId,+ onSelect,+ }: {+ memories?: Array<{ id: string; content: string }>;+ selectedId?: string | null;+ onSelect: (id: string) => void;+ }) => (+ <div>+ {(memories || []).map((memory) => (+ <button key={memory.id} type="button" onClick={() => onSelect(memory.id)}>+ {memory.content}+ </button>+ ))}+ <button type="button" data-testid="list-select" onClick={() => onSelect("mem-1")}>+ list {selectedId || "none"}+ </button>+ </div>+ ),+}));++jest.mock("@/components/(playground)/memory/memory-detail-sheet", () => ({+ __esModule: true,+ default: ({+ open,+ memoryId,+ onClose,+ }: {+ open: boolean;+ memoryId: string | null;+ onClose: () => void;+ }) => (+ <div data-testid="detail-sheet" data-open={open ? "true" : "false"} data-id={memoryId || ""}>+ <button type="button" data-testid="close-sheet" onClick={onClose}>+ close+ </button>+ </div>+ ),+}));++jest.mock("@/components/(playground)/memory/ask-otter", () => ({+ __esModule: true,+ default: ({+ scope,+ }: {+ scope?: { memoryId?: string; memoryContent?: string };+ }) => (+ <div+ data-testid="ask-otter"+ data-memory-id={scope?.memoryId || ""}+ data-memory-content={scope?.memoryContent || ""}+ />+ ),+}));++jest.mock("@/components/ui/resizable", () => ({+ ResizablePanelGroup: ({ children }: { children: ReactNode }) => (+ <div data-testid="memory-split">{children}</div>+ ),+ ResizablePanel: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ ResizableHandle: ({ "aria-label": label }: { "aria-label"?: string }) => (+ <div role="separator" aria-label={label} />+ ),+}));++jest.mock("@/components/(playground)/memory/memory-copy-dialog", () => ({+ __esModule: true,+ default: ({+ open,+ onSubmit,+ }: {+ open: boolean;+ onSubmit: (input: { targetConnectorId: string }) => void;+ }) =>+ open ? (+ <div data-testid="copy-dialog">+ <button+ type="button"+ data-testid="copy-submit"+ onClick={() => onSubmit({ targetConnectorId: "memory:2" })}+ >+ submit copy+ </button>+ </div>+ ) : null,+}));++jest.mock("@/components/(playground)/memory/memory-write-dialog", () => ({+ __esModule: true,+ default: ({+ open,+ onSubmit,+ }: {+ open: boolean;+ onSubmit: (input: {+ content: string;+ userId?: string;+ sessionId?: string;+ agentId?: string;+ }) => void;+ }) =>+ open ? (+ <div data-testid="write-dialog">+ <button+ type="button"+ data-testid="write-submit"+ onClick={() => onSubmit({ content: "remember this", userId: "alex" })}+ >+ submit+ </button>+ </div>+ ) : null,+}));++const payload = {+ connectors: [{ id: "memory:1", name: "Mem0", type: "mem0" }],+ connector: { id: "memory:1", name: "Mem0", type: "mem0" },+ capabilities: { get: true, list: true },+ memories: [{ id: "mem-1", content: "User visited New York", kind: "temporal" }],+ stats: { total: 1, connections: 0, temporal: 1, profile: 0, summary: 0 },+ graph: { nodes: [], edges: [] },+ filters: { users: [], sessions: [], agents: [] },+ filterFields: [],+};++class ResizeObserverMock {+ observe() {}+ unobserve() {}+ disconnect() {}+}+Object.defineProperty(global, "ResizeObserver", {+ writable: true,+ value: ResizeObserverMock,+});+Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {+ writable: true,+ value: jest.fn(),+});++describe("MemoryPage URL selection", () => {+ beforeEach(() => {+ searchParams = "";+ replaceMock.mockReset();+ global.fetch = jest.fn().mockResolvedValue({+ ok: true,+ json: async () => payload,+ }) as unknown as typeof fetch;+ });++ it("keeps the detail sheet closed on /memory until an id is in the URL", async () => {+ render(<MemoryPage />);+ await waitFor(() => expect(screen.getByTestId("graph-select")).toBeInTheDocument());+ expect(screen.getByTestId("detail-sheet")).toHaveAttribute("data-open", "false");+ expect(screen.getByTestId("detail-sheet")).toHaveAttribute("data-id", "");+ expect(screen.getByTestId("memory-split")).toBeInTheDocument();+ expect(screen.getByRole("separator", { name: "Resize memories and Ask Otter panels" })).toBeInTheDocument();+ expect(screen.getByTestId("ask-otter")).toBeInTheDocument();+ });++ it("opens the detail sheet from ?id=", async () => {+ searchParams = "id=mem-1";+ render(<MemoryPage />);+ await waitFor(() => expect(screen.getByTestId("detail-sheet")).toHaveAttribute("data-open", "true"));+ expect(screen.getByTestId("detail-sheet")).toHaveAttribute("data-id", "mem-1");+ await waitFor(() => {+ expect(screen.getByTestId("ask-otter")).toHaveAttribute("data-memory-id", "mem-1");+ expect(screen.getByTestId("ask-otter")).toHaveAttribute(+ "data-memory-content",+ "User visited New York"+ );+ });+ });++ it("writes the memory id into the URL when a memory is selected", async () => {+ render(<MemoryPage />);+ await waitFor(() => expect(screen.getByTestId("graph-select")).toBeInTheDocument());+ fireEvent.click(screen.getByTestId("graph-select"));+ expect(replaceMock).toHaveBeenCalledWith(+ "/memory?id=mem-1&connectorId=memory%3A1",+ { scroll: false }+ );+ });++ it("shows graph and list in separate tabs", async () => {+ render(<MemoryPage />);+ await waitFor(() => expect(screen.getByTestId("graph-select")).toBeInTheDocument());+ const graphTab = screen.getByRole("tab", { name: "Memory graph" });+ const listTab = screen.getByRole("tab", { name: "Memories" });+ expect(graphTab).toHaveAttribute("data-state", "active");+ expect(listTab).toHaveAttribute("data-state", "inactive");+ fireEvent.mouseDown(listTab);+ expect(listTab).toHaveAttribute("data-state", "active");+ expect(graphTab).toHaveAttribute("data-state", "inactive");+ });++ it("removes the memory id from the URL when the sheet closes", async () => {+ searchParams = "id=mem-1&connectorId=memory%3A1";+ render(<MemoryPage />);+ await waitFor(() => expect(screen.getByTestId("detail-sheet")).toHaveAttribute("data-open", "true"));+ fireEvent.click(screen.getByTestId("close-sheet"));+ expect(replaceMock).toHaveBeenCalledWith("/memory?connectorId=memory%3A1", {+ scroll: false,+ });+ });++ it("shows an API key hint when the connector rejects auth", async () => {+ (global.fetch as jest.Mock).mockResolvedValue({+ ok: true,+ json: async () => ({+ ...payload,+ memories: [],+ stats: { total: 0, connections: 0, temporal: 0, profile: 0, summary: 0 },+ hint: "auth_failed",+ }),+ });+ render(<MemoryPage />);+ await waitFor(() =>+ expect(screen.getByText("Memories are unavailable")).toBeInTheDocument()+ );+ expect(+ screen.getByText(+ "This connector rejected the API key. Edit the connector, save a valid key, and try again."+ )+ ).toBeInTheDocument();+ expect(screen.queryByTestId("graph-select")).not.toBeInTheDocument();+ });++ it("hides user and session filters when the vendor declares none", async () => {+ (global.fetch as jest.Mock).mockResolvedValue({+ ok: true,+ json: async () => ({+ ...payload,+ connectors: [+ {+ id: "memory:read-only",+ name: "read-only memory",+ type: "mem0",+ environment: "production",+ },+ ],+ connector: {+ id: "memory:read-only",+ name: "read-only memory",+ type: "mem0",+ environment: "production",+ },+ filters: { users: [{ id: "alex", label: "alex" }], sessions: [], agents: [] },+ filterFields: [],+ }),+ });+ render(<MemoryPage />);+ await waitFor(() => expect(screen.getByTestId("graph-select")).toBeInTheDocument());+ expect(screen.queryByLabelText("User")).not.toBeInTheDocument();+ expect(screen.queryByLabelText("Session")).not.toBeInTheDocument();+ });++ it("shows editable connector filters even when the vendor listed no options", async () => {+ (global.fetch as jest.Mock).mockResolvedValue({+ ok: true,+ json: async () => ({+ ...payload,+ filters: { users: [], sessions: [], agents: [] },+ filterFields: [+ { key: "userId", label: "User", allowCustom: true, required: true },+ { key: "sessionId", label: "Session", allowCustom: true },+ ],+ }),+ });+ render(<MemoryPage />);+ await waitFor(() => expect(screen.getByLabelText("User")).toBeInTheDocument());+ expect(screen.getByLabelText("User")).not.toBeDisabled();+ expect(screen.getByLabelText("Session")).not.toBeDisabled();+ expect(screen.getByLabelText("User")).toHaveTextContent("User");+ });++ it("auto-selects the only required user", async () => {+ (global.fetch as jest.Mock).mockResolvedValue({+ ok: true,+ json: async () => ({+ ...payload,+ filters: { users: [{ id: "alex", label: "alex" }], sessions: [], agents: [] },+ filterFields: [+ { key: "userId", label: "User", allowCustom: true, required: true },+ ],+ }),+ });+ render(<MemoryPage />);+ await waitFor(() => expect(screen.getByLabelText("User")).toHaveTextContent("alex"));+ });++ it("hides copy when there is no writable destination connector", async () => {+ render(<MemoryPage />);+ await waitFor(() => expect(screen.getByTestId("graph-select")).toBeInTheDocument());+ expect(screen.queryByRole("button", { name: "Copy to connector" })).not.toBeInTheDocument();+ });++ it("copies loaded memories to another connector", async () => {+ (global.fetch as jest.Mock).mockImplementation(+ async (input: RequestInfo, init?: RequestInit) => {+ const url = String(input);+ const method = init?.method || "GET";+ if (url === "/api/memory/copy" && method === "POST") {+ return {+ ok: true,+ json: async () => ({+ copied: 1,+ failed: [],+ target: { id: "memory:2", name: "Zep" },+ }),+ };+ }+ if (url.startsWith("/api/memory")) {+ return {+ ok: true,+ json: async () => ({+ ...payload,+ connectors: [+ {+ id: "memory:1",+ name: "Mem0",+ type: "mem0",+ capabilities: { add: true },+ },+ {+ id: "memory:2",+ name: "Zep",+ type: "zep",+ capabilities: { add: true },+ },+ ],+ capabilities: { add: true, get: true, list: true },+ }),+ };+ }+ return { ok: true, json: async () => ({ types: [] }) };+ }+ );+ render(<MemoryPage />);+ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Copy to connector" })).toBeEnabled()+ );+ fireEvent.click(screen.getByRole("button", { name: "Copy to connector" }));+ fireEvent.click(screen.getByTestId("copy-submit"));+ await waitFor(() =>+ expect(global.fetch).toHaveBeenCalledWith(+ "/api/memory/copy",+ expect.objectContaining({ method: "POST" })+ )+ );+ expect(replaceMock).toHaveBeenCalledWith("/memory?connectorId=memory%3A2", {+ scroll: false,+ });+ });++ it("hides add memory when the connector cannot write", async () => {+ render(<MemoryPage />);+ await waitFor(() => expect(screen.getByTestId("graph-select")).toBeInTheDocument());+ expect(screen.queryByRole("button", { name: "Add memory" })).not.toBeInTheDocument();+ });++ it("shows add memory when the connector can write", async () => {+ (global.fetch as jest.Mock).mockResolvedValue({+ ok: true,+ json: async () => ({+ ...payload,+ capabilities: { add: true, get: true, list: true, update: true, delete: true },+ }),+ });+ render(<MemoryPage />);+ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Add memory" })).toBeEnabled()+ );+ fireEvent.click(screen.getByRole("button", { name: "Add memory" }));+ expect(screen.getByTestId("write-dialog")).toBeInTheDocument();+ });++ it("shows the connector brand logo in the memory connector dropdown", async () => {+ render(<MemoryPage />);+ const trigger = await screen.findByLabelText("Memory connector");+ fireEvent.click(trigger);+ await waitFor(() => {+ expect(+ document.querySelectorAll('img[src="/images/connectors/mem0.svg"]').length+ ).toBeGreaterThan(0);+ });+ });++ it("opens the add-connector dialog on the memory page", async () => {+ render(<MemoryPage />);+ const addConnector = await screen.findByRole("button", { name: "Add connector" });+ fireEvent.click(addConnector);+ expect(screen.getByTestId("source-form-dialog")).toBeInTheDocument();+ expect(replaceMock).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(+ (global.fetch as jest.Mock).mock.calls.some(+ ([url]: [RequestInfo]) => String(url) === "/api/connectors/types"+ )+ ).toBe(true)+ );+ });++ it("refreshes the list after adding a memory", async () => {+ const memories = [...payload.memories];+ (global.fetch as jest.Mock).mockImplementation(+ async (input: RequestInfo, init?: RequestInit) => {+ const url = String(input);+ const method = init?.method || "GET";+ if (url === "/api/memory" && method === "POST") {+ const created = {+ id: "mem-new",+ content: "remember this",+ kind: "temporal",+ };+ memories.unshift(created);+ return {+ ok: true,+ json: async () => ({ memories: [created] }),+ };+ }+ if (url.startsWith("/api/memory")) {+ return {+ ok: true,+ json: async () => ({+ ...payload,+ capabilities: {+ add: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ },+ memories: [...memories],+ stats: { ...payload.stats, total: memories.length },+ }),+ };+ }+ return { ok: true, json: async () => ({ types: [] }) };+ }+ );+ render(<MemoryPage />);+ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Add memory" })).toBeEnabled()+ );+ fireEvent.click(screen.getByRole("button", { name: "Add memory" }));+ fireEvent.click(screen.getByTestId("write-submit"));+ await waitFor(() =>+ expect(screen.getByText("remember this")).toBeInTheDocument()+ );+ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Load" })).toBeEnabled()+ );+ const calls = (global.fetch as jest.Mock).mock.calls.map(+ ([url, init]: [RequestInfo, RequestInit?]) => [+ String(url),+ init?.method || "GET",+ ]+ );+ const postIndex = calls.findIndex(+ ([url, method]) => url === "/api/memory" && method === "POST"+ );+ expect(postIndex).toBeGreaterThanOrEqual(0);+ expect(+ calls+ .slice(postIndex + 1)+ .some(([url, method]) => url.startsWith("/api/memory?") && method === "GET")+ ).toBe(true);+ });+});diff --git a/src/client/src/__tests__/components/memory-write-dialog.test.tsx b/src/client/src/__tests__/components/memory-write-dialog.test.tsxnew file mode 100644index 00000000..873fdc57--- /dev/null+++ b/src/client/src/__tests__/components/memory-write-dialog.test.tsx@@ -0,0 +1,108 @@+import { fireEvent, render, screen } from "@testing-library/react";+import MemoryWriteDialog from "@/components/(playground)/memory/memory-write-dialog";++class ResizeObserverMock {+ observe() {}+ unobserve() {}+ disconnect() {}+}+Object.defineProperty(global, "ResizeObserver", {+ writable: true,+ value: ResizeObserverMock,+});+Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {+ writable: true,+ value: jest.fn(),+});++describe("MemoryWriteDialog", () => {+ const filterFields = [+ { key: "userId" as const, label: "User", required: true, allowCustom: true },+ {+ key: "sessionId" as const,+ label: "Session",+ writeRequired: true,+ allowCustom: true,+ },+ ];+ const filters = {+ users: [{ id: "ada", label: "[email protected]" }],+ sessions: [{ id: "thread-1", label: "thread-1", userId: "ada" }],+ agents: [],+ };++ it("shows the same user and session comboboxes as the memory filters", () => {+ render(+ <MemoryWriteDialog+ open+ mode="add"+ scope={{ userId: "ada", sessionId: "thread-1" }}+ filterFields={filterFields}+ filters={filters}+ onOpenChange={jest.fn()}+ onSubmit={jest.fn()}+ />+ );+ expect(screen.getByLabelText("User")).toHaveTextContent("[email protected]");+ expect(screen.getByLabelText("Session")).toHaveTextContent("thread-1");+ });++ it("swaps reversed Zep user and session values", () => {+ render(+ <MemoryWriteDialog+ open+ mode="add"+ scope={{ userId: "thread-1", sessionId: "ada" }}+ filterFields={filterFields}+ filters={filters}+ onOpenChange={jest.fn()}+ onSubmit={jest.fn()}+ />+ );+ expect(screen.getByLabelText("User")).toHaveTextContent("[email protected]");+ expect(screen.getByLabelText("Session")).toHaveTextContent("thread-1");+ });++ it("submits userId and sessionId on their own fields", () => {+ const onSubmit = jest.fn();+ render(+ <MemoryWriteDialog+ open+ mode="add"+ scope={{ userId: "ada", sessionId: "thread-1" }}+ filterFields={filterFields}+ filters={filters}+ onOpenChange={jest.fn()}+ onSubmit={onSubmit}+ />+ );+ fireEvent.change(screen.getByPlaceholderText("What should this connector remember?"), {+ target: { value: "Prefers tabs" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Save memory" }));+ expect(onSubmit).toHaveBeenCalledWith({+ content: "Prefers tabs",+ userId: "ada",+ sessionId: "thread-1",+ agentId: undefined,+ });+ });++ it("does not put the selected email into the filter search box", () => {+ render(+ <MemoryWriteDialog+ open+ mode="add"+ scope={{ userId: "ada", sessionId: "thread-1" }}+ filterFields={filterFields}+ filters={filters}+ onOpenChange={jest.fn()}+ onSubmit={jest.fn()}+ />+ );+ fireEvent.click(screen.getByLabelText("User"));+ const search = screen.getByPlaceholderText("Type a value and press Enter.");+ expect(search).toHaveValue("");+ expect(screen.getAllByTitle("[email protected]").length).toBeGreaterThan(1);+ });+});diff --git a/src/client/src/__tests__/constants/events.test.ts b/src/client/src/__tests__/constants/events.test.tsindex 5d06d580..59aa7526 100644--- a/src/client/src/__tests__/constants/events.test.ts+++ b/src/client/src/__tests__/constants/events.test.ts@@ -129,6 +129,7 @@ describe("CLIENT_EVENTS", () => {expect(CLIENT_EVENTS.OTTER_CHAT_PAGE_VISITED).toBe("OTTER_CHAT_PAGE_VISITED");+ expect(CLIENT_EVENTS.MEMORY_PAGE_VISITED).toBe("MEMORY_PAGE_VISITED");expect(CLIENT_EVENTS.OTTER_CHAT_MESSAGE_SENT).toBe("OTTER_CHAT_MESSAGE_SENT");diff --git a/src/client/src/__tests__/lib/access/memory-route.test.ts b/src/client/src/__tests__/lib/access/memory-route.test.tsnew file mode 100644index 00000000..700f4f60--- /dev/null+++ b/src/client/src/__tests__/lib/access/memory-route.test.ts@@ -0,0 +1,29 @@+import {+ recordMemoryMutationAudit,+ requireMemoryAccess,+ withMemoryAccess,+ withMemoryAudit,+} from "@/lib/access/memory-route";++describe("CE memory route fallback", () => {+ it("keeps handlers unchanged", async () => {+ const handler = jest.fn().mockResolvedValue({ status: 204 });+ const wrapped = withMemoryAudit(withMemoryAccess("create", handler));++ await wrapped({} as Request);++ expect(handler).toHaveBeenCalledTimes(1);+ expect(wrapped).toBe(handler);+ });++ it("allows library callers without enforcing RBAC or audit", async () => {+ await expect(requireMemoryAccess("delete")).resolves.toBeUndefined();+ await expect(+ recordMemoryMutationAudit({+ action: "create",+ targetId: "m1",+ contentLength: 12,+ })+ ).resolves.toBeUndefined();+ });+});diff --git a/src/client/src/__tests__/lib/audit/route.test.ts b/src/client/src/__tests__/lib/audit/route.test.tsindex ea4be071..82cdcb21 100644--- a/src/client/src/__tests__/lib/audit/route.test.ts+++ b/src/client/src/__tests__/lib/audit/route.test.ts@@ -10,7 +10,7 @@ beforeAll(() => {});});-import { withAudit } from "@/lib/audit/route";+import { recordAuditEvent, withAudit } from "@/lib/audit/route";describe("CE audit route fallback", () => {it("withAudit returns the handler unchanged", async () => {@@ -21,4 +21,10 @@ describe("CE audit route fallback", () => {await wrapped({} as Request, {});expect(handler).toHaveBeenCalledTimes(1);});++ it("recordAuditEvent is a no-op", async () => {+ await expect(+ recordAuditEvent({ action: "memory.created", targetId: "m1" })+ ).resolves.toBeUndefined();+ });});diff --git a/src/client/src/__tests__/lib/platform/chat/schema-context.test.ts b/src/client/src/__tests__/lib/platform/chat/schema-context.test.tsindex 668d5d9e..f386303b 100644--- a/src/client/src/__tests__/lib/platform/chat/schema-context.test.ts+++ b/src/client/src/__tests__/lib/platform/chat/schema-context.test.ts@@ -43,6 +43,11 @@ describe('getChatSystemPrompt', () => {expect(prompt).toContain('create_prompt');expect(prompt).toContain('create_vault_secret');expect(prompt).toContain('create_custom_model');+ expect(prompt).toContain('list_memories');+ expect(prompt).toContain('search_memories');+ expect(prompt).toContain('add_memory');+ expect(prompt).toContain('update_memory');+ expect(prompt).toContain('delete_memory');});it('includes entity links section', () => {@@ -50,6 +55,7 @@ describe('getChatSystemPrompt', () => {expect(prompt).toContain('/rule-engine/{id}');expect(prompt).toContain('/context/{id}');expect(prompt).toContain('/prompt-hub/{id}');+ expect(prompt).toContain('/memory?id={id}&connectorId={connectorId}');});it('includes dashboard generation section', () => {diff --git a/src/client/src/__tests__/lib/platform/chat/tools.test.ts b/src/client/src/__tests__/lib/platform/chat/tools.test.tsindex 2f009c48..749c6f6d 100644--- a/src/client/src/__tests__/lib/platform/chat/tools.test.ts+++ b/src/client/src/__tests__/lib/platform/chat/tools.test.ts@@ -84,6 +84,26 @@ jest.mock("@/lib/telemetry-source", () => ({resolveSignalSource: (...args: unknown[]) => mockResolveSignalSource(...args),}));+const mockQueryProjectMemories = jest.fn();+const mockAddProjectMemories = jest.fn();+const mockUpdateProjectMemory = jest.fn();+const mockDeleteProjectMemory = jest.fn();+const mockRequireMemoryAccess = jest.fn().mockResolvedValue(undefined);+const mockRecordMemoryMutationAudit = jest.fn().mockResolvedValue(undefined);+jest.mock("@/lib/platform/connectors/memory/read", () => ({+ queryProjectMemories: (...args: unknown[]) => mockQueryProjectMemories(...args),+}));+jest.mock("@/lib/platform/connectors/memory/write", () => ({+ addProjectMemories: (...args: unknown[]) => mockAddProjectMemories(...args),+ updateProjectMemory: (...args: unknown[]) => mockUpdateProjectMemory(...args),+ deleteProjectMemory: (...args: unknown[]) => mockDeleteProjectMemory(...args),+}));+jest.mock("@/lib/access/memory-route", () => ({+ requireMemoryAccess: (...args: unknown[]) => mockRequireMemoryAccess(...args),+ recordMemoryMutationAudit: (...args: unknown[]) =>+ mockRecordMemoryMutationAudit(...args),+}));+jest.mock("@/utils/sanitizer", () => ({__esModule: true,default: {@@ -146,6 +166,8 @@ function ndjsonResponse(payload: string) {describe("getChatTools", () => {beforeEach(() => {jest.clearAllMocks();+ mockRequireMemoryAccess.mockResolvedValue(undefined);+ mockRecordMemoryMutationAudit.mockResolvedValue(undefined);});it("builds the expected tool set", () => {@@ -167,6 +189,11 @@ describe("getChatTools", () => {"analyze_traces_by_attribute","get_telemetry_routing","query_telemetry",+ "list_memories",+ "search_memories",+ "add_memory",+ "update_memory",+ "delete_memory",]));expect(tools.create_rule.inputSchema.required).toEqual(["name"]);@@ -1400,4 +1427,119 @@ describe("getChatTools", () => {expect(batch.limitApplied).toBe(true);expect(batch.results[0].success).toBe(true);});++ it("lists and searches memories through the memory connector facade", async () => {+ mockQueryProjectMemories.mockResolvedValue({+ connector: {+ id: "memory:abc",+ name: "Prod Mem0",+ type: "mem0",+ environment: "production",+ },+ memories: [+ {+ id: "m1",+ content: "x".repeat(300),+ userId: "ada",+ kind: "summary",+ },+ ],+ stats: { total: 1 },+ });+ const tools = getChatTools("user-1", "db-1") as any;++ const listed = await tools.list_memories.execute({ user_id: "ada" });+ expect(listed.success).toBe(true);+ expect(listed.memories[0].content.endsWith("…")).toBe(true);+ expect(listed.memories[0].url).toBe("/memory?id=m1&connectorId=memory%3Aabc");+ expect(mockRequireMemoryAccess).toHaveBeenCalledWith("read");+ expect(mockQueryProjectMemories).toHaveBeenCalledWith(+ expect.objectContaining({ userId: "ada" })+ );++ await tools.search_memories.execute({ query: "tracing" });+ expect(mockQueryProjectMemories).toHaveBeenCalledWith(+ expect.objectContaining({ query: "tracing" })+ );+ expect(tools.search_memories.inputSchema.required).toEqual(["query"]);+ });++ it("adds, updates, and deletes memories through the write facade", async () => {+ mockAddProjectMemories.mockResolvedValue({+ connector: { id: "memory:abc", name: "Prod Mem0", type: "mem0" },+ memories: [{ id: "m1", content: "Prefers tabs", userId: "ada" }],+ });+ mockUpdateProjectMemory.mockResolvedValue({+ connector: { id: "memory:abc" },+ memory: { id: "m1", content: "Prefers spaces" },+ });+ mockDeleteProjectMemory.mockResolvedValue({+ connector: { id: "memory:abc" },+ ok: true,+ });+ const tools = getChatTools("user-1", "db-1") as any;++ const added = await tools.add_memory.execute({+ content: "Prefers tabs",+ user_id: "ada",+ });+ expect(added.success).toBe(true);+ expect(added.url).toBe("/memory?id=m1&connectorId=memory%3Aabc");+ expect(mockRequireMemoryAccess).toHaveBeenCalledWith("create");+ expect(mockAddProjectMemories).toHaveBeenCalledWith(+ expect.objectContaining({ content: "Prefers tabs", userId: "ada" })+ );+ expect(mockRecordMemoryMutationAudit).toHaveBeenCalledWith(+ expect.objectContaining({+ action: "create",+ targetId: "m1",+ connectorId: "memory:abc",+ userId: "ada",+ contentLength: "Prefers tabs".length,+ source: "chat",+ })+ );+ expect(mockRecordMemoryMutationAudit.mock.calls[0][0]).not.toHaveProperty(+ "content"+ );+ expect(tools.add_memory.inputSchema.required).toEqual(["content"]);++ const updated = await tools.update_memory.execute({+ id: "m1",+ content: "Prefers spaces",+ });+ expect(updated.success).toBe(true);+ expect(mockRequireMemoryAccess).toHaveBeenCalledWith("update");+ expect(mockUpdateProjectMemory).toHaveBeenCalledWith({+ id: "m1",+ content: "Prefers spaces",+ connectorId: undefined,+ });++ const removed = await tools.delete_memory.execute({ id: "m1" });+ expect(removed.success).toBe(true);+ expect(mockRequireMemoryAccess).toHaveBeenCalledWith("delete");+ expect(mockDeleteProjectMemory).toHaveBeenCalledWith({+ id: "m1",+ connectorId: undefined,+ });+ expect(mockRecordMemoryMutationAudit).toHaveBeenCalledWith(+ expect.objectContaining({ action: "delete", targetId: "m1", source: "chat" })+ );+ });++ it("blocks Otter memory mutations when access is denied", async () => {+ mockRequireMemoryAccess.mockRejectedValueOnce(+ new Error("You do not have permission to perform this action.")+ );+ const tools = getChatTools("user-1", "db-1") as any;++ const added = await tools.add_memory.execute({ content: "secret" });+ expect(added).toEqual({+ success: false,+ error: "You do not have permission to perform this action.",+ });+ expect(mockAddProjectMemories).not.toHaveBeenCalled();+ expect(mockRecordMemoryMutationAudit).not.toHaveBeenCalled();+ });});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.tsnew file mode 100644index 00000000..4a8723e5--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/memory-adapters.test.ts@@ -0,0 +1,896 @@+jest.mock("@/lib/platform/connectors/datasource/http/safe-fetch", () => {+ class SourceResponseError extends Error {+ status: number;+ constructor(status: number, message: string) {+ super(message);+ this.name = "SourceResponseError";+ this.status = status;+ }+ }+ return {+ safeFetch: (...args: unknown[]) => mockSafeFetch(...args),+ selfHostedNetworkOptions: () => ({ allowHttp: true, allowPrivateNetwork: true }),+ SourceResponseError,+ };+});+jest.mock("@/lib/platform/connectors/datasource/http/secret", () => ({+ resolveSourceSecret: jest.fn().mockResolvedValue({+ raw: "secret-key",+ credentials: { apiKey: "secret-key" },+ }),+ redactableSecretValues: (secret: { raw?: string; credentials?: Record<string, string> }) =>+ [secret.raw, ...Object.values(secret.credentials || {})].filter(Boolean),+}));++const mockSafeFetch = jest.fn();++import { ClaudeAdapter, claudeAdapterFactory } from "@/lib/platform/connectors/memory/claude/adapter";+import { 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 type { MemorySourceDescriptor } from "@/lib/platform/connectors/memory/types";++function defaultUrl(type: "claude" | "mem0" | "zep"): string {+ if (type === "claude") return "https://api.anthropic.com";+ if (type === "mem0") return "https://api.mem0.ai";+ return "https://api.getzep.com";+}++function descriptor(+ type: "claude" | "mem0" | "zep",+ settings: Record<string, unknown> = {}+): MemorySourceDescriptor {+ return {+ type,+ id: `memory:${type}`,+ settings: {+ url: defaultUrl(type),+ ...settings,+ },+ secretRef: "vault-1",+ name: type,+ projectId: "proj-1",+ };+}++beforeEach(() => {+ mockSafeFetch.mockReset();+});++describe("Mem0 adapter", () => {+ it("describes a self-contained config schema", () => {+ const described = mem0AdapterFactory.describe();+ expect(described.type).toBe("mem0");+ expect(described.capabilities).toEqual({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: true,+ });+ expect(described.configFields.map((field) => field.key)).toEqual(+ expect.arrayContaining(["url", "apiKey", "orgId", "projectId"])+ );+ expect(described.configFields.find((field) => field.key === "apiKey")?.group).toBe(+ "credentials"+ );+ expect(described.filterFields?.map((field) => field.key)).toEqual([+ "userId",+ "sessionId",+ "agentId",+ ]);+ expect(described.filterFields?.[1]).toMatchObject({+ key: "sessionId",+ label: "Run",+ });+ });++ it("health-checks entities and sends Token auth", async () => {+ mockSafeFetch.mockResolvedValue({ results: [] });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.healthCheck()).resolves.toEqual(+ expect.objectContaining({ ok: true })+ );+ const [url, options] = mockSafeFetch.mock.calls[0];+ expect(String(url)).toContain("https://api.mem0.ai/v1/entities/");+ expect(options.headers.Authorization).toBe("Token secret-key");+ });++ it("adds a memory from content and normalizes the response", async () => {+ mockSafeFetch.mockResolvedValue({+ results: [{ id: "mem-1", memory: "User likes tea", user_id: "u1" }],+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ const records = await adapter.add({ content: "User likes tea", userId: "u1" });+ expect(records).toEqual([+ expect.objectContaining({ id: "mem-1", content: "User likes tea", userId: "u1" }),+ ]);+ const [, options] = mockSafeFetch.mock.calls[0];+ expect(options.method).toBe("POST");+ expect(JSON.parse(options.body)).toEqual(+ expect.objectContaining({+ messages: [{ role: "user", content: "User likes tea" }],+ user_id: "u1",+ })+ );+ });++ it("searches memories through the v2 search API", async () => {+ mockSafeFetch.mockResolvedValue({+ results: [{ id: "mem-1", memory: "tea", score: 0.9 }],+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ const records = await adapter.search({ query: "tea", userId: "u1", limit: 5 });+ expect(records[0]).toEqual(expect.objectContaining({ id: "mem-1", score: 0.9 }));+ const [url, options] = mockSafeFetch.mock.calls[0];+ expect(String(url)).toContain("/v2/memories/search/");+ expect(JSON.parse(options.body)).toEqual(+ expect.objectContaining({+ query: "tea",+ filters: { user_id: "u1" },+ top_k: 5,+ })+ );+ });++ it("ORs multiple entity filters when searching", async () => {+ mockSafeFetch.mockResolvedValue({ results: [] });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await adapter.search({ query: "tea", userId: "u1", agentId: "researcher" });+ expect(JSON.parse(mockSafeFetch.mock.calls[0][1].body)).toEqual(+ expect.objectContaining({+ filters: { OR: [{ user_id: "u1" }, { agent_id: "researcher" }] },+ })+ );+ });++ it("does not list memories until a user, agent, or session is provided", async () => {+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.list({})).rejects.toThrow(/user, agent, or session/i);+ expect(mockSafeFetch).not.toHaveBeenCalled();+ });++ it("lists memories through the v3 filters API", async () => {+ mockSafeFetch.mockResolvedValue({+ count: 1,+ results: [{ id: "mem-1", memory: "likes tea", user_id: "u1", run_id: "run-9" }],+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ const records = await adapter.list({ userId: "u1", sessionId: "run-9", limit: 10 });+ expect(records).toEqual([+ expect.objectContaining({+ id: "mem-1",+ content: "likes tea",+ userId: "u1",+ sessionId: "run-9",+ }),+ ]);+ const [url, options] = mockSafeFetch.mock.calls[0];+ expect(String(url)).toContain("/v3/memories/?page=1&page_size=10");+ expect(options.method).toBe("POST");+ expect(JSON.parse(options.body)).toEqual(+ expect.objectContaining({+ filters: { OR: [{ user_id: "u1" }, { run_id: "run-9" }] },+ })+ );+ });++ it("lists filter options from entities", async () => {+ mockSafeFetch.mockResolvedValue({+ results: [+ { id: "e1", name: "ada", type: "user", email: "[email protected]" },+ { name: "run-9", type: "run" },+ { name: "researcher", entity_type: "agent" },+ ],+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.listFilters()).resolves.toEqual({+ users: [{ id: "ada", label: "[email protected]" }],+ sessions: [{ id: "run-9", label: "run-9" }],+ agents: [{ id: "researcher", label: "researcher" }],+ });+ expect(String(mockSafeFetch.mock.calls[0][0])).toContain("/v1/entities/");+ });++ it("gets a memory by id including categories, input, and history", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) {+ return [+ {+ id: "h1",+ event: "ADD",+ new_memory: "User's name is Alex",+ input: [{ role: "user", content: "I'm Alex" }],+ created_at: "2026-08-15T02:17:47Z",+ },+ ];+ }+ return {+ id: "mem-1",+ memory: "User's name is Alex",+ user_id: "alex",+ categories: ["personal_details", "health"],+ created_at: "2026-08-15T02:17:47Z",+ updated_at: "2026-08-15T02:18:27Z",+ metadata: { memory_type: "profile" },+ };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-1")).resolves.toEqual(+ expect.objectContaining({+ id: "mem-1",+ content: "User's name is Alex",+ userId: "alex",+ categories: ["personal_details", "health"],+ input: [{ role: "user", content: "I'm Alex" }],+ history: [+ expect.objectContaining({+ id: "h1",+ event: "ADD",+ newMemory: "User's name is Alex",+ }),+ ],+ })+ );+ expect(String(mockSafeFetch.mock.calls[0][0])).toBe(+ "https://api.mem0.ai/v1/memories/mem-1/"+ );+ expect(String(mockSafeFetch.mock.calls[1][0])).toBe(+ "https://api.mem0.ai/v1/memories/mem-1/history/"+ );+ });++ it("retries get without a trailing slash after a redirect budget error", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ const href = String(url);+ if (href.endsWith("/mem-1/")) {+ throw new Error("Data source exceeded the maximum number of redirects");+ }+ if (href.includes("/history")) {+ return [];+ }+ if (href.endsWith("/mem-1")) {+ return { id: "mem-1", memory: "hello", user_id: "alex" };+ }+ throw new Error(`unexpected ${href}`);+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-1")).resolves.toEqual(+ expect.objectContaining({+ id: "mem-1",+ content: "hello",+ userId: "alex",+ })+ );+ expect(String(mockSafeFetch.mock.calls[0][0])).toBe(+ "https://api.mem0.ai/v1/memories/mem-1/"+ );+ expect(String(mockSafeFetch.mock.calls[1][0])).toBe(+ "https://api.mem0.ai/v1/memories/mem-1"+ );+ });++ it("still returns a memory when history cannot be loaded", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) {+ throw new Error("history unavailable");+ }+ return { id: "mem-1", memory: "hello", user_id: "alex" };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-1")).resolves.toEqual(+ expect.objectContaining({+ id: "mem-1",+ content: "hello",+ userId: "alex",+ })+ );+ });++ it("submits and clears memory feedback through the v1 feedback API", async () => {+ mockSafeFetch.mockResolvedValue({+ id: "fb-1",+ feedback: "NEGATIVE",+ feedback_reason: "Outdated",+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(+ adapter.feedback("mem-1", { rating: "negative", reason: "Outdated" })+ ).resolves.toEqual({+ rating: "negative",+ reason: "Outdated",+ });+ const [url, options] = mockSafeFetch.mock.calls[0];+ expect(String(url)).toBe("https://api.mem0.ai/v1/feedback/");+ expect(options.method).toBe("POST");+ expect(JSON.parse(options.body)).toEqual({+ memory_id: "mem-1",+ feedback: "NEGATIVE",+ feedback_reason: "Outdated",+ });++ mockSafeFetch.mockResolvedValue({ id: "fb-1", feedback: null, feedback_reason: null });+ await expect(adapter.feedback("mem-1", { rating: null })).resolves.toEqual({});+ expect(JSON.parse(mockSafeFetch.mock.calls[1][1].body)).toEqual({+ memory_id: "mem-1",+ feedback: null,+ feedback_reason: null,+ });+ });++ it("reads existing feedback from a memory payload", async () => {+ mockSafeFetch.mockImplementation(async (url: string) => {+ if (String(url).includes("/history")) return [];+ return {+ id: "mem-1",+ memory: "hello",+ feedback: "POSITIVE",+ feedback_reason: "Accurate",+ };+ });+ const adapter = new Mem0Adapter(descriptor("mem0"));+ await expect(adapter.get("mem-1")).resolves.toEqual(+ expect.objectContaining({+ id: "mem-1",+ feedback: { rating: "positive", reason: "Accurate" },+ })+ );+ });+});++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");+ });+});++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",+ });+ });+});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.tsnew file mode 100644index 00000000..8d9f8b93--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/memory-ask.test.ts@@ -0,0 +1,74 @@+import { buildMemoryAskPrompt, memoryAskSelectedSummary } from "@/lib/platform/connectors/memory/ask";+import {+ MEMORY_ASK_FALLBACK_PROMPT,+ MEMORY_ASK_OTTER_PROMPT,+ MEMORY_ASK_SELECTED_PROMPT,+ MEMORY_ASK_TOOLS_PROMPT,+} from "@/constants/messages/en";++describe("buildMemoryAskPrompt", () => {+ it("stays compact and only passes filters the connector declares", () => {+ const prompt = buildMemoryAskPrompt("What does Ada prefer?", {+ connectorId: "memory:abc",+ userId: "ada",+ sessionId: "run-9",+ agentId: "bot",+ filterKeys: ["userId", "sessionId", "agentId"],+ canList: true,+ canSearch: true,+ });+ expect(prompt).toContain(MEMORY_ASK_TOOLS_PROMPT);+ expect(prompt).toContain(MEMORY_ASK_OTTER_PROMPT);+ expect(prompt).toContain("connector_id=memory:abc");+ expect(prompt).toContain("user_id=ada");+ expect(prompt).toContain("session_id=run-9");+ expect(prompt).toContain("agent_id=bot");+ expect(prompt).toContain("What does Ada prefer?");+ expect(prompt.split("\n").length).toBeLessThan(10);+ });++ it("omits user_id for store-scoped connectors like Claude", () => {+ const prompt = buildMemoryAskPrompt("what is remembered?", {+ connectorId: "memory:claude",+ userId: "alex",+ sessionId: "memstore_1",+ filterKeys: ["sessionId"],+ canList: true,+ canSearch: true,+ });+ expect(prompt).toContain("session_id=memstore_1");+ expect(prompt).not.toContain("user_id=");+ expect(prompt).toContain("what is remembered?");+ });++ it("includes a short selected-memory hint only", () => {+ const prompt = buildMemoryAskPrompt("Summarize this", {+ memoryId: "mem-1",+ memoryContent: "User visited New York",+ canList: true,+ filterKeys: ["sessionId"],+ });+ expect(prompt).toContain(+ MEMORY_ASK_SELECTED_PROMPT("mem-1", "User visited New York")+ );+ expect(+ memoryAskSelectedSummary({+ memoryId: "mem-1",+ memoryContent: "User visited New York",+ })+ ).toBe("User visited New York");+ });++ it("falls back when the connector has no list/search API", () => {+ const prompt = buildMemoryAskPrompt("who are my users?", {+ connectorId: "memory:1",+ filterKeys: ["userId"],+ userId: "alex",+ canList: false,+ canSearch: false,+ });+ expect(prompt).toContain(MEMORY_ASK_FALLBACK_PROMPT);+ expect(prompt).not.toContain(MEMORY_ASK_TOOLS_PROMPT);+ expect(prompt).toContain("user_id=alex");+ });+});diff --git a/src/client/src/__tests__/lib/platform/connectors/memory-bootstrap.test.ts b/src/client/src/__tests__/lib/platform/connectors/memory-bootstrap.test.tsnew file mode 100644index 00000000..e3a23dab--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/memory-bootstrap.test.ts@@ -0,0 +1,81 @@+import {+ __resetMemoryBootstrapForTests,+ ensureMemoryAdaptersRegistered,+} from "@/lib/platform/connectors/memory/bootstrap";+import {+ __resetMemoryRegistryForTests,+ createMemoryAdapter,+ hasMemoryAdapterFactory,+ listMemoryTypeDescriptors,+} from "@/lib/platform/connectors/memory/registry";+import {+ __resetConnectorRegistryForTests,+ listConnectorTypes,+} from "@/lib/platform/connectors/registry";+import { Mem0Adapter } from "@/lib/platform/connectors/memory/mem0/adapter";+import type { MemorySourceDescriptor } from "@/lib/platform/connectors/memory/types";++jest.mock("@/lib/session", () => ({ getCurrentUser: jest.fn() }));++beforeEach(() => {+ __resetMemoryRegistryForTests();+ __resetMemoryBootstrapForTests();+ __resetConnectorRegistryForTests();+});++describe("memory connector bootstrap", () => {+ it("registers Claude, Mem0, and Zep exactly once", () => {+ ensureMemoryAdaptersRegistered();+ ensureMemoryAdaptersRegistered();+ expect(hasMemoryAdapterFactory("claude")).toBe(true);+ expect(hasMemoryAdapterFactory("mem0")).toBe(true);+ expect(hasMemoryAdapterFactory("zep")).toBe(true);+ expect(listMemoryTypeDescriptors().map((item) => item.type).sort()).toEqual([+ "claude",+ "mem0",+ "zep",+ ]);+ });++ it("creates a Mem0 adapter from a descriptor", () => {+ ensureMemoryAdaptersRegistered();+ const descriptor: MemorySourceDescriptor = {+ type: "mem0",+ id: "memory:1",+ settings: { url: "https://api.mem0.ai" },+ name: "Mem0",+ };+ expect(createMemoryAdapter(descriptor)).toBeInstanceOf(Mem0Adapter);+ });++ it("re-registers after the registry Map is cleared", () => {+ ensureMemoryAdaptersRegistered();+ __resetMemoryRegistryForTests();+ expect(hasMemoryAdapterFactory("mem0")).toBe(false);+ ensureMemoryAdaptersRegistered();+ expect(hasMemoryAdapterFactory("mem0")).toBe(true);+ });++ it("exposes memory types through the generic connector registry", () => {+ ensureMemoryAdaptersRegistered();+ expect(listConnectorTypes("memory").map((item) => item.type).sort()).toEqual([+ "claude",+ "mem0",+ "zep",+ ]);+ expect(listConnectorTypes("datasource")).toHaveLength(0);+ });++ it("every registered type exposes a valid config schema", () => {+ ensureMemoryAdaptersRegistered();+ for (const descriptor of listMemoryTypeDescriptors()) {+ expect(descriptor.configFields.length).toBeGreaterThan(0);+ for (const field of descriptor.configFields) {+ expect(field.key).toBeTruthy();+ expect(field.label).toBeTruthy();+ expect(["settings", "credentials"]).toContain(field.group);+ }+ expect(descriptor.authStyle).toBe("api-key");+ }+ });+});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.tsnew file mode 100644index 00000000..2934be0b--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/memory-copy.test.ts@@ -0,0 +1,167 @@+const mockListMemoryConnectors = jest.fn();+const mockRecordMemoryPortLinks = jest.fn();+const mockQueryProjectMemories = jest.fn();+const mockAddProjectMemories = jest.fn();+const mockGetMemoryTypeDescriptor = jest.fn();++jest.mock("@/lib/platform/connectors/memory/crud", () => ({+ listMemoryConnectors: (...a: unknown[]) => mockListMemoryConnectors(...a),+ recordMemoryPortLinks: (...a: unknown[]) => mockRecordMemoryPortLinks(...a),+ memoryConnectorId: (id: string) =>+ String(id).startsWith("memory:") ? id : `memory:${id}`,+}));+jest.mock("@/lib/platform/connectors/memory/read", () => ({+ queryProjectMemories: (...a: unknown[]) => mockQueryProjectMemories(...a),+}));+jest.mock("@/lib/platform/connectors/memory/write", () => ({+ addProjectMemories: (...a: unknown[]) => mockAddProjectMemories(...a),+}));+jest.mock("@/lib/platform/connectors/memory/registry", () => ({+ getMemoryTypeDescriptor: (...a: unknown[]) => mockGetMemoryTypeDescriptor(...a),+}));++import { copyProjectMemories } from "@/lib/platform/connectors/memory/port";+import {+ MEMORY_ADD_UNSUPPORTED,+ MEMORY_COPY_EMPTY,+ MEMORY_COPY_SAME_CONNECTOR,+} from "@/constants/messages/en";++const source = { id: "memory:src", name: "Mem0", type: "mem0" };+const target = { id: "memory:dst", name: "Zep", type: "zep" };++describe("copyProjectMemories", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockListMemoryConnectors.mockResolvedValue([source, target]);+ mockGetMemoryTypeDescriptor.mockReturnValue({+ capabilities: { add: true },+ });+ mockRecordMemoryPortLinks.mockResolvedValue(undefined);+ });++ it("rejects copying a connector onto itself", async () => {+ await expect(+ copyProjectMemories({+ sourceConnectorId: "memory:src",+ targetConnectorId: "memory:src",+ })+ ).rejects.toThrow(MEMORY_COPY_SAME_CONNECTOR);+ });++ it("rejects destinations that cannot add memories", async () => {+ mockGetMemoryTypeDescriptor.mockReturnValue({+ capabilities: { add: false },+ });+ await expect(+ copyProjectMemories({+ sourceConnectorId: "memory:src",+ targetConnectorId: "memory:dst",+ })+ ).rejects.toThrow(MEMORY_ADD_UNSUPPORTED);+ });++ it("copies selected memories with a stored source link", 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(result.failed).toEqual([]);+ expect(result.memories[0].port).toEqual(+ expect.objectContaining({+ sourceConnectorId: "memory:src",+ sourceMemoryId: "m1",+ sourceConnectorName: "Mem0",+ destMemoryId: "z1",+ })+ );+ expect(mockAddProjectMemories).toHaveBeenCalledWith(+ expect.objectContaining({+ connectorId: "memory:dst",+ content: "Prefers tabs",+ userId: "ada",+ metadata: expect.objectContaining({+ openlit: expect.objectContaining({+ port: expect.objectContaining({ sourceMemoryId: "m1" }),+ }),+ }),+ })+ );+ expect(mockRecordMemoryPortLinks).toHaveBeenCalledWith(+ "memory:dst",+ expect.arrayContaining([+ expect.objectContaining({ sourceMemoryId: "m1", destMemoryId: "z1" }),+ ])+ );+ });++ it("keeps the original source when copying an already-ported memory", async () => {+ mockListMemoryConnectors.mockResolvedValue([+ source,+ target,+ { id: "memory:claude", name: "Claude", type: "claude" },+ ]);+ mockQueryProjectMemories.mockResolvedValue({+ memories: [+ {+ id: "z1",+ content: "Prefers tabs",+ userId: "ada",+ kind: "profile",+ metadata: {+ openlit: {+ port: {+ sourceConnectorId: "memory:src",+ sourceMemoryId: "m1",+ originConnectorId: "memory:origin",+ originMemoryId: "o1",+ },+ },+ },+ },+ ],+ });+ mockAddProjectMemories.mockResolvedValue({+ memories: [{ id: "c1", content: "Prefers tabs", userId: "ada", kind: "profile" }],+ });++ const result = await copyProjectMemories({+ sourceConnectorId: "memory:dst",+ targetConnectorId: "memory:claude",+ memoryIds: ["z1"],+ });++ expect(result.memories[0].port).toEqual(+ expect.objectContaining({+ sourceConnectorId: "memory:dst",+ sourceMemoryId: "z1",+ originConnectorId: "memory:origin",+ originMemoryId: "o1",+ destMemoryId: "c1",+ })+ );+ });++ it("fails when nothing is selected", async () => {+ mockQueryProjectMemories.mockResolvedValue({ memories: [] });+ await expect(+ copyProjectMemories({+ sourceConnectorId: "memory:src",+ targetConnectorId: "memory:dst",+ })+ ).rejects.toThrow(MEMORY_COPY_EMPTY);+ });+});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.tsnew file mode 100644index 00000000..af6d7628--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/memory-crud.test.ts@@ -0,0 +1,287 @@+const mockFindFirst = jest.fn();+const mockFindMany = jest.fn();+const mockCreate = jest.fn();+const mockUpdate = jest.fn();+const mockDelete = jest.fn();+const mockGetCurrentOrganisation = jest.fn();+const mockGetCurrentProjectForOrganisation = jest.fn();+const mockHasMemoryAdapterFactory = jest.fn();+const mockGetMemoryTypeDescriptor = jest.fn();+const mockCreateMemoryAdapter = jest.fn();++jest.mock("@/lib/prisma", () => ({+ __esModule: true,+ default: {+ connectorInstance: {+ findFirst: (...a: unknown[]) => mockFindFirst(...a),+ findMany: (...a: unknown[]) => mockFindMany(...a),+ create: (...a: unknown[]) => mockCreate(...a),+ update: (...a: unknown[]) => mockUpdate(...a),+ delete: (...a: unknown[]) => mockDelete(...a),+ },+ },+}));++jest.mock("@/lib/organisation", () => ({+ getCurrentOrganisation: (...a: unknown[]) => mockGetCurrentOrganisation(...a),+ getCurrentProjectForOrganisation: (...a: unknown[]) =>+ mockGetCurrentProjectForOrganisation(...a),+}));++jest.mock("@/lib/project-environment", () => ({+ createProjectEnvironment: jest.fn().mockResolvedValue({ id: "env-1" }),+}));++jest.mock("next/headers", () => ({+ headers: jest.fn(async () => ({+ get: () => null,+ })),+}));++jest.mock("@/utils/crypto", () => ({+ encryptValue: (value: string) => `enc:v1:${value}`,+ decryptValue: (value: string) => String(value).replace(/^enc:v1:/, ""),+ isEncrypted: (value: string) => String(value).startsWith("enc:v1:"),+}));++jest.mock("@/lib/access/connector-entitlement", () => ({+ assertPremiumConnectorAllowed: jest.fn().mockResolvedValue(undefined),+}));++jest.mock("@/lib/platform/connectors/memory/bootstrap", () => ({+ ensureMemoryAdaptersRegistered: jest.fn(),+}));++jest.mock("@/lib/platform/connectors/memory/registry", () => ({+ hasMemoryAdapterFactory: (...a: unknown[]) => mockHasMemoryAdapterFactory(...a),+ getMemoryTypeDescriptor: (...a: unknown[]) => mockGetMemoryTypeDescriptor(...a),+ createMemoryAdapter: (...a: unknown[]) => mockCreateMemoryAdapter(...a),+ listMemoryTypeDescriptors: jest.fn().mockReturnValue([]),+}));++jest.mock("@/lib/platform/connectors/datasource/http/secret", () => ({+ invalidateSourceSecretCache: jest.fn(),+}));++import {+ createMemoryConnector,+ deleteMemoryConnector,+ healthCheckMemoryConnector,+ isMemoryConnectorId,+ listMemoryConnectors,+ readRememberedMemoryFilters,+ rememberMemoryFilters,+ updateMemoryConnector,+} from "@/lib/platform/connectors/memory/crud";++const row = (over: Record<string, unknown> = {}) => ({+ id: "memory:abc",+ category: "memory",+ type: "mem0",+ name: "Prod Mem0",+ environment: "production",+ organisationId: "org-1",+ projectId: "proj-1",+ settings: '{"url":"https://api.mem0.ai"}',+ secretRef: 'enc:v1:{"apiKey":"m0-key"}',+ status: "active",+ metadata: "{}",+ createdAt: new Date(),+ updatedAt: new Date(),+ ...over,+});++beforeEach(() => {+ jest.clearAllMocks();+ mockGetCurrentOrganisation.mockResolvedValue({ id: "org-1" });+ mockGetCurrentProjectForOrganisation.mockResolvedValue({ id: "proj-1" });+ mockHasMemoryAdapterFactory.mockReturnValue(true);+ mockGetMemoryTypeDescriptor.mockReturnValue({ type: "mem0" });+ mockFindFirst.mockResolvedValue(null);+});++describe("memory connector CRUD", () => {+ it("identifies memory connector ids", () => {+ expect(isMemoryConnectorId("memory:abc")).toBe(true);+ expect(isMemoryConnectorId("telemetry:abc")).toBe(false);+ });++ 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({+ name: "Prod Mem0",+ type: "mem0",+ environment: "production",+ settings: { url: "https://api.mem0.ai" },+ credentials: { apiKey: "m0-key" },+ });+ expect(mockCreate.mock.calls[0][0].data).toEqual(+ expect.objectContaining({+ category: "memory",+ type: "mem0",+ projectId: "proj-1",+ secretRef: 'enc:v1:{"apiKey":"m0-key"}',+ })+ );+ expect(created).toEqual(+ expect.objectContaining({+ id: "memory:abc",+ hasSecret: true,+ category: "memory",+ })+ );+ expect(created).not.toHaveProperty("secretRef");+ expect(JSON.stringify(created)).not.toContain("m0-key");+ });++ it("rejects a ClickHouse vault id instead of an inline encrypted key", async () => {+ await expect(+ createMemoryConnector({+ name: "Prod Mem0",+ type: "mem0",+ environment: "production",+ secretRef: "vault-1",+ })+ ).rejects.toThrow(/store its API key on the connector/i);+ expect(mockCreate).not.toHaveBeenCalled();+ });++ it("rejects a missing name", async () => {+ await expect(createMemoryConnector({ type: "mem0" })).rejects.toThrow(+ /name is required/i+ );+ expect(mockCreate).not.toHaveBeenCalled();+ });++ it("rejects an unknown type", async () => {+ mockHasMemoryAdapterFactory.mockReturnValue(false);+ await expect(+ createMemoryConnector({ name: "X", type: "unknown-memory" })+ ).rejects.toThrow(/unknown memory connector/i);+ });++ it("rejects a duplicate name in the same environment", async () => {+ mockFindFirst.mockResolvedValue({ id: "memory:existing" });+ await expect(+ createMemoryConnector({+ name: "Prod Mem0",+ type: "mem0",+ environment: "production",+ })+ ).rejects.toThrow(/already exists/);+ expect(mockCreate).not.toHaveBeenCalled();+ });++ it("updates settings without exposing the secret", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockUpdate.mockResolvedValue(row());+ const updated = await updateMemoryConnector("memory:abc", {+ settings: { url: "https://api.mem0.ai" },+ });+ expect(mockUpdate).toHaveBeenCalled();+ expect(updated).not.toHaveProperty("secretRef");+ expect(updated.hasSecret).toBe(true);+ });++ it("deletes only a memory connector in the current project", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockDelete.mockResolvedValue(row());+ await expect(deleteMemoryConnector("abc")).resolves.toEqual({ ok: true });+ expect(mockFindFirst).toHaveBeenCalledWith(+ expect.objectContaining({+ where: expect.objectContaining({+ id: "memory:abc",+ projectId: "proj-1",+ category: "memory",+ }),+ })+ );+ });++ it("health-checks through the registered adapter", async () => {+ mockFindFirst.mockResolvedValue(row());+ mockCreateMemoryAdapter.mockReturnValue({+ healthCheck: async () => ({ ok: true, latencyMs: 12 }),+ });+ await expect(healthCheckMemoryConnector("memory:abc")).resolves.toEqual({+ ok: true,+ latencyMs: 12,+ });+ });++ it("lists environment-scoped memory connectors without secretRef", async () => {+ mockFindMany.mockResolvedValue([row()]);+ const listed = await listMemoryConnectors();+ expect(mockFindMany).toHaveBeenCalledWith(+ expect.objectContaining({+ where: {+ projectId: "proj-1",+ category: "memory",+ environment: "production",+ },+ })+ );+ expect(listed[0]).not.toHaveProperty("secretRef");+ expect(listed[0].hasSecret).toBe(true);+ });++ it("lists connectors for an explicit environment", async () => {+ mockFindMany.mockResolvedValue([+ row({ id: "memory:dev", name: "Dev Mem0", environment: "development" }),+ ]);+ await listMemoryConnectors("development");+ expect(mockFindMany).toHaveBeenCalledWith(+ expect.objectContaining({+ where: {+ projectId: "proj-1",+ category: "memory",+ environment: "development",+ },+ })+ );+ });++ it("remembers typed user ids and omits them from public connector metadata", async () => {+ mockFindFirst.mockResolvedValue(+ row({+ metadata: JSON.stringify({+ category: "memory",+ memoryFilters: { users: ["ada"] },+ }),+ })+ );+ mockUpdate.mockResolvedValue(row());+ await rememberMemoryFilters("abc", { users: ["aman"] });+ expect(JSON.parse(mockUpdate.mock.calls[0][0].data.metadata)).toEqual({+ category: "memory",+ memoryFilters: { users: ["ada", "aman"], sessions: [], agents: [] },+ });++ await expect(readRememberedMemoryFilters("abc")).resolves.toEqual({+ users: ["ada"],+ sessions: [],+ agents: [],+ });++ mockFindMany.mockResolvedValue([+ row({+ metadata: JSON.stringify({+ category: "memory",+ memoryFilters: { users: ["aman"] },+ }),+ }),+ ]);+ const listed = await listMemoryConnectors();+ expect(JSON.parse(String(listed[0].metadata))).toEqual({ category: "memory" });+ });++ it("omits memory connectors whose adapter is no longer registered", async () => {+ mockFindMany.mockResolvedValue([+ row(),+ row({ id: "memory:gone", type: "unknown-vendor", name: "retired vendor" }),+ ]);+ mockHasMemoryAdapterFactory.mockImplementation((type: unknown) => type === "mem0");+ const listed = await listMemoryConnectors();+ expect(listed.map((item) => item.id)).toEqual(["memory:abc"]);+ });+});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.tsnew file mode 100644index 00000000..828806e0--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/memory-graph.test.ts@@ -0,0 +1,177 @@+import {+ buildMemoryGraph,+ classifyMemoryKind,+ layoutMemoryGraph,+ summarizeMemoryStats,+} from "@/lib/platform/connectors/memory/graph";+import type { MemoryRecord } from "@/lib/platform/connectors/memory/types";++function record(over: Partial<MemoryRecord> = {}): MemoryRecord {+ return {+ id: "m1",+ content: "Presenting a report on tracing coverage",+ ...over,+ };+}++describe("memory graph helpers", () => {+ it("classifies from metadata and content heuristics", () => {+ expect(+ classifyMemoryKind(record({ metadata: { memory_type: "episodic" } }))+ ).toBe("temporal");+ expect(+ classifyMemoryKind(record({ metadata: { type: "identity" } }))+ ).toBe("profile");+ expect(classifyMemoryKind(record({ content: "Alex likes dark mode" }))).toBe(+ "profile"+ );+ expect(+ classifyMemoryKind(record({ categories: ["profile"], metadata: { domain: "profile" } }))+ ).toBe("profile");+ expect(classifyMemoryKind(record())).toBe("summary");+ });++ it("summarizes counts and unique connections", () => {+ const stats = summarizeMemoryStats([+ record({+ id: "1",+ userId: "u1",+ sessionId: "s1",+ metadata: { memory_type: "temporal" },+ }),+ record({+ id: "2",+ userId: "u1",+ sessionId: "s2",+ metadata: { type: "profile" },+ }),+ record({ id: "3", content: "Weekly summary of tracing work" }),+ ]);+ expect(stats).toEqual(+ expect.objectContaining({+ total: 3,+ users: 1,+ sessions: 2,+ connections: 2,+ temporal: 1,+ profile: 1,+ summary: 1,+ })+ );+ });++ it("builds user → session → memory edges", () => {+ const graph = buildMemoryGraph([+ record({ id: "mem-1", userId: "ada", sessionId: "run-9" }),+ ]);+ expect(graph.nodes.map((node) => node.id)).toEqual([+ "user:ada",+ "session:run-9",+ "memory:mem-1",+ ]);+ expect(graph.edges).toEqual([+ { from: "user:ada", to: "session:run-9" },+ { from: "session:run-9", to: "memory:mem-1", memoryId: "mem-1" },+ ]);+ });++ it("lays out nodes with coordinates", () => {+ const laid = layoutMemoryGraph(+ buildMemoryGraph([+ record({ id: "a", userId: "u1" }),+ record({ id: "b", userId: "u2" }),+ ])+ );+ expect(laid.length).toBeGreaterThan(2);+ expect(laid.every((node) => Number.isFinite(node.x) && Number.isFinite(node.y))).toBe(+ true+ );+ });++ it("fans memories out instead of stacking them on the parent", () => {+ const laid = layoutMemoryGraph(+ buildMemoryGraph([+ record({ id: "a", userId: "ada", sessionId: "s1", content: "one" }),+ record({ id: "b", userId: "ada", sessionId: "s1", content: "two" }),+ record({ id: "c", userId: "ada", sessionId: "s2", content: "three" }),+ ])+ );+ const memories = laid.filter((node) => node.type === "memory");+ const user = laid.find((node) => node.type === "user");+ expect(memories).toHaveLength(3);+ expect(user).toBeDefined();+ const spread = Math.max(+ ...memories.map((node) => Math.hypot(node.x - memories[0].x, node.y - memories[0].y))+ );+ expect(spread).toBeGreaterThan(40);+ expect(+ memories.every(+ (node) => Math.hypot(node.x - (user?.x || 0), node.y - (user?.y || 0)) > 40+ )+ ).toBe(true);+ });++ it("builds an entity knowledge graph from relation endpoints", () => {+ const graph = buildMemoryGraph([+ record({+ id: "e1",+ content: "Sarah lives in Austin",+ relation: {+ source: {+ id: "n-user",+ label: "Sarah Smith",+ types: ["User", "Node"],+ },+ target: {+ id: "n-loc",+ label: "Austin",+ types: ["Location", "Node"],+ },+ name: "LIVES_IN",+ },+ }),+ record({+ id: "n-topic",+ content: "Observability",+ graphOnly: true,+ categories: ["Topic", "Node"],+ metadata: { name: "Observability" },+ }),+ ]);+ expect(graph.kind).toBe("knowledge");+ expect(graph.nodes).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: "n-user",+ type: "user",+ entityType: "user",+ label: "Sarah Smith",+ }),+ expect.objectContaining({+ id: "n-loc",+ entityType: "location",+ label: "Austin",+ }),+ expect.objectContaining({+ id: "n-topic",+ entityType: "topic",+ label: "Observability",+ }),+ ])+ );+ expect(graph.edges).toEqual([+ {+ from: "n-user",+ to: "n-loc",+ memoryId: "e1",+ label: "LIVES_IN",+ },+ ]);+ const laid = layoutMemoryGraph(graph);+ const hub = laid.find((node) => node.id === "n-user");+ expect(hub).toBeDefined();+ expect(laid.every((node) => Number.isFinite(node.x) && Number.isFinite(node.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.tsnew file mode 100644index 00000000..fa8b5c0d--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/memory-port.test.ts@@ -0,0 +1,58 @@+import {+ attachMemoryPorts,+ memoryContentFingerprint,+ memoryPortMetadata,+ parseMemoryPortLink,+} from "@/lib/platform/connectors/memory/port-link";+import type { MemoryRecord } from "@/lib/platform/connectors/memory/types";++describe("memory port links", () => {+ it("parses and reattaches provenance metadata", () => {+ const link = {+ sourceConnectorId: "memory:src",+ sourceConnectorName: "Prod Mem0",+ sourceMemoryId: "mem-1",+ copiedAt: "2026-08-18T12:00:00.000Z",+ contentFingerprint: memoryContentFingerprint("Lives in Berlin", "ada"),+ };+ const metadata = memoryPortMetadata(link, { topic: "profile" });+ expect(parseMemoryPortLink(metadata)).toEqual(+ expect.objectContaining({+ sourceConnectorId: "memory:src",+ sourceMemoryId: "mem-1",+ sourceConnectorName: "Prod Mem0",+ })+ );+ expect(metadata).toEqual(+ expect.objectContaining({ topic: "profile" })+ );+ });++ it("returns nothing when provenance metadata is missing", () => {+ expect(parseMemoryPortLink(undefined)).toBeUndefined();+ expect(parseMemoryPortLink(null)).toBeUndefined();+ expect(parseMemoryPortLink({ memory_type: "temporal" })).toBeUndefined();+ });++ it("matches stored links by destination id or content fingerprint", () => {+ const fingerprint = memoryContentFingerprint("Prefers tabs", "ada");+ const attached = attachMemoryPorts<MemoryRecord>(+ [+ { id: "dest-1", content: "Prefers tabs", userId: "ada" },+ { id: "other", content: "Unrelated", userId: "ada" },+ ],+ [+ {+ sourceConnectorId: "memory:src",+ sourceMemoryId: "mem-1",+ sourceConnectorName: "Mem0",+ copiedAt: "2026-08-18T12:00:00.000Z",+ contentFingerprint: fingerprint,+ destMemoryId: "dest-1",+ },+ ]+ );+ expect(attached[0].port?.sourceMemoryId).toBe("mem-1");+ expect(attached[1].port).toBeUndefined();+ });+});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.tsnew file mode 100644index 00000000..a0efe635--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/memory-read.test.ts@@ -0,0 +1,450 @@+const mockListMemoryConnectors = jest.fn();+const mockGetMemoryRuntime = jest.fn();++jest.mock("@/lib/platform/connectors/memory/crud", () => ({+ listMemoryConnectors: (...a: unknown[]) => mockListMemoryConnectors(...a),+ getMemoryRuntime: (...a: unknown[]) => mockGetMemoryRuntime(...a),+ readMemoryPortLinks: jest.fn().mockResolvedValue([]),+ readRememberedMemoryFilters: jest.fn().mockResolvedValue({+ users: [],+ sessions: [],+ agents: [],+ }),+ rememberMemoryFilters: jest.fn().mockResolvedValue(undefined),+ emptyRememberedMemoryFilters: () => ({ users: [], sessions: [], agents: [] }),+ memoryConnectorId: (id: string) =>+ String(id).startsWith("memory:") ? id : `memory:${id}`,+}));++import { getProjectMemory, queryProjectMemories, submitProjectMemoryFeedback } from "@/lib/platform/connectors/memory/read";+import { readRememberedMemoryFilters } from "@/lib/platform/connectors/memory/crud";+import {+ MEMORY_CONNECTOR_FILTER_REQUIRED,+ MEMORY_CONNECTOR_SESSION_REQUIRED,+ MEMORY_DETAIL_FEEDBACK_UNSUPPORTED,+ MEMORY_DETAIL_NOT_FOUND,+} from "@/constants/messages/en";++const connector = {+ id: "memory:abc",+ name: "Prod Mem0",+ type: "mem0",+ environment: "production",+ hasSecret: true,+};++describe("queryProjectMemories", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("returns an empty payload when the project has no memory connectors", async () => {+ mockListMemoryConnectors.mockResolvedValue([]);+ await expect(queryProjectMemories()).resolves.toEqual(+ expect.objectContaining({+ connectors: [],+ connector: null,+ memories: [],+ stats: expect.objectContaining({ total: 0 }),+ })+ );+ expect(mockGetMemoryRuntime).not.toHaveBeenCalled();+ });++ it("lists memories through the selected adapter and classifies them", 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: "Migrated tracing SDK",+ userId: "ada",+ metadata: { memory_type: "temporal" },+ },+ ],+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories({ connectorId: "abc" });+ expect(result.connector?.id).toBe("memory:abc");+ expect(result.memories[0].kind).toBe("temporal");+ expect(result.stats.total).toBe(1);+ expect(result.graph.nodes.some((node) => node.id === "memory:m1")).toBe(true);+ expect(result.filters.users).toEqual([{ id: "ada", label: "ada" }]);+ expect(result.filterFields.length).toBeGreaterThan(0);+ expect(result.connector).not.toHaveProperty("secretRef");+ });++ it("searches when a query is provided", async () => {+ const search = jest.fn().mockResolvedValue([+ { id: "hit", content: "Profiled the trace exporter", userId: "ada" },+ ]);+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ list: jest.fn(),+ search,+ },+ });++ const result = await queryProjectMemories({ query: "exporter" });+ expect(search).toHaveBeenCalledWith(+ expect.objectContaining({ query: "exporter" })+ );+ expect(result.memories[0].id).toBe("hit");+ });++ it("returns a session hint instead of failing when Zep list needs a session", async () => {+ mockListMemoryConnectors.mockResolvedValue([+ { ...connector, type: "zep" },+ ]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector: { ...connector, type: "zep" },+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: false,+ list: true,+ update: false,+ delete: true,+ }),+ list: async () => {+ throw new Error(MEMORY_CONNECTOR_SESSION_REQUIRED);+ },+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories();+ expect(result.hint).toBe("session_required");+ expect(result.connectors).toHaveLength(1);+ expect(result.memories).toEqual([]);+ expect(result.filters).toEqual({ users: [], sessions: [], agents: [] });+ });++ it("returns a filter hint and vendor options when Mem0 list needs a scope", async () => {+ 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: "[email protected]" }],+ sessions: [{ id: "run-1", label: "run-1", userId: "ada" }],+ agents: [],+ }),+ list: async () => {+ throw new Error(+ 'SourceResponseError: Data source responded 400: ["One of the filters: app_id, user_id, agent_id, run_id is required!"]'+ );+ },+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories();+ expect(result.hint).toBe("filter_required");+ expect(result.memories).toEqual([]);+ expect(result.filters.users).toEqual([{ id: "ada", label: "[email protected]" }]);+ expect(result.filters.sessions[0].id).toBe("run-1");+ });++ it("includes the requested user in filters when the vendor cannot enumerate users", async () => {+ mockListMemoryConnectors.mockResolvedValue([+ { ...connector, type: "mem0" },+ ]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector: { ...connector, type: "mem0" },+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: false,+ list: true,+ update: false,+ delete: false,+ feedback: false,+ }),+ listFilters: async () => ({ users: [], sessions: [], agents: [] }),+ list: async () => [],+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories({+ connectorId: "abc",+ userId: "aman",+ });+ expect(result.filters.users).toEqual([{ id: "aman", label: "aman" }]);+ });++ it("includes remembered users when listing still needs a user filter", async () => {+ (readRememberedMemoryFilters as jest.Mock).mockResolvedValueOnce({+ users: ["aman"],+ sessions: [],+ agents: [],+ });+ mockListMemoryConnectors.mockResolvedValue([+ { ...connector, type: "mem0" },+ ]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector: { ...connector, type: "mem0" },+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: false,+ list: true,+ update: false,+ delete: false,+ feedback: false,+ }),+ listFilters: async () => ({ users: [], sessions: [], agents: [] }),+ list: async () => {+ throw new Error(MEMORY_CONNECTOR_FILTER_REQUIRED);+ },+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories({ connectorId: "abc" });+ expect(result.hint).toBe("filter_required");+ expect(result.filters.users).toEqual([{ id: "aman", label: "aman" }]);+ });++ it("returns an auth hint when the vendor rejects the API key", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ listFilters: async () => ({ users: [], sessions: [], agents: [] }),+ list: async () => {+ const error = new Error(+ 'Data source responded 401: {"error":{"message":"API key is invalid."}}'+ ) as Error & { status: number };+ error.status = 401;+ throw error;+ },+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories();+ expect(result.hint).toBe("auth_failed");+ expect(result.memories).toEqual([]);+ expect(result.connectors).toHaveLength(1);+ });++ it("returns an unavailable hint when the vendor list call fails", 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 Error("Data source responded 404: memory store not found");+ },+ search: jest.fn(),+ },+ });++ const result = await queryProjectMemories();+ expect(result.hint).toBe("unavailable");+ expect(result.memories).toEqual([]);+ });+});++describe("getProjectMemory", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("fetches a memory by id through the adapter", async () => {+ const get = jest.fn().mockResolvedValue({+ id: "mem-1",+ content: "User's name is Alex, they are a vegetarian, and they have a nut allergy",+ userId: "alex",+ metadata: { memory_type: "profile" },+ });+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ get,+ },+ });++ const result = await getProjectMemory({ id: "mem-1", connectorId: "abc" });+ expect(get).toHaveBeenCalledWith("mem-1");+ expect(result.memory?.kind).toBe("profile");+ expect(result.memory?.userId).toBe("alex");+ expect(result.connector).not.toHaveProperty("secretRef");+ });++ it("returns a get_unsupported hint when the vendor cannot fetch by id", async () => {+ mockListMemoryConnectors.mockResolvedValue([{ ...connector, type: "zep" }]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector: { ...connector, type: "zep" },+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: false,+ list: true,+ update: false,+ delete: true,+ }),+ get: jest.fn(),+ },+ });++ const result = await getProjectMemory({ id: "mem-1" });+ expect(result.hint).toBe("get_unsupported");+ expect(result.memory).toBeNull();+ });++ it("throws when the memory is missing", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ }),+ get: async () => null,+ },+ });++ await expect(getProjectMemory({ id: "missing" })).rejects.toThrow(+ MEMORY_DETAIL_NOT_FOUND+ );+ });+});++describe("submitProjectMemoryFeedback", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("posts feedback through the adapter and refreshes the memory", async () => {+ const feedback = jest.fn().mockResolvedValue({+ rating: "positive",+ reason: "Accurate",+ });+ const get = jest.fn().mockResolvedValue({+ id: "mem-1",+ content: "hello",+ feedback: { rating: "positive", reason: "Accurate" },+ });+ 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",+ connectorId: "abc",+ rating: "positive",+ reason: "Accurate",+ });+ expect(feedback).toHaveBeenCalledWith("mem-1", {+ rating: "positive",+ reason: "Accurate",+ });+ expect(result.feedback.rating).toBe("positive");+ expect(result.memory?.feedback?.rating).toBe("positive");+ expect(result.connector).not.toHaveProperty("secretRef");+ });++ it("rejects feedback when the vendor does not support it", async () => {+ mockListMemoryConnectors.mockResolvedValue([{ ...connector, type: "zep" }]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector: { ...connector, type: "zep" },+ adapter: {+ capabilities: () => ({+ add: true,+ search: true,+ get: true,+ list: true,+ update: false,+ delete: true,+ feedback: false,+ }),+ feedback: jest.fn(),+ },+ });++ await expect(+ submitProjectMemoryFeedback({ id: "mem-1", rating: "negative" })+ ).rejects.toThrow(MEMORY_DETAIL_FEEDBACK_UNSUPPORTED);+ });+});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.tsnew file mode 100644index 00000000..93094058--- /dev/null+++ b/src/client/src/__tests__/lib/platform/connectors/memory-write.test.ts@@ -0,0 +1,172 @@+const mockListMemoryConnectors = jest.fn();+const mockGetMemoryRuntime = jest.fn();++jest.mock("@/lib/platform/connectors/memory/crud", () => ({+ listMemoryConnectors: (...a: unknown[]) => mockListMemoryConnectors(...a),+ getMemoryRuntime: (...a: unknown[]) => mockGetMemoryRuntime(...a),+ rememberMemoryFilters: jest.fn().mockResolvedValue(undefined),+ memoryConnectorId: (id: string) =>+ String(id).startsWith("memory:") ? id : `memory:${id}`,+}));++import {+ addProjectMemories,+ deleteProjectMemory,+ parseMemoryMetadata,+ updateProjectMemory,+} from "@/lib/platform/connectors/memory/write";+import {+ MEMORY_ADD_UNSUPPORTED,+ MEMORY_CONNECTOR_CONTENT_REQUIRED,+ MEMORY_DELETE_UNSUPPORTED,+ MEMORY_EDIT_UNSUPPORTED,+ MEMORY_INVALID_METADATA,+} from "@/constants/messages/en";++const connector = {+ id: "memory:abc",+ name: "Prod Mem0",+ type: "mem0",+ environment: "production",+ hasSecret: true,+};++const capabilities = {+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: false,+};++describe("addProjectMemories", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("writes through the adapter and classifies the result", async () => {+ const add = jest.fn().mockResolvedValue([+ { id: "m1", content: "Prefers tabs", userId: "ada" },+ ]);+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: { capabilities: () => capabilities, add },+ });++ const result = await addProjectMemories({+ connectorId: "abc",+ content: "Prefers tabs",+ userId: "ada",+ });+ expect(add).toHaveBeenCalledWith(+ expect.objectContaining({ content: "Prefers tabs", userId: "ada" })+ );+ expect(result.memories[0].id).toBe("m1");+ expect(result.memories[0].kind).toBeDefined();+ expect(result.connector).not.toHaveProperty("secretRef");+ });++ it("rejects empty content", async () => {+ await expect(addProjectMemories({ content: " " })).rejects.toThrow(+ MEMORY_CONNECTOR_CONTENT_REQUIRED+ );+ expect(mockGetMemoryRuntime).not.toHaveBeenCalled();+ });++ it("rejects vendors that cannot add", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({ ...capabilities, add: false }),+ add: jest.fn(),+ },+ });+ await expect(addProjectMemories({ content: "hello" })).rejects.toThrow(+ MEMORY_ADD_UNSUPPORTED+ );+ });+});++describe("updateProjectMemory", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("updates through the adapter", async () => {+ const update = jest.fn().mockResolvedValue({+ id: "m1",+ content: "Prefers spaces",+ });+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: { capabilities: () => capabilities, update },+ });+ const result = await updateProjectMemory({+ id: "m1",+ content: "Prefers spaces",+ });+ expect(update).toHaveBeenCalledWith("m1", {+ content: "Prefers spaces",+ metadata: undefined,+ });+ expect(result.memory.content).toBe("Prefers spaces");+ });++ it("rejects vendors that cannot update", async () => {+ mockListMemoryConnectors.mockResolvedValue([{ ...connector, type: "zep" }]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector: { ...connector, type: "zep" },+ adapter: {+ capabilities: () => ({ ...capabilities, update: false }),+ update: jest.fn(),+ },+ });+ await expect(+ updateProjectMemory({ id: "m1", content: "hello" })+ ).rejects.toThrow(MEMORY_EDIT_UNSUPPORTED);+ });+});++describe("deleteProjectMemory", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("deletes through the adapter", async () => {+ const remove = jest.fn().mockResolvedValue(undefined);+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: { capabilities: () => capabilities, delete: remove },+ });+ await expect(deleteProjectMemory({ id: "m1" })).resolves.toEqual(+ expect.objectContaining({ ok: true })+ );+ expect(remove).toHaveBeenCalledWith("m1");+ });++ it("rejects vendors that cannot delete", async () => {+ mockListMemoryConnectors.mockResolvedValue([connector]);+ mockGetMemoryRuntime.mockResolvedValue({+ connector,+ adapter: {+ capabilities: () => ({ ...capabilities, delete: false }),+ delete: jest.fn(),+ },+ });+ await expect(deleteProjectMemory({ id: "m1" })).rejects.toThrow(+ MEMORY_DELETE_UNSUPPORTED+ );+ });+});++describe("parseMemoryMetadata", () => {+ it("rejects arrays", () => {+ expect(() => parseMemoryMetadata([])).toThrow(MEMORY_INVALID_METADATA);+ });+});diff --git a/src/client/src/__tests__/lib/platform/datasource/secret.test.ts b/src/client/src/__tests__/lib/platform/datasource/secret.test.tsindex ac4486fd..ab515556 100644--- a/src/client/src/__tests__/lib/platform/datasource/secret.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/secret.test.ts@@ -48,6 +48,15 @@ describe("resolveSourceSecret", () => {expect(getSecretById).not.toHaveBeenCalled();});+ it("does not query ClickHouse vault when clickHouseVault is disabled", async () => {+ await expect(+ resolveSourceSecret("vault-uuid", undefined, "project-1", {+ clickHouseVault: false,+ })+ ).rejects.toThrow(/could not be loaded from the OpenLIT vault/i);+ expect(getSecretById).not.toHaveBeenCalled();+ });+it("forwards the background database and project scope to the vault lookup", async () => {(getSecretById as jest.Mock).mockResolvedValue({data: [{ value: '{"token":"abc"}' }],diff --git a/src/client/src/__tests__/utils/date.test.ts b/src/client/src/__tests__/utils/date.test.tsindex 8e3fdacf..e08d12b3 100644--- a/src/client/src/__tests__/utils/date.test.ts+++ b/src/client/src/__tests__/utils/date.test.ts@@ -1,4 +1,4 @@-import { formatBrowserDateTime, formatDate } from '@/utils/date';+import { formatBrowserDateTime, formatDate, formatDatePartsValue } from '@/utils/date';describe('formatDate', () => {const isoDate = '2024-06-15T10:30:00Z';@@ -65,3 +65,34 @@ describe('formatBrowserDateTime', () => {expect(formatBrowserDateTime('', 'No date')).toBe('No date');});});++describe('formatDatePartsValue', () => {+ it('formats calendar part objects as a locale datetime', () => {+ const formatted = formatDatePartsValue({+ Day: 17,+ Hour: 11,+ Year: 2026,+ Month: 8,+ Minute: 28,+ Quarter: 3,+ 'Is weekend': 'No',+ 'Day of week': 'monday',+ 'Day of year': 229,+ 'Week of year': 34,+ });++ expect(formatted).toBe(new Date(2026, 7, 17, 11, 28, 0).toLocaleString());+ expect(formatted).not.toMatch(/Day of week/i);+ });++ it('leaves mixed objects alone', () => {+ expect(+ formatDatePartsValue({+ year: 2026,+ month: 8,+ day: 17,+ note: 'kickoff',+ })+ ).toBeNull();+ });+});diff --git a/src/client/src/app/(playground)/chat/page.tsx b/src/client/src/app/(playground)/chat/page.tsxindex 9da7e643..b35e202c 100644--- a/src/client/src/app/(playground)/chat/page.tsx+++ b/src/client/src/app/(playground)/chat/page.tsx@@ -18,6 +18,7 @@ export default function ChatPage() {const router = useRouter();const searchParams = useSearchParams();const conversationId = searchParams.get("id");+ const initialPrompt = searchParams.get("prompt");const currentOrg = useRootStore(getCurrentOrganisation);const projects = useRootStore(getProjectList);const currentProject = useRootStore(getCurrentProject);@@ -60,7 +61,7 @@ export default function ChatPage() {return (<RequestProvider><div className="flex flex-col w-full h-full overflow-hidden">- <ChatLayout initialConversationId={conversationId} />+ <ChatLayout initialConversationId={conversationId} initialPrompt={initialPrompt} /></div></RequestProvider>);diff --git a/src/client/src/app/(playground)/memory/page.tsx b/src/client/src/app/(playground)/memory/page.tsxnew file mode 100644index 00000000..8e4b3241--- /dev/null+++ b/src/client/src/app/(playground)/memory/page.tsx@@ -0,0 +1,7 @@+"use client";++import MemoryPage from "@/components/(playground)/memory/memory-page";++export default function MemoryRoute() {+ return <MemoryPage />;+}diff --git a/src/client/src/app/api/connectors/[id]/health/route.ts b/src/client/src/app/api/connectors/[id]/health/route.tsindex 017f5790..13bfa612 100644--- a/src/client/src/app/api/connectors/[id]/health/route.ts+++ b/src/client/src/app/api/connectors/[id]/health/route.ts@@ -6,6 +6,10 @@ import {validateTelemetrySourceAISignal,} from "@/lib/telemetry-source-crud";import { withConnectorAccess, withConnectorAudit } from "@/lib/access/connector-route";+import {+ healthCheckMemoryConnector,+ isMemoryConnectorId,+} from "@/lib/platform/connectors/memory/crud";const DEFAULT_PROBE_MS = 60 * 60 * 1000;@@ -14,6 +18,15 @@ function telemetrySourceId(id: string) {}async function healthAndValidate(id: string) {+ if (isMemoryConnectorId(id)) {+ const [healthErr, health] = await asaw(healthCheckMemoryConnector(id));+ if (healthErr) return errorResponse(healthErr, "Connector health check failed");+ return Response.json({+ health,+ validation: { supported: false },+ });+ }+const sourceId = telemetrySourceId(id);const [healthErr, health] = await asaw(healthCheckTelemetrySource(sourceId));if (healthErr) return errorResponse(healthErr, "Connector health check failed");diff --git a/src/client/src/app/api/connectors/[id]/route.ts b/src/client/src/app/api/connectors/[id]/route.tsindex 6c551bdf..054979c1 100644--- a/src/client/src/app/api/connectors/[id]/route.ts+++ b/src/client/src/app/api/connectors/[id]/route.ts@@ -7,6 +7,11 @@ import {} from "@/lib/telemetry-source-crud";import { NextRequest } from "next/server";import { withConnectorAccess, withConnectorAudit } from "@/lib/access/connector-route";+import {+ deleteMemoryConnector,+ isMemoryConnectorId,+ updateMemoryConnector,+} from "@/lib/platform/connectors/memory/crud";function telemetrySourceId(id: string) {return id.startsWith("telemetry:") ? id.slice("telemetry:".length) : id;@@ -24,6 +29,11 @@ async function PATCHHandler(} catch {return Response.json({ err: "Invalid JSON" }, { status: 400 });}+ if (isMemoryConnectorId(params.id)) {+ const [err, connector] = await asaw(updateMemoryConnector(params.id, body));+ if (err) return errorResponse(err, "Failed to update connector");+ return Response.json(connector);+ }const [err, connector] = await asaw(updateTelemetrySource(telemetrySourceId(params.id), body));if (err) return errorResponse(err, "Failed to update connector");return Response.json({ ...connector, category: "datasource", scope: "project" });@@ -35,6 +45,11 @@ async function DELETEHandler() {const user = await getCurrentUser();if (!user) return Response.json("Unauthorized", { status: 401 });+ if (isMemoryConnectorId(params.id)) {+ const [err, result] = await asaw(deleteMemoryConnector(params.id));+ if (err) return errorResponse(err, "Failed to delete connector");+ return Response.json(result);+ }const [err, result] = await asaw(deleteTelemetrySource(telemetrySourceId(params.id)));if (err) return errorResponse(err, "Failed to delete connector");return Response.json(result);diff --git a/src/client/src/app/api/connectors/route.ts b/src/client/src/app/api/connectors/route.tsindex 408eca75..56ff0593 100644--- a/src/client/src/app/api/connectors/route.ts+++ b/src/client/src/app/api/connectors/route.ts@@ -1,7 +1,7 @@import { getCurrentUser } from "@/lib/session";import { errorResponse } from "@/utils/api-response";import asaw from "@/utils/asaw";-import { createTelemetrySource, availableSourceTypeDescriptors } from "@/lib/telemetry-source-crud";+import { createTelemetrySource } from "@/lib/telemetry-source-crud";import { upsertDBConfig } from "@/lib/db-config";import { NextRequest } from "next/server";import { withConnectorAccess, withConnectorAudit } from "@/lib/access/connector-route";@@ -13,11 +13,16 @@ import {import { listProjectConnectorInstances } from "@/lib/platform/connectors/instances";import { isVisibleConnectorType } from "@/lib/platform/connectors/visible-types";import { validateOpenPlaitClickHouseConnection } from "@/lib/platform/openplait";+import { availableConnectorTypeDescriptors } from "@/lib/platform/connectors/catalog";+import {+ createMemoryConnector,+ isMemoryConnectorType,+} from "@/lib/platform/connectors/memory/crud";/*** Generic connector endpoint. Datasource instances are exposed through the* connector contract while legacy repositories remain compatibility stores- * for existing platform features.+ * for existing platform features. Memory connectors persist on ConnectorInstance.*/async function GETHandler() {const user = await getCurrentUser();@@ -35,16 +40,11 @@ async function GETHandler() {return {...safeConnector,icon: connectorIconPath(String(connector.type || "")),- category: "datasource",+ category: String(connector.category || "datasource"),scope: "project",};}),- availableTypeDescriptors: availableSourceTypeDescriptors().filter((descriptor) => isVisibleConnectorType(descriptor.type)).map((descriptor) => ({- ...descriptor,- icon: connectorIconPath(descriptor.type),- category: "datasource",- scope: "project",- })),+ availableTypeDescriptors: availableConnectorTypeDescriptors(),});}@@ -57,7 +57,14 @@ async function POSTHandler(request: NextRequest) {} catch {return Response.json({ err: "Invalid JSON" }, { status: 400 });}- if (body.category && body.category !== "datasource") {+ const category = String(body.category || "");+ const type = String(body.type || "");+ if (category === "memory" || isMemoryConnectorType(type)) {+ const [err, connector] = await asaw(createMemoryConnector(body));+ if (err) return errorResponse(err, "Failed to create connector");+ return Response.json(connector);+ }+ if (category && category !== "datasource") {return Response.json({ err: `Connector category is not available in CE: ${String(body.category)}` },{ status: 400 }diff --git a/src/client/src/app/api/connectors/types/route.ts b/src/client/src/app/api/connectors/types/route.tsindex 04a1bb4c..b1da29b9 100644--- a/src/client/src/app/api/connectors/types/route.ts+++ b/src/client/src/app/api/connectors/types/route.ts@@ -1,21 +1,15 @@import { getCurrentUser } from "@/lib/session";-import { availableSourceTypeDescriptors } from "@/lib/telemetry-source-crud";import { withConnectorAccess } from "@/lib/access/connector-route";-import { connectorIconPath } from "@/lib/platform/connectors/icons";-import { isVisibleConnectorType } from "@/lib/platform/connectors/visible-types";+import { availableConnectorTypeDescriptors } from "@/lib/platform/connectors/catalog";async function GETHandler() {const user = await getCurrentUser();if (!user) return Response.json("Unauthorized", { status: 401 });+ const types = availableConnectorTypeDescriptors();return Response.json({categories: ["datasource", "notification", "memory", "vector-store", "model-provider"],- types: availableSourceTypeDescriptors().filter((descriptor) => isVisibleConnectorType(descriptor.type)).map((descriptor) => ({- ...descriptor,- icon: connectorIconPath(descriptor.type),- category: "datasource",- scope: "project",- })),+ types,});}diff --git a/src/client/src/app/api/memory/[id]/feedback/route.ts b/src/client/src/app/api/memory/[id]/feedback/route.tsnew file mode 100644index 00000000..a9060bf8--- /dev/null+++ b/src/client/src/app/api/memory/[id]/feedback/route.ts@@ -0,0 +1,100 @@+import { NextRequest } from "next/server";+import { getCurrentUser } from "@/lib/session";+import { errorResponse } from "@/utils/api-response";+import asaw from "@/utils/asaw";+import { withMemoryAccess, withMemoryAudit } from "@/lib/access/memory-route";+import { isMemoryConnectorId, memoryConnectorId } from "@/lib/platform/connectors/memory/crud";+import { submitProjectMemoryFeedback } from "@/lib/platform/connectors/memory/read";+import { isMemoryFeedbackRating } from "@/lib/platform/connectors/memory/types";+import {+ MEMORY_CONNECTOR_NOT_FOUND,+ MEMORY_DETAIL_FEEDBACK_SAVE_FAILED,+ MEMORY_DETAIL_FEEDBACK_UNSUPPORTED,+ MEMORY_DETAIL_NOT_FOUND,+ MEMORY_FEEDBACK_INVALID,+ MEMORY_FEEDBACK_REASON_TOO_LONG,+ MEMORY_INVALID_FILTER,+ MEMORY_INVALID_JSON,+} from "@/constants/messages/en";++const ID_MAX = 200;++function parseId(value: string): string {+ const trimmed = String(value || "").trim();+ if (!trimmed || trimmed.length > ID_MAX || /[\u0000-\u001f]/.test(trimmed)) {+ throw new Error(MEMORY_INVALID_FILTER);+ }+ return trimmed;+}++function parseConnectorId(value: string | null): string | undefined {+ if (value == null) return undefined;+ const trimmed = value.trim();+ if (!trimmed) return undefined;+ if (trimmed.length > 120 || /[\u0000-\u001f]/.test(trimmed)) {+ throw new Error(MEMORY_INVALID_FILTER);+ }+ const id = memoryConnectorId(trimmed);+ if (!isMemoryConnectorId(id)) {+ throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ }+ return id;+}++async function POSTHandler(+ request: NextRequest,+ { params }: { params: { id: string } }+) {+ const user = await getCurrentUser();+ if (!user) return Response.json("Unauthorized", { status: 401 });++ let id: string;+ let connectorId: string | undefined;+ try {+ id = parseId(params.id);+ connectorId = parseConnectorId(request.nextUrl.searchParams.get("connectorId"));+ } catch (error) {+ return errorResponse(error, MEMORY_INVALID_FILTER, 400);+ }++ let body: Record<string, unknown>;+ try {+ body = (await request.json()) as Record<string, unknown>;+ } catch {+ return errorResponse(MEMORY_INVALID_JSON, MEMORY_INVALID_JSON, 400);+ }++ const rating = body.rating === null || body.rating === "" ? null : body.rating;+ if (rating !== null && !isMemoryFeedbackRating(rating)) {+ return errorResponse(MEMORY_FEEDBACK_INVALID, MEMORY_FEEDBACK_INVALID, 400);+ }+ if (typeof body.reason === "string" && body.reason.length > 1000) {+ return errorResponse(+ MEMORY_FEEDBACK_REASON_TOO_LONG,+ MEMORY_FEEDBACK_REASON_TOO_LONG,+ 400+ );+ }++ const [err, result] = await asaw(+ submitProjectMemoryFeedback({+ id,+ connectorId,+ rating,+ reason: typeof body.reason === "string" ? body.reason : body.reason === null ? null : undefined,+ })+ );+ if (err) {+ const message = err instanceof Error ? err.message : String(err);+ const status =+ message === MEMORY_DETAIL_NOT_FOUND || message === MEMORY_CONNECTOR_NOT_FOUND+ ? 404+ : message === MEMORY_DETAIL_FEEDBACK_UNSUPPORTED+ ? 400+ : 400;+ return errorResponse(err, MEMORY_DETAIL_FEEDBACK_SAVE_FAILED, status);+ }+ return Response.json(result);+}++export const POST = withMemoryAudit(withMemoryAccess("feedback", POSTHandler));diff --git a/src/client/src/app/api/memory/[id]/route.ts b/src/client/src/app/api/memory/[id]/route.tsnew file mode 100644index 00000000..1b771e9f--- /dev/null+++ b/src/client/src/app/api/memory/[id]/route.ts@@ -0,0 +1,166 @@+import { NextRequest } from "next/server";+import { getCurrentUser } from "@/lib/session";+import { errorResponse } from "@/utils/api-response";+import asaw from "@/utils/asaw";+import { withMemoryAccess, withMemoryAudit } from "@/lib/access/memory-route";+import { isMemoryConnectorId, memoryConnectorId } from "@/lib/platform/connectors/memory/crud";+import { getProjectMemory } from "@/lib/platform/connectors/memory/read";+import {+ deleteProjectMemory,+ parseMemoryMetadata,+ updateProjectMemory,+} from "@/lib/platform/connectors/memory/write";+import {+ MEMORY_CONNECTOR_CONTENT_REQUIRED,+ MEMORY_CONNECTOR_NOT_FOUND,+ MEMORY_CONTENT_TOO_LONG,+ MEMORY_DELETE_FAILED,+ MEMORY_DETAIL_LOAD_FAILED,+ MEMORY_DETAIL_NOT_FOUND,+ MEMORY_EDIT_FAILED,+ MEMORY_INVALID_FILTER,+ MEMORY_INVALID_JSON,+ MEMORY_INVALID_METADATA,+} from "@/constants/messages/en";++const ID_MAX = 200;++function parseId(value: string): string {+ const trimmed = String(value || "").trim();+ if (!trimmed || trimmed.length > ID_MAX || /[\u0000-\u001f]/.test(trimmed)) {+ throw new Error(MEMORY_INVALID_FILTER);+ }+ return trimmed;+}++function parseConnectorId(value: string | null | undefined): string | undefined {+ if (value == null) return undefined;+ const trimmed = value.trim();+ if (!trimmed) return undefined;+ if (trimmed.length > 120 || /[\u0000-\u001f]/.test(trimmed)) {+ throw new Error(MEMORY_INVALID_FILTER);+ }+ const id = memoryConnectorId(trimmed);+ if (!isMemoryConnectorId(id)) {+ throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ }+ return id;+}++function mutationStatus(message: string): number {+ if (message === MEMORY_DETAIL_NOT_FOUND || message === MEMORY_CONNECTOR_NOT_FOUND) {+ return 404;+ }+ return 400;+}++async function GETHandler(+ request: NextRequest,+ { params }: { params: { id: string } }+) {+ const user = await getCurrentUser();+ if (!user) return Response.json("Unauthorized", { status: 401 });++ let id: string;+ let connectorId: string | undefined;+ try {+ id = parseId(params.id);+ connectorId = parseConnectorId(request.nextUrl.searchParams.get("connectorId"));+ } catch (error) {+ return errorResponse(error, MEMORY_INVALID_FILTER, 400);+ }++ const [err, result] = await asaw(getProjectMemory({ id, connectorId }));+ if (err) {+ const message = err instanceof Error ? err.message : String(err);+ const status =+ message === MEMORY_DETAIL_NOT_FOUND || message === MEMORY_CONNECTOR_NOT_FOUND+ ? 404+ : 400;+ return errorResponse(err, MEMORY_DETAIL_LOAD_FAILED, status);+ }+ return Response.json(result);+}++async function PATCHHandler(+ request: NextRequest,+ { params }: { params: { id: string } }+) {+ const user = await getCurrentUser();+ if (!user) return Response.json("Unauthorized", { status: 401 });++ let id: string;+ let connectorId: string | undefined;+ try {+ id = parseId(params.id);+ connectorId = parseConnectorId(request.nextUrl.searchParams.get("connectorId"));+ } catch (error) {+ return errorResponse(error, MEMORY_INVALID_FILTER, 400);+ }++ let body: Record<string, unknown>;+ try {+ body = (await request.json()) as Record<string, unknown>;+ } catch {+ return errorResponse(MEMORY_INVALID_JSON, MEMORY_INVALID_JSON, 400);+ }++ let content: string;+ let metadata;+ try {+ if (typeof body.connectorId === "string" && !connectorId) {+ connectorId = parseConnectorId(body.connectorId);+ }+ if (typeof body.content !== "string") {+ throw new Error(MEMORY_CONNECTOR_CONTENT_REQUIRED);+ }+ content = body.content;+ metadata = parseMemoryMetadata(body.metadata);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ const fallback =+ message === MEMORY_INVALID_METADATA ||+ message === MEMORY_CONTENT_TOO_LONG ||+ message === MEMORY_CONNECTOR_CONTENT_REQUIRED+ ? message+ : MEMORY_INVALID_FILTER;+ return errorResponse(error, fallback, 400);+ }++ const [err, result] = await asaw(+ updateProjectMemory({ id, connectorId, content, metadata })+ );+ if (err) {+ const message = err instanceof Error ? err.message : String(err);+ return errorResponse(err, MEMORY_EDIT_FAILED, mutationStatus(message));+ }+ return Response.json(result);+}++async function DELETEHandler(+ request: NextRequest,+ { params }: { params: { id: string } }+) {+ const user = await getCurrentUser();+ if (!user) return Response.json("Unauthorized", { status: 401 });++ let id: string;+ let connectorId: string | undefined;+ try {+ id = parseId(params.id);+ connectorId = parseConnectorId(request.nextUrl.searchParams.get("connectorId"));+ } catch (error) {+ return errorResponse(error, MEMORY_INVALID_FILTER, 400);+ }++ const [err, result] = await asaw(deleteProjectMemory({ id, connectorId }));+ if (err) {+ const message = err instanceof Error ? err.message : String(err);+ return errorResponse(err, MEMORY_DELETE_FAILED, mutationStatus(message));+ }+ return Response.json(result);+}++export const GET = withMemoryAccess("read", GETHandler);+export const PATCH = withMemoryAudit(withMemoryAccess("update", PATCHHandler));+export const DELETE = withMemoryAudit(withMemoryAccess("delete", DELETEHandler));diff --git a/src/client/src/app/api/memory/copy/route.ts b/src/client/src/app/api/memory/copy/route.tsnew file mode 100644index 00000000..c43f7599--- /dev/null+++ b/src/client/src/app/api/memory/copy/route.ts@@ -0,0 +1,124 @@+import { NextRequest } from "next/server";+import { getCurrentUser } from "@/lib/session";+import { errorResponse } from "@/utils/api-response";+import asaw from "@/utils/asaw";+import { withMemoryAccess, withMemoryAudit } from "@/lib/access/memory-route";+import { isMemoryConnectorId, memoryConnectorId } from "@/lib/platform/connectors/memory/crud";+import { copyProjectMemories } from "@/lib/platform/connectors/memory/port";+import {+ MEMORY_ADD_UNSUPPORTED,+ MEMORY_CONNECTOR_NOT_FOUND,+ MEMORY_COPY_EMPTY,+ MEMORY_COPY_FAILED,+ MEMORY_COPY_SAME_CONNECTOR,+ MEMORY_COPY_TOO_MANY,+ MEMORY_INVALID_FILTER,+ MEMORY_INVALID_JSON,+} from "@/constants/messages/en";++const FILTER_MAX = 200;+const ID_MAX = 200;+const COPY_IDS_MAX = 50;++function optionalFilter(value: unknown, max = FILTER_MAX): string | undefined {+ if (value == null) return undefined;+ if (typeof value !== "string") throw new Error(MEMORY_INVALID_FILTER);+ const trimmed = value.trim();+ if (!trimmed) return undefined;+ if (trimmed.length > max || /[\u0000-\u001f]/.test(trimmed)) {+ throw new Error(MEMORY_INVALID_FILTER);+ }+ return trimmed;+}++function parseConnectorId(value: unknown): string {+ const trimmed = optionalFilter(value, 120);+ if (!trimmed) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ const id = memoryConnectorId(trimmed);+ if (!isMemoryConnectorId(id)) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ return id;+}++function parseMemoryIds(value: unknown): string[] | undefined {+ if (value == null) return undefined;+ if (!Array.isArray(value)) throw new Error(MEMORY_INVALID_FILTER);+ if (value.length > COPY_IDS_MAX) throw new Error(MEMORY_COPY_TOO_MANY);+ return value.map((item) => {+ if (typeof item !== "string") throw new Error(MEMORY_INVALID_FILTER);+ const trimmed = item.trim();+ if (!trimmed || trimmed.length > ID_MAX) throw new Error(MEMORY_INVALID_FILTER);+ return trimmed;+ });+}++function copyStatus(message: string): number {+ if (message === MEMORY_CONNECTOR_NOT_FOUND) return 404;+ if (+ message === MEMORY_ADD_UNSUPPORTED ||+ message === MEMORY_COPY_EMPTY ||+ message === MEMORY_COPY_SAME_CONNECTOR ||+ message === MEMORY_COPY_TOO_MANY+ ) {+ return 400;+ }+ return 400;+}++async function POSTHandler(request: NextRequest) {+ const user = await getCurrentUser();+ if (!user) return Response.json("Unauthorized", { status: 401 });++ let body: Record<string, unknown>;+ try {+ body = (await request.json()) as Record<string, unknown>;+ } catch {+ return errorResponse(MEMORY_INVALID_JSON, MEMORY_INVALID_JSON, 400);+ }++ let sourceConnectorId: string;+ let targetConnectorId: string;+ let memoryIds: string[] | undefined;+ let userId: string | undefined;+ let agentId: string | undefined;+ let sessionId: string | undefined;+ let query: string | undefined;+ let targetUserId: string | undefined;+ let targetAgentId: string | undefined;+ let targetSessionId: string | undefined;+ try {+ sourceConnectorId = parseConnectorId(body.sourceConnectorId);+ targetConnectorId = parseConnectorId(body.targetConnectorId);+ memoryIds = parseMemoryIds(body.memoryIds);+ userId = optionalFilter(body.userId);+ agentId = optionalFilter(body.agentId);+ sessionId = optionalFilter(body.sessionId);+ query = optionalFilter(body.query, 2000);+ targetUserId = optionalFilter(body.targetUserId);+ targetAgentId = optionalFilter(body.targetAgentId);+ targetSessionId = optionalFilter(body.targetSessionId);+ } catch (error) {+ return errorResponse(error, MEMORY_INVALID_FILTER, 400);+ }++ const [err, result] = await asaw(+ copyProjectMemories({+ sourceConnectorId,+ targetConnectorId,+ memoryIds,+ userId,+ agentId,+ sessionId,+ query,+ targetUserId,+ targetAgentId,+ targetSessionId,+ })+ );+ if (err) {+ const message = err instanceof Error ? err.message : String(err);+ return errorResponse(err, MEMORY_COPY_FAILED, copyStatus(message));+ }+ return Response.json(result);+}++export const POST = withMemoryAudit(withMemoryAccess("create", POSTHandler));diff --git a/src/client/src/app/api/memory/route.ts b/src/client/src/app/api/memory/route.tsnew file mode 100644index 00000000..120f8b99--- /dev/null+++ b/src/client/src/app/api/memory/route.ts@@ -0,0 +1,174 @@+import { NextRequest } from "next/server";+import { getCurrentUser } from "@/lib/session";+import { errorResponse } from "@/utils/api-response";+import asaw from "@/utils/asaw";+import { withMemoryAccess, withMemoryAudit } from "@/lib/access/memory-route";+import { isMemoryConnectorId, memoryConnectorId } from "@/lib/platform/connectors/memory/crud";+import { queryProjectMemories } from "@/lib/platform/connectors/memory/read";+import {+ addProjectMemories,+ parseMemoryMessages,+ parseMemoryMetadata,+} from "@/lib/platform/connectors/memory/write";+import {+ MEMORY_ADD_FAILED,+ MEMORY_ADD_UNSUPPORTED,+ MEMORY_CONNECTOR_CONTENT_REQUIRED,+ MEMORY_CONNECTOR_NOT_FOUND,+ MEMORY_CONNECTOR_SESSION_REQUIRED,+ MEMORY_CONTENT_TOO_LONG,+ MEMORY_INVALID_FILTER,+ MEMORY_INVALID_JSON,+ MEMORY_INVALID_LIMIT,+ MEMORY_INVALID_METADATA,+ MEMORY_LOAD_FAILED,+} from "@/constants/messages/en";++const FILTER_MAX = 200;+const QUERY_MAX = 2000;++function optionalFilter(value: string | null, max = FILTER_MAX): string | undefined {+ if (value == null) return undefined;+ const trimmed = value.trim();+ if (!trimmed) return undefined;+ if (trimmed.length > max || /[\u0000-\u001f]/.test(trimmed)) {+ throw new Error(MEMORY_INVALID_FILTER);+ }+ return trimmed;+}++function parseLimit(value: string | null): number | undefined {+ if (value == null || !value.trim()) return undefined;+ const parsed = Number(value);+ if (!Number.isFinite(parsed) || parsed < 1 || parsed > 100) {+ throw new Error(MEMORY_INVALID_LIMIT);+ }+ return Math.floor(parsed);+}++function parseConnectorId(value: string | null | undefined): string | undefined {+ if (value == null) return undefined;+ const trimmed = optionalFilter(String(value), 120);+ if (!trimmed) return undefined;+ const id = memoryConnectorId(trimmed);+ if (!isMemoryConnectorId(id)) {+ throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ }+ return id;+}++function optionalBodyFilter(value: unknown): string | undefined {+ if (value == null) return undefined;+ if (typeof value !== "string") throw new Error(MEMORY_INVALID_FILTER);+ return optionalFilter(value);+}++function writeStatus(message: string): number {+ if (message === MEMORY_CONNECTOR_NOT_FOUND) return 404;+ if (+ message === MEMORY_ADD_UNSUPPORTED ||+ message === MEMORY_CONNECTOR_CONTENT_REQUIRED ||+ message === MEMORY_CONNECTOR_SESSION_REQUIRED ||+ message === MEMORY_CONTENT_TOO_LONG ||+ message === MEMORY_INVALID_METADATA+ ) {+ return 400;+ }+ return 400;+}++async function GETHandler(request: NextRequest) {+ const user = await getCurrentUser();+ if (!user) return Response.json("Unauthorized", { status: 401 });++ let connectorId: string | undefined;+ let userId: string | undefined;+ let agentId: string | undefined;+ let sessionId: string | undefined;+ let query: string | undefined;+ let limit: number | undefined;+ try {+ const params = request.nextUrl.searchParams;+ connectorId = parseConnectorId(params.get("connectorId"));+ userId = optionalFilter(params.get("userId"));+ agentId = optionalFilter(params.get("agentId"));+ sessionId = optionalFilter(params.get("sessionId"));+ query = optionalFilter(params.get("q"), QUERY_MAX);+ limit = parseLimit(params.get("limit"));+ } catch (error) {+ return errorResponse(error, MEMORY_INVALID_FILTER, 400);+ }++ const [err, result] = await asaw(+ queryProjectMemories({+ connectorId,+ userId,+ agentId,+ sessionId,+ query,+ limit,+ })+ );+ if (err) {+ const message = err instanceof Error ? err.message : String(err);+ const status = message === MEMORY_CONNECTOR_NOT_FOUND ? 404 : 400;+ return errorResponse(err, MEMORY_LOAD_FAILED, status);+ }+ return Response.json(result);+}++async function POSTHandler(request: NextRequest) {+ const user = await getCurrentUser();+ if (!user) return Response.json("Unauthorized", { status: 401 });++ let body: Record<string, unknown>;+ try {+ body = (await request.json()) as Record<string, unknown>;+ } catch {+ return errorResponse(MEMORY_INVALID_JSON, MEMORY_INVALID_JSON, 400);+ }++ let connectorId: string | undefined;+ let userId: string | undefined;+ let agentId: string | undefined;+ let sessionId: string | undefined;+ let content: string | undefined;+ let messages;+ let metadata;+ try {+ connectorId = parseConnectorId(+ typeof body.connectorId === "string" ? body.connectorId : undefined+ );+ userId = optionalBodyFilter(body.userId);+ agentId = optionalBodyFilter(body.agentId);+ sessionId = optionalBodyFilter(body.sessionId);+ if (body.content != null && typeof body.content !== "string") {+ throw new Error(MEMORY_CONNECTOR_CONTENT_REQUIRED);+ }+ content = typeof body.content === "string" ? body.content : undefined;+ messages = parseMemoryMessages(body.messages);+ metadata = parseMemoryMetadata(body.metadata);+ } catch (error) {+ return errorResponse(error, MEMORY_INVALID_FILTER, 400);+ }++ const [err, result] = await asaw(+ addProjectMemories({+ connectorId,+ content,+ messages,+ userId,+ agentId,+ sessionId,+ metadata,+ })+ );+ if (err) {+ const message = err instanceof Error ? err.message : String(err);+ return errorResponse(err, MEMORY_ADD_FAILED, writeStatus(message));+ }+ return Response.json(result);+}++export const GET = withMemoryAccess("read", GETHandler);+export const POST = withMemoryAudit(withMemoryAccess("create", POSTHandler));diff --git a/src/client/src/components/(playground)/chat/ask-otter-panel.tsx b/src/client/src/components/(playground)/chat/ask-otter-panel.tsxnew file mode 100644index 00000000..204a33e9--- /dev/null+++ b/src/client/src/components/(playground)/chat/ask-otter-panel.tsx@@ -0,0 +1,326 @@+"use client";++import { FormEvent, useCallback, useEffect, useRef, useState } from "react";+import Link from "next/link";+import ReactMarkdown from "react-markdown";+import { Loader2, Send, Sparkles } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import getMessage from "@/constants/messages";+import { getRequestHeaders } from "@/utils/api";+import { cn } from "@/lib/utils";++export type AskOtterCopy = {+ title: string;+ empty: string;+ placeholder: string;+ hint: string;+ send: string;+ conversationTitle?: string;+};++export type AskOtterPanelProps = {+ /** Disable ask when the host page has no usable context (e.g. no connectors). */+ disabled?: boolean;+ /** Page-owned strings so the same panel can sit on Memory, traces, etc. */+ copy: AskOtterCopy;+ /** Host builds the chat prompt (filters, selected item, system instructions). */+ buildPrompt: (question: string) => string;+ /** Optional chip for the currently selected item on the host page. */+ contextLabel?: string | null;+ /**+ * `dock` — compact bottom strip.+ * `fill` — full-height column for side panels / resizable hosts.+ */+ layout?: "dock" | "fill";+ className?: string;+};++type AskMessage = {+ id: string;+ role: "user" | "assistant";+ content: string;+ steps?: string[];+};++export default function AskOtterPanel({+ disabled,+ copy,+ buildPrompt,+ contextLabel,+ layout = "dock",+ className,+}: AskOtterPanelProps) {+ const messages = getMessage();+ const [question, setQuestion] = useState("");+ const [hasConfig, setHasConfig] = useState<boolean | null>(null);+ const [thread, setThread] = useState<AskMessage[]>([]);+ const [streaming, setStreaming] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const conversationIdRef = useRef<string | null>(null);+ const abortRef = useRef<AbortController | null>(null);+ const listRef = useRef<HTMLDivElement | null>(null);++ useEffect(() => {+ let cancelled = false;+ fetch("/api/chat/config")+ .then((response) => response.json())+ .then((body) => {+ if (!cancelled) setHasConfig(!!body?.data?.provider);+ })+ .catch(() => {+ if (!cancelled) setHasConfig(false);+ });+ return () => {+ cancelled = true;+ abortRef.current?.abort();+ };+ }, []);++ useEffect(() => {+ listRef.current?.scrollTo?.({ top: listRef.current.scrollHeight });+ }, [thread, streaming]);++ const ensureConversation = useCallback(async (): Promise<string | null> => {+ if (conversationIdRef.current) return conversationIdRef.current;+ const response = await fetch("/api/chat/conversation", {+ method: "POST",+ headers: getRequestHeaders({ "Content-Type": "application/json" }),+ body: JSON.stringify({+ title: copy.conversationTitle || copy.title,+ provider: "",+ model: "",+ }),+ });+ const body = await response.json().catch(() => null);+ const id = typeof body?.data === "string" ? body.data : body?.data?.id;+ if (!response.ok || !id) {+ throw new Error(+ typeof body === "string"+ ? body+ : body?.err || messages.CHAT_FAILED_TO_CREATE_CONVERSATION+ );+ }+ conversationIdRef.current = String(id);+ return conversationIdRef.current;+ }, [+ copy.conversationTitle,+ copy.title,+ messages.CHAT_FAILED_TO_CREATE_CONVERSATION,+ ]);++ const submit = async (event: FormEvent) => {+ event.preventDefault();+ const text = question.trim();+ if (!text || disabled || streaming || hasConfig === false) return;+ setError(null);+ setQuestion("");+ const userMessage: AskMessage = {+ id: `user-${Date.now()}`,+ role: "user",+ content: text,+ };+ const assistantId = `assistant-${Date.now()}`;+ setThread((current) => [+ ...current,+ userMessage,+ { id: assistantId, role: "assistant", content: "", steps: [] },+ ]);+ setStreaming(true);++ try {+ const conversationId = await ensureConversation();+ if (!conversationId) throw new Error(messages.CHAT_FAILED_TO_CREATE_CONVERSATION);+ const controller = new AbortController();+ abortRef.current = controller;+ const response = await fetch("/api/chat/message", {+ method: "POST",+ headers: getRequestHeaders({ "Content-Type": "application/json" }),+ body: JSON.stringify({+ conversationId,+ content: buildPrompt(text),+ }),+ signal: controller.signal,+ });+ if (!response.ok) {+ const errText = await response.text();+ throw new Error(errText || messages.CHAT_FAILED_TO_GET_RESPONSE);+ }+ const reader = response.body?.getReader();+ if (!reader) throw new Error(messages.CHAT_NO_RESPONSE_STREAM);+ const decoder = new TextDecoder();+ let fullText = "";+ let buffer = "";+ const steps: string[] = [];+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split("\n");+ buffer = lines.pop() || "";+ for (const line of lines) {+ if (!line.trim()) continue;+ try {+ const eventLine = JSON.parse(line) as {+ type?: string;+ text?: string;+ label?: string;+ error?: string;+ };+ if (eventLine.type === "step" && eventLine.label) {+ steps.push(eventLine.label);+ setThread((current) =>+ current.map((item) =>+ item.id === assistantId ? { ...item, steps: [...steps] } : item+ )+ );+ continue;+ }+ if (eventLine.type === "delta") {+ fullText += eventLine.text || "";+ setThread((current) =>+ current.map((item) =>+ item.id === assistantId ? { ...item, content: fullText } : item+ )+ );+ continue;+ }+ if (eventLine.type === "error") {+ throw new Error(eventLine.error || messages.CHAT_SOMETHING_WENT_WRONG);+ }+ } catch (parseError) {+ if (parseError instanceof SyntaxError) {+ fullText += line;+ setThread((current) =>+ current.map((item) =>+ item.id === assistantId ? { ...item, content: fullText } : item+ )+ );+ } else {+ throw parseError;+ }+ }+ }+ }+ } catch (caught) {+ if ((caught as { name?: string })?.name === "AbortError") return;+ const message =+ caught instanceof Error ? caught.message : messages.CHAT_SOMETHING_WENT_WRONG;+ setError(message);+ setThread((current) =>+ current.map((item) =>+ item.id === assistantId+ ? {+ ...item,+ content: item.content || `**${messages.CHAT_ERROR_PREFIX}** ${message}`,+ }+ : item+ )+ );+ } finally {+ setStreaming(false);+ abortRef.current = null;+ }+ };++ const blocked = disabled || hasConfig === false || streaming;++ return (+ <section+ className={cn(+ "flex min-h-0 flex-col bg-stone-50 dark:bg-stone-900",+ layout === "fill"+ ? "h-full border-0"+ : "border-t border-stone-200 dark:border-stone-800",+ className+ )}+ >+ <div className="flex shrink-0 items-center gap-1.5 border-b border-stone-200 px-3 py-2.5 dark:border-stone-800">+ <Sparkles className="size-3.5 text-violet-600 dark:text-violet-300" />+ <p className="min-w-0 flex-1 truncate text-sm font-semibold text-stone-900 dark:text-stone-50">+ {copy.title}+ </p>+ {contextLabel ? (+ <p+ title={contextLabel}+ className="max-w-[55%] truncate rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary"+ >+ {contextLabel}+ </p>+ ) : null}+ </div>+ <div+ ref={listRef}+ className={cn(+ "min-h-0 space-y-2 overflow-auto px-3 py-3",+ layout === "fill" ? "flex-1" : "max-h-44"+ )}+ >+ {thread.length === 0 ? (+ <p className="text-xs leading-5 text-stone-500 dark:text-stone-400">+ {copy.empty}+ </p>+ ) : (+ thread.map((item) => (+ <div+ key={item.id}+ className={`rounded-md px-2.5 py-1.5 text-xs ${+ item.role === "user"+ ? "bg-stone-100 text-stone-800 dark:bg-stone-900 dark:text-stone-200"+ : "text-stone-700 dark:text-stone-300"+ }`}+ >+ {item.role === "assistant" && item.steps?.length ? (+ <p className="mb-1 text-[10px] uppercase tracking-wide text-stone-400">+ {item.steps[item.steps.length - 1]}+ </p>+ ) : null}+ {item.role === "assistant" ? (+ <div className="prose prose-sm max-w-none dark:prose-invert prose-p:my-1 prose-pre:my-1">+ <ReactMarkdown>{item.content || (streaming ? "…" : "")}</ReactMarkdown>+ </div>+ ) : (+ <p>{item.content}</p>+ )}+ </div>+ ))+ )}+ </div>+ <div className="shrink-0 border-t border-stone-200 px-3 py-3 dark:border-stone-800">+ {hasConfig === false ? (+ <p className="mb-2 text-xs text-amber-800 dark:text-amber-200">+ {messages.CHAT_CONFIGURE_PROVIDER}{" "}+ <Link href="/chat/settings" className="underline font-medium">+ {messages.CHAT_SETTINGS_LINK}+ </Link>{" "}+ {messages.CHAT_TO_GET_STARTED}+ </p>+ ) : null}+ {error && hasConfig !== false ? (+ <p className="mb-2 text-xs text-error">{error}</p>+ ) : null}+ <form onSubmit={submit} className="flex items-center gap-2">+ <Input+ value={question}+ onChange={(event) => setQuestion(event.target.value)}+ placeholder={copy.placeholder}+ disabled={blocked || hasConfig === null}+ className="h-9"+ />+ <Button+ type="submit"+ size="sm"+ disabled={blocked || hasConfig === null || !question.trim()}+ className="shrink-0 gap-1.5"+ >+ {streaming ? <Loader2 className="size-3.5 animate-spin" /> : <Send className="size-3.5" />}+ {copy.send}+ </Button>+ </form>+ <p className="mt-1.5 text-[11px] text-stone-500 dark:text-stone-400">+ {copy.hint}+ </p>+ </div>+ </section>+ );+}diff --git a/src/client/src/components/(playground)/chat/chat-floating-button.tsx b/src/client/src/components/(playground)/chat/chat-floating-button.tsxindex 2c32c722..65791e24 100644--- a/src/client/src/components/(playground)/chat/chat-floating-button.tsx+++ b/src/client/src/components/(playground)/chat/chat-floating-button.tsx@@ -9,6 +9,7 @@ import {TooltipTrigger,} from "@/components/ui/tooltip";import Otter from "@/components/svg/otter";+import getMessage from "@/constants/messages";const OTTER_TOOLTIPS = ["Hi, I'm Otter 🦦, ask me anything!",@@ -61,6 +62,7 @@ export default function ChatFloatingButton() {}export function ChatHeaderButton() {+ const messages = getMessage();const tooltip = useMemo(() => OTTER_TOOLTIPS[Math.floor(Math.random() * OTTER_TOOLTIPS.length)],[]@@ -69,17 +71,14 @@ export function ChatHeaderButton() {return (<Tooltip><TooltipTrigger asChild>- <span className="relative isolate inline-flex overflow-hidden rounded-md p-px shadow-sm transition-shadow hover:shadow-primary/25">- <span className="absolute inset-[-250%] animate-[spin_4s_linear_infinite] bg-[conic-gradient(from_90deg_at_50%_50%,#f97316_0deg,#ec4899_90deg,#8b5cf6_180deg,#06b6d4_270deg,#f97316_360deg)]" />- <Link- href="/chat"- aria-label="Ask Otter"- className="group relative flex h-8 items-center gap-1.5 rounded-[5px] bg-white px-2.5 text-xs font-semibold text-stone-800 transition-colors hover:bg-stone-50 dark:bg-stone-950 dark:text-stone-100 dark:hover:bg-stone-900"- >- <Otter className="h-5 w-5 transition-transform group-hover:rotate-6" />- <span>Ask Otter</span>- </Link>- </span>+ <Link+ href="/chat"+ aria-label={messages.CHAT_ASK_OTTER}+ className="group inline-flex h-8 items-center gap-1.5 rounded-md bg-primary px-2.5 text-xs font-semibold text-white shadow-sm transition-colors hover:bg-primary/90"+ >+ <Otter className="h-5 w-5 text-white transition-transform group-hover:rotate-6" />+ <span>{messages.CHAT_ASK_OTTER}</span>+ </Link></TooltipTrigger><TooltipContent side="bottom" className="max-w-xs text-xs"><p>{tooltip}</p></TooltipContent></Tooltip>diff --git a/src/client/src/components/(playground)/chat/chat-layout.tsx b/src/client/src/components/(playground)/chat/chat-layout.tsxindex 08baabb9..279edf12 100644--- a/src/client/src/components/(playground)/chat/chat-layout.tsx+++ b/src/client/src/components/(playground)/chat/chat-layout.tsx@@ -23,9 +23,10 @@ import { toast } from "sonner";interface ChatLayoutProps {initialConversationId: string | null;initialView?: "chat" | "usage" | "settings";+ initialPrompt?: string | null;}-export default function ChatLayout({ initialConversationId, initialView = "chat" }: ChatLayoutProps) {+export default function ChatLayout({ initialConversationId, initialView = "chat", initialPrompt }: ChatLayoutProps) {const m = getMessage();const router = useRouter();const posthog = usePostHog();@@ -147,6 +148,7 @@ export default function ChatLayout({ initialConversationId, initialView = "chat"hasConfig={hasConfig && !loadingConfig}configInfo={configInfo}onNewConversation={handleNewConversation}+ initialPrompt={initialPrompt}/>)}</div>diff --git a/src/client/src/components/(playground)/chat/chat-panel.tsx b/src/client/src/components/(playground)/chat/chat-panel.tsxindex 7fcb8768..93155a0d 100644--- a/src/client/src/components/(playground)/chat/chat-panel.tsx+++ b/src/client/src/components/(playground)/chat/chat-panel.tsx@@ -21,6 +21,7 @@ interface ChatPanelProps {hasConfig: boolean;configInfo?: ChatConfigInfo | null;onNewConversation: () => Promise<string | null>;+ initialPrompt?: string | null;}export default function ChatPanel({@@ -28,6 +29,7 @@ export default function ChatPanel({hasConfig,configInfo,onNewConversation,+ initialPrompt,}: ChatPanelProps) {const posthog = usePostHog();const messages = useRootStore(getChatMessages);@@ -44,6 +46,8 @@ export default function ChatPanel({const inputRef = useRef("");const abortControllerRef = useRef<AbortController | null>(null);const skipNextLoadRef = useRef(false);+ const sentInitialPromptRef = useRef(false);+ const sendMessageRef = useRef<(text?: string) => Promise<void>>(async () => {});// Input state — ref avoids re-renders, state keeps textarea controlledconst [inputValue, setInputValue] = useInputState(inputRef);@@ -284,6 +288,16 @@ export default function ChatPanel({[conversationId, isStreaming, messages, onNewConversation, addMessage, posthog, updateLastMessage, updateLastMessageStep, setMessages, setIsStreaming, setInputValue, refreshConversation]);+ sendMessageRef.current = sendMessage;++ useEffect(() => {+ if (sentInitialPromptRef.current) return;+ const prompt = initialPrompt?.trim();+ if (!prompt || !hasConfig) return;+ sentInitialPromptRef.current = true;+ void sendMessageRef.current(prompt);+ }, [initialPrompt, hasConfig]);+const handleExecuteQuery = useCallback(async (query: string, messageId?: string) => {try {@@ -316,7 +330,7 @@ export default function ChatPanel({[posthog]);- const showEmptyState = !conversationId && messages.length === 0 && !isStreaming;+ const showEmptyState = !conversationId && messages.length === 0 && !isStreaming && !initialPrompt?.trim();return (<div className="flex flex-col h-full">diff --git a/src/client/src/components/(playground)/chat/entity-card.tsx b/src/client/src/components/(playground)/chat/entity-card.tsxindex 2f8314a3..dfaca849 100644--- a/src/client/src/components/(playground)/chat/entity-card.tsx+++ b/src/client/src/components/(playground)/chat/entity-card.tsx@@ -2,6 +2,7 @@import Link from "next/link";import {+ BrainCircuit,SlidersHorizontal,BookOpen,BookKey,@@ -18,6 +19,7 @@ const ENTITY_ICONS: Record<string, React.ElementType> = {model: SettingsIcon,evaluation: MonitorCog,vault: BookKey,+ memory: BrainCircuit,};const ENTITY_COLORS: Record<string, { bg: string; border: string; icon: string; text: string }> = {@@ -57,6 +59,12 @@ const ENTITY_COLORS: Record<string, { bg: string; border: string; icon: string;icon: "text-rose-600 dark:text-rose-400",text: "text-rose-700 dark:text-rose-300",},+ memory: {+ bg: "bg-violet-50 dark:bg-violet-950/20",+ border: "border-violet-200 dark:border-violet-800",+ icon: "text-violet-600 dark:text-violet-400",+ text: "text-violet-700 dark:text-violet-300",+ },};const DEFAULT_COLORS = {diff --git a/src/client/src/components/(playground)/connectors/connectors-page.tsx b/src/client/src/components/(playground)/connectors/connectors-page.tsxindex 51e3d9c5..2d0ffc4d 100644--- a/src/client/src/components/(playground)/connectors/connectors-page.tsx+++ b/src/client/src/components/(playground)/connectors/connectors-page.tsx@@ -184,8 +184,8 @@ export default function ConnectorsPage() {<Inputvalue={search}onChange={(event) => setSearch(event.target.value)}- placeholder="Search connectors"- aria-label="Search connectors"+ placeholder={messages.CONNECTOR_SEARCH_PLACEHOLDER}+ aria-label={messages.CONNECTOR_SEARCH_PLACEHOLDER}className="h-9 pl-9"/></div>@@ -309,7 +309,7 @@ export default function ConnectorsPage() {))}</Accordion>{!filteredConnectorGroups.length && (- <p className="py-10 text-center text-sm text-muted-foreground">No connectors match your search.</p>+ <p className="py-10 text-center text-sm text-muted-foreground">{messages.CONNECTOR_NO_MATCHES}</p>)}</>)}diff --git a/src/client/src/components/(playground)/database-config/database-config-page.tsx b/src/client/src/components/(playground)/database-config/database-config-page.tsxindex c3de6265..2008fec1 100644--- a/src/client/src/components/(playground)/database-config/database-config-page.tsx+++ b/src/client/src/components/(playground)/database-config/database-config-page.tsx@@ -252,6 +252,10 @@ function DatabaseList({openNew,onOpenNewHandled,hideEmpty,+ hideList,+ editing: controlledEditing,+ onEditingChange,+ onConfigSaved,}: {dbConfigs: DatabaseConfigWithActive[];canCreate: boolean;@@ -262,10 +266,16 @@ function DatabaseList({openNew?: boolean;onOpenNewHandled?: () => void;hideEmpty?: boolean;+ hideList?: boolean;+ editing?: DatabaseConfigWithActive | "new" | null;+ onEditingChange?: (next: DatabaseConfigWithActive | "new" | null) => void;+ onConfigSaved?: () => void;}) {const messages = getMessage();const selectedEnvironment = useRootStore(getCurrentProjectEnvironment) || "production";- const [editing, setEditing] = useState<DatabaseConfigWithActive | "new" | null>(null);+ const [internalEditing, setInternalEditing] = useState<DatabaseConfigWithActive | "new" | null>(null);+ const editing = controlledEditing !== undefined ? controlledEditing : internalEditing;+ const setEditing = onEditingChange || setInternalEditing;const [testingId, setTestingId] = useState<string | null>(null);const visibleConfigs = useMemo(() => dbConfigs.filter((config) => (config.environment || "production").toLowerCase() === selectedEnvironment.toLowerCase()),@@ -298,6 +308,24 @@ function DatabaseList({}};+ const dialog = editing ? (+ <Dialog open onOpenChange={(open) => !open && setEditing(null)}>+ <DialogContent className="max-h-[92vh] w-[calc(100vw-2rem)] max-w-3xl overflow-y-auto p-0">+ <ModifyDatabaseConfig+ dbConfig={editing === "new" ? undefined : editing}+ canCreate={canCreate}+ canUpdate={canUpdate}+ onSaved={() => {+ setEditing(null);+ onConfigSaved?.();+ }}+ />+ </DialogContent>+ </Dialog>+ ) : null;++ if (hideList) return dialog;+return (<div className={hideHeader ? "relative contents" : "relative w-full p-4"}>{!hideHeader && <div className="mb-4 flex flex-wrap items-center justify-between gap-3">@@ -328,7 +356,7 @@ function DatabaseList({))}</div>)}- {editing && <Dialog open onOpenChange={(open) => !open && setEditing(null)}><DialogContent className="max-h-[92vh] w-[calc(100vw-2rem)] max-w-3xl overflow-y-auto p-0"><ModifyDatabaseConfig dbConfig={editing === "new" ? undefined : editing} canCreate={canCreate} canUpdate={canUpdate} onSaved={() => setEditing(null)} /></DialogContent></Dialog>}+ {dialog}</div>);}@@ -342,6 +370,10 @@ export default function Database({openNew = false,onOpenNewHandled,hideEmpty = false,+ hideList = false,+ editing,+ onEditingChange,+ onConfigSaved,}: {canCreate?: boolean;canUpdate?: boolean;@@ -351,9 +383,31 @@ export default function Database({openNew?: boolean;onOpenNewHandled?: () => void;hideEmpty?: boolean;+ hideList?: boolean;+ editing?: DatabaseConfigWithActive | "new" | null;+ onEditingChange?: (next: DatabaseConfigWithActive | "new" | null) => void;+ onConfigSaved?: () => void;}) {const databaseList = useRootStore(getDatabaseConfigList);+ if (isNil(databaseList) && hideList) {+ return (+ <DatabaseList+ dbConfigs={[]}+ canCreate={canCreate}+ canUpdate={canUpdate}+ canDelete={canDelete}+ canShare={canShare}+ hideHeader+ hideEmpty+ hideList+ editing={editing}+ onEditingChange={onEditingChange}+ onConfigSaved={onConfigSaved}+ />+ );+ }+return isNil(databaseList) ? (<div className={hideHeader ? "contents" : "p-4"}><div className="flex min-h-[190px] flex-col gap-4 rounded-lg border border-stone-200 bg-stone-50/70 p-3 dark:border-stone-800 dark:bg-stone-900/50">@@ -373,6 +427,10 @@ export default function Database({openNew={openNew}onOpenNewHandled={onOpenNewHandled}hideEmpty={hideEmpty}+ hideList={hideList}+ editing={editing}+ onEditingChange={onEditingChange}+ onConfigSaved={onConfigSaved}/>);}diff --git a/src/client/src/components/(playground)/memory/ask-otter.tsx b/src/client/src/components/(playground)/memory/ask-otter.tsxnew file mode 100644index 00000000..034154a6--- /dev/null+++ b/src/client/src/components/(playground)/memory/ask-otter.tsx@@ -0,0 +1,45 @@+"use client";++import getMessage from "@/constants/messages";+import {+ buildMemoryAskPrompt,+ memoryAskSelectedSummary,+ type MemoryAskScope,+} from "@/lib/platform/connectors/memory/ask";+import AskOtterPanel from "@/components/(playground)/chat/ask-otter-panel";++type AskOtterBarProps = {+ disabled?: boolean;+ scope?: MemoryAskScope;+ /** Pass `fill` when embedding beside a resizable host panel. */+ layout?: "dock" | "fill";+ className?: string;+};++/** Memory-page adapter around the shared Ask Otter panel. */+export default function AskOtterBar({+ disabled,+ scope,+ layout = "dock",+ className,+}: AskOtterBarProps) {+ const messages = getMessage();+ const selected = memoryAskSelectedSummary(scope);+ return (+ <AskOtterPanel+ disabled={disabled}+ layout={layout}+ className={className}+ copy={{+ title: messages.MEMORY_ASK_TITLE,+ empty: messages.MEMORY_ASK_EMPTY,+ placeholder: messages.MEMORY_ASK_PLACEHOLDER,+ hint: messages.MEMORY_ASK_HINT,+ send: messages.MEMORY_ASK_SEND,+ conversationTitle: messages.MEMORY_ASK_TITLE,+ }}+ contextLabel={selected ? messages.MEMORY_ASK_SELECTED_CHIP(selected) : undefined}+ buildPrompt={(question) => buildMemoryAskPrompt(question, scope)}+ />+ );+}diff --git a/src/client/src/components/(playground)/memory/memory-copy-dialog.tsx b/src/client/src/components/(playground)/memory/memory-copy-dialog.tsxnew file mode 100644index 00000000..2f975fe6--- /dev/null+++ b/src/client/src/components/(playground)/memory/memory-copy-dialog.tsx@@ -0,0 +1,210 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Label } from "@/components/ui/label";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import getMessage from "@/constants/messages";+import { getRequestHeaders } from "@/utils/api";+import {+ emptyMemoryFilters,+ type MemoryFilterField,+ type MemoryFilterKey,+ type MemoryFilterOptions,+} from "@/lib/platform/connectors/memory/types";+import {+ applyMemoryFilterChange,+ emptyMemoryFilterScope,+ keepDialogPopoverOpen,+ MemoryDialogFilterFields,+ memoryFilterRequiredMissing,+ trimmedMemoryFilterScope,+ type MemoryFilterScope,+} from "./memory-filter-fields";++export type MemoryCopyTarget = {+ id: string;+ name: string;+ type: string;+ environment?: string;+ capabilities?: { add?: boolean } | null;+ filterFields?: MemoryFilterField[];+};++export type MemoryCopyScope = {+ userId?: string;+ sessionId?: string;+ agentId?: string;+};++type MemoryCopyDialogProps = {+ open: boolean;+ count: number;+ targets: MemoryCopyTarget[];+ saving?: boolean;+ onOpenChange: (open: boolean) => void;+ onSubmit: (input: { targetConnectorId: string } & MemoryCopyScope) => void;+};++export default function MemoryCopyDialog({+ open,+ count,+ targets,+ saving,+ onOpenChange,+ onSubmit,+}: MemoryCopyDialogProps) {+ const messages = getMessage();+ const [targetId, setTargetId] = useState(targets[0]?.id || "");+ const [scope, setScope] = useState<MemoryFilterScope>(emptyMemoryFilterScope());+ const [filters, setFilters] = useState<MemoryFilterOptions>(emptyMemoryFilters());+ const [filterFields, setFilterFields] = useState<MemoryFilterField[]>([]);+ const [loadingFilters, setLoadingFilters] = useState(false);+ const targetsRef = useRef(targets);+ targetsRef.current = targets;++ useEffect(() => {+ if (!open) return;+ setTargetId((current) =>+ targets.some((target) => target.id === current) ? current : targets[0]?.id || ""+ );+ }, [open, targets]);++ useEffect(() => {+ if (!open || !targetId) {+ setFilters(emptyMemoryFilters());+ setFilterFields([]);+ setLoadingFilters(false);+ return;+ }+ const target = targetsRef.current.find((item) => item.id === targetId);+ setScope(emptyMemoryFilterScope());+ setFilters(emptyMemoryFilters());+ setFilterFields(target?.filterFields || []);+ const controller = new AbortController();+ setLoadingFilters(true);+ const params = new URLSearchParams({+ connectorId: targetId,+ limit: "1",+ });+ fetch(`/api/memory?${params.toString()}`, {+ signal: controller.signal,+ headers: getRequestHeaders(),+ })+ .then(async (response) => {+ const body = await response.json().catch(() => null);+ if (!response.ok) {+ throw new Error(messages.MEMORY_LOAD_FAILED);+ }+ return body as {+ filters?: MemoryFilterOptions;+ filterFields?: MemoryFilterField[];+ };+ })+ .then((payload) => {+ setFilters(payload.filters || emptyMemoryFilters());+ if (payload.filterFields?.length) setFilterFields(payload.filterFields);+ })+ .catch((error: unknown) => {+ if (controller.signal.aborted) return;+ if (error instanceof DOMException && error.name === "AbortError") return;+ setFilters(emptyMemoryFilters());+ })+ .finally(() => {+ if (!controller.signal.aborted) setLoadingFilters(false);+ });+ return () => controller.abort();+ }, [open, targetId, messages.MEMORY_LOAD_FAILED]);++ const canSave =+ !!targetId &&+ !saving &&+ !loadingFilters &&+ !memoryFilterRequiredMissing(filterFields, scope) &&+ count > 0;++ function setFieldValue(key: MemoryFilterKey, next: string) {+ setScope((current) => applyMemoryFilterChange(current, filters, key, next));+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ className="sm:max-w-lg"+ onPointerDownOutside={keepDialogPopoverOpen}+ onInteractOutside={keepDialogPopoverOpen}+ >+ <DialogHeader>+ <DialogTitle>{messages.MEMORY_COPY_TITLE}</DialogTitle>+ <DialogDescription>{messages.MEMORY_COPY_DESCRIPTION}</DialogDescription>+ </DialogHeader>+ <div className="space-y-3">+ {targets.length === 0 ? (+ <p className="text-sm text-muted-foreground">{messages.MEMORY_COPY_NO_TARGETS}</p>+ ) : (+ <div className="space-y-1.5">+ <Label>{messages.MEMORY_COPY_TARGET}</Label>+ <Select value={targetId} onValueChange={setTargetId} disabled={saving}>+ <SelectTrigger className="h-8" aria-label={messages.MEMORY_COPY_TARGET}>+ <SelectValue placeholder={messages.MEMORY_COPY_TARGET} />+ </SelectTrigger>+ <SelectContent>+ {targets.map((item) => (+ <SelectItem key={item.id} value={item.id}>+ {item.environment ? `${item.name} · ${item.environment}` : item.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )}+ <MemoryDialogFilterFields+ fields={filterFields}+ filters={filters}+ scope={scope}+ onChange={setFieldValue}+ disabled={saving || loadingFilters}+ />+ </div>+ <DialogFooter>+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={saving}+ onClick={() => onOpenChange(false)}+ >+ {messages.MEMORY_CANCEL}+ </Button>+ <Button+ type="button"+ size="sm"+ disabled={!canSave}+ onClick={() =>+ onSubmit({+ targetConnectorId: targetId,+ ...trimmedMemoryFilterScope(scope),+ })+ }+ >+ {messages.MEMORY_COPY_SAVE}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/client/src/components/(playground)/memory/memory-detail-sheet.tsx b/src/client/src/components/(playground)/memory/memory-detail-sheet.tsxnew file mode 100644index 00000000..cd41a29f--- /dev/null+++ b/src/client/src/components/(playground)/memory/memory-detail-sheet.tsx@@ -0,0 +1,1158 @@+"use client";++import { useEffect, useRef, useState, type ReactNode } from "react";+import { Angry, ArrowRightLeft, ChevronDown, ChevronUp, Copy, Pencil, ThumbsDown, ThumbsUp, Trash2, User, X } from "lucide-react";+import { toast } from "sonner";+import FeatureAccess from "@/components/rbac/feature-access";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { ResizeablePanel } from "@/components/ui/resizeable-panel";+import { Sheet, SheetContent } from "@/components/ui/sheet";+import { Skeleton } from "@/components/ui/skeleton";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import getMessage from "@/constants/messages";+import { formatBrowserDateTime, formatDatePartsValue } from "@/utils/date";+import { getRequestHeaders } from "@/utils/api";+import type { MemoryDetailResult, MemoryListItem } from "@/lib/platform/connectors/memory/read";+import type { MemoryKind } from "@/lib/platform/connectors/memory/graph";+import type {+ MemoryCapabilities,+ MemoryFeedback,+ MemoryFeedbackRating,+ MemoryHistoryEvent,+ MemoryMessage,+} from "@/lib/platform/connectors/memory/types";+import MemoryWriteDialog from "./memory-write-dialog";++const DETAIL_SHEET_CONTENT_CLASS =+ "right-2 top-2 bottom-2 flex h-auto w-auto max-w-none flex-col gap-0 border-0 bg-transparent p-0 shadow-none focus-visible:outline-none sm:max-w-none";++const KIND_DOT: Record<MemoryKind, string> = {+ temporal: "bg-teal-500",+ profile: "bg-orange-500",+ summary: "bg-lime-500",+};++const CATEGORY_DOTS = [+ "bg-sky-500",+ "bg-pink-500",+ "bg-violet-500",+ "bg-teal-500",+ "bg-orange-500",+ "bg-lime-500",+];++type MemoryDetailSheetProps = {+ open: boolean;+ memoryId: string | null;+ memoryIds?: string[];+ connectorId?: string;+ capabilities?: MemoryCapabilities | null;+ preview?: MemoryListItem | null;+ onSelect?: (id: string) => void;+ onClose: () => void;+ onChanged?: () => void;+ onCopy?: (id: string) => void;+ onOpenSource?: (connectorId: string, memoryId: string) => void;+};++export default function MemoryDetailSheet({+ open,+ memoryId,+ memoryIds = [],+ connectorId,+ capabilities,+ preview,+ onSelect,+ onClose,+ onChanged,+ onCopy,+ onOpenSource,+}: MemoryDetailSheetProps) {+ const messages = getMessage();+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [hint, setHint] = useState<MemoryDetailResult["hint"]>();+ const [detail, setDetail] = useState<MemoryListItem | null>(preview || null);+ const [connectorName, setConnectorName] = useState<string>("");+ const [canFeedback, setCanFeedback] = useState(false);+ const [canUpdate, setCanUpdate] = useState(!!capabilities?.update);+ const [canDelete, setCanDelete] = useState(!!capabilities?.delete);+ const [editOpen, setEditOpen] = useState(false);+ const [deleteOpen, setDeleteOpen] = useState(false);+ const [saving, setSaving] = useState(false);+ const suppressSheetDismissRef = useRef(false);++ useEffect(() => {+ if (!open || !memoryId) {+ setError(null);+ setHint(undefined);+ setDetail(null);+ setCanFeedback(false);+ setCanUpdate(!!capabilities?.update);+ setCanDelete(!!capabilities?.delete);+ setEditOpen(false);+ setDeleteOpen(false);+ setLoading(false);+ return;+ }+ const controller = new AbortController();+ setLoading(true);+ setError(null);+ setHint(undefined);+ setDetail((current) =>+ current?.id === memoryId ? current : preview?.id === memoryId ? preview : null+ );+ const params = new URLSearchParams();+ if (connectorId) params.set("connectorId", connectorId);+ fetch(`/api/memory/${encodeURIComponent(memoryId)}?${params.toString()}`, {+ signal: controller.signal,+ headers: getRequestHeaders(),+ })+ .then(async (response) => {+ const body = await response.json().catch(() => null);+ if (!response.ok) {+ const message =+ typeof body === "string"+ ? body+ : body?.err || body?.error || messages.MEMORY_DETAIL_LOAD_FAILED;+ const notFound =+ response.status === 404 || message === messages.MEMORY_DETAIL_NOT_FOUND;+ if (notFound && preview?.id === memoryId) {+ return { memory: preview } as MemoryDetailResult;+ }+ throw new Error(message);+ }+ return body as MemoryDetailResult;+ })+ .then((payload) => {+ setHint(payload.hint);+ setConnectorName(payload.connector?.name ? String(payload.connector.name) : "");+ setCanFeedback(!!payload.capabilities?.feedback);+ setCanUpdate(!!(payload.capabilities?.update ?? capabilities?.update));+ setCanDelete(!!(payload.capabilities?.delete ?? capabilities?.delete));+ if (payload.memory) setDetail(payload.memory);+ })+ .catch((caught: unknown) => {+ if ((caught as { name?: string })?.name === "AbortError") return;+ setError(+ caught instanceof Error ? caught.message : messages.MEMORY_DETAIL_LOAD_FAILED+ );+ })+ .finally(() => setLoading(false));+ return () => controller.abort();+ }, [capabilities?.delete, capabilities?.update, connectorId, memoryId, messages.MEMORY_DETAIL_LOAD_FAILED, open, preview]);++ const memory = detail || preview;+ const title = memory?.content?.trim() || messages.MEMORY_DETAIL_TITLE;+ const index = memoryId ? memoryIds.indexOf(memoryId) : -1;+ const prevId = index > 0 ? memoryIds[index - 1] : undefined;+ const nextId =+ index >= 0 && index < memoryIds.length - 1 ? memoryIds[index + 1] : undefined;+ const inputCount = memory?.input?.length || 0;+ const changelogCount = memory?.history?.length || 0;++ function handleUpdate(input: { content: string }) {+ if (!memoryId || saving) return;+ setSaving(true);+ const params = new URLSearchParams();+ if (connectorId) params.set("connectorId", connectorId);+ fetch(`/api/memory/${encodeURIComponent(memoryId)}?${params.toString()}`, {+ method: "PATCH",+ headers: getRequestHeaders({ "Content-Type": "application/json" }),+ body: JSON.stringify({ content: input.content }),+ })+ .then(async (response) => {+ const body = await response.json().catch(() => null);+ if (!response.ok) {+ throw new Error(apiError(body, messages.MEMORY_EDIT_FAILED));+ }+ return body as MemoryDetailResult;+ })+ .then((payload) => {+ if (payload.memory) setDetail(payload.memory);+ toast.success(messages.MEMORY_EDIT_SAVED);+ setEditOpen(false);+ onChanged?.();+ })+ .catch((caught: unknown) => {+ toast.error(+ caught instanceof Error ? caught.message : messages.MEMORY_EDIT_FAILED+ );+ })+ .finally(() => setSaving(false));+ }++ function handleDelete() {+ if (!memoryId || saving) return;+ setSaving(true);+ const params = new URLSearchParams();+ if (connectorId) params.set("connectorId", connectorId);+ fetch(`/api/memory/${encodeURIComponent(memoryId)}?${params.toString()}`, {+ method: "DELETE",+ headers: getRequestHeaders(),+ })+ .then(async (response) => {+ const body = await response.json().catch(() => null);+ if (!response.ok) {+ throw new Error(apiError(body, messages.MEMORY_DELETE_FAILED));+ }+ })+ .then(() => {+ toast.success(messages.MEMORY_DELETED);+ setDeleteOpen(false);+ onClose();+ onChanged?.();+ })+ .catch((caught: unknown) => {+ toast.error(+ caught instanceof Error ? caught.message : messages.MEMORY_DELETE_FAILED+ );+ })+ .finally(() => setSaving(false));+ }++ function dismissBlocked() {+ if (suppressSheetDismissRef.current || editOpen || deleteOpen) return true;+ if (typeof document === "undefined") return false;+ return (+ document.querySelectorAll('[role="dialog"][data-state="open"]').length > 1 ||+ !!document.querySelector('[role="alertdialog"][data-state="open"]')+ );+ }++ function openNestedDialog(setter: (open: boolean) => void) {+ suppressSheetDismissRef.current = true;+ setter(true);+ }++ function onNestedOpenChange(+ setter: (open: boolean) => void,+ next: boolean+ ) {+ setter(next);+ if (next) {+ suppressSheetDismissRef.current = true;+ return;+ }+ window.setTimeout(() => {+ suppressSheetDismissRef.current = false;+ }, 50);+ }++ return (+ <>+ <Sheet+ modal={false}+ open={open}+ onOpenChange={(next) => {+ if (!next && dismissBlocked()) return;+ if (!next) onClose();+ }}+ >+ <SheetContent+ side="right"+ className={DETAIL_SHEET_CONTENT_CLASS}+ displayOverlay={false}+ displayClose={false}+ onPointerDownOutside={(event) => {+ if (dismissBlocked()) event.preventDefault();+ }}+ onFocusOutside={(event) => {+ if (dismissBlocked()) event.preventDefault();+ }}+ onInteractOutside={(event) => {+ if (dismissBlocked()) event.preventDefault();+ }}+ >+ <ResizableDetailSheet>+ <div className="flex h-full min-h-0 flex-col overflow-hidden rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950">+ <div className="flex items-start justify-between gap-3 border-b border-stone-200 px-4 py-3 dark:border-stone-800">+ <div className="min-w-0 flex-1">+ <h2 className="line-clamp-3 text-base font-semibold text-stone-950 dark:text-stone-50">+ {title}+ </h2>+ <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-[11px] text-stone-500 dark:text-stone-400">+ <HeaderMeta+ label={messages.MEMORY_DETAIL_CREATED}+ value={formatBrowserDateTime(memory?.createdAt, "")}+ />+ <HeaderMeta+ label={messages.MEMORY_DETAIL_UPDATED}+ value={formatBrowserDateTime(memory?.updatedAt, "")}+ />+ {memory?.id ? (+ <span className="inline-flex items-center gap-1 font-mono">+ <span className="font-sans">{messages.MEMORY_DETAIL_ID}:</span>+ {truncateId(memory.id)}+ <button+ type="button"+ className="rounded p-0.5 text-stone-400 hover:bg-stone-100 hover:text-stone-700 dark:hover:bg-stone-800 dark:hover:text-stone-200"+ title={messages.MEMORY_DETAIL_COPY_ID}+ onClick={() => copyMemoryId(memory.id, messages.COPIED_TO_CLIPBOARD)}+ >+ <Copy className="h-3 w-3" />+ </button>+ </span>+ ) : null}+ </div>+ {memory?.userId ? (+ <p className="mt-2 flex items-center gap-1.5 text-xs text-stone-600 dark:text-stone-300">+ <span>{messages.MEMORY_DETAIL_USER}</span>+ <User className="h-3.5 w-3.5 text-stone-400" />+ <span className="font-semibold text-stone-900 dark:text-stone-100">+ {memory.userId}+ </span>+ </p>+ ) : null}+ {memory?.port ? (+ <p className="mt-2 text-xs text-violet-700 dark:text-violet-300">+ <span>{messages.MEMORY_COPY_SOURCE}</span>+ {" · "}+ <button+ type="button"+ className="font-medium underline underline-offset-2"+ onClick={() =>+ onOpenSource?.(+ memory.port!.sourceConnectorId,+ memory.port!.sourceMemoryId+ )+ }+ >+ {memory.port.sourceConnectorName || memory.port.sourceConnectorId}+ </button>+ </p>+ ) : null}+ </div>+ <div className="flex shrink-0 items-center gap-1">+ <FeatureAccess access="memory.create" hideWhenDenied>+ {onCopy && memory?.id ? (+ <Button+ variant="outline"+ size="sm"+ className="h-7 w-7 border-stone-200 bg-white p-0 text-stone-600 hover:bg-stone-100 hover:text-stone-950 disabled:opacity-40 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300 dark:hover:bg-stone-800 dark:hover:text-stone-50"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ onCopy(memory.id);+ }}+ disabled={!memory || saving}+ title={messages.MEMORY_COPY}+ >+ <ArrowRightLeft className="h-3.5 w-3.5" />+ </Button>+ ) : null}+ </FeatureAccess>+ <FeatureAccess access="memory.update" hideWhenDenied>+ {canUpdate ? (+ <Button+ variant="outline"+ size="sm"+ className="h-7 w-7 border-stone-200 bg-white p-0 text-stone-600 hover:bg-stone-100 hover:text-stone-950 disabled:opacity-40 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300 dark:hover:bg-stone-800 dark:hover:text-stone-50"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ openNestedDialog(setEditOpen);+ }}+ disabled={!memory || saving}+ title={messages.MEMORY_EDIT}+ >+ <Pencil className="h-3.5 w-3.5" />+ </Button>+ ) : null}+ </FeatureAccess>+ <FeatureAccess access="memory.delete" hideWhenDenied>+ {canDelete ? (+ <Button+ variant="outline"+ size="sm"+ className="h-7 w-7 border-stone-200 bg-white p-0 text-stone-600 hover:bg-stone-100 hover:text-error disabled:opacity-40 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300 dark:hover:bg-stone-800"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ openNestedDialog(setDeleteOpen);+ }}+ disabled={!memoryId || saving}+ title={messages.MEMORY_DELETE}+ >+ <Trash2 className="h-3.5 w-3.5" />+ </Button>+ ) : null}+ </FeatureAccess>+ <Button+ variant="outline"+ size="sm"+ className="h-7 w-7 border-stone-200 bg-white p-0 text-stone-600 hover:bg-stone-100 hover:text-stone-950 disabled:opacity-40 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300 dark:hover:bg-stone-800 dark:hover:text-stone-50"+ onClick={() => prevId && onSelect?.(prevId)}+ disabled={!prevId}+ title={messages.MEMORY_DETAIL_PREVIOUS}+ >+ <ChevronUp className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ size="sm"+ className="h-7 w-7 border-stone-200 bg-white p-0 text-stone-600 hover:bg-stone-100 hover:text-stone-950 disabled:opacity-40 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300 dark:hover:bg-stone-800 dark:hover:text-stone-50"+ onClick={() => nextId && onSelect?.(nextId)}+ disabled={!nextId}+ title={messages.MEMORY_DETAIL_NEXT}+ >+ <ChevronDown className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ size="sm"+ className="h-7 w-7 border-stone-200 bg-white p-0 text-stone-600 hover:bg-stone-100 hover:text-stone-950 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300 dark:hover:bg-stone-800 dark:hover:text-stone-50"+ onClick={onClose}+ title={messages.OBSERVABILITY_CLOSE}+ >+ <X className="h-4 w-4" />+ </Button>+ </div>+ </div>+ <div className="min-h-0 flex-1 overflow-auto p-4">+ {hint === "get_unsupported" && preview ? (+ <p className="mb-3 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-900/70 dark:bg-amber-950/30 dark:text-amber-100">+ {messages.MEMORY_DETAIL_UNSUPPORTED}+ </p>+ ) : null}+ {error && !memory ? (+ <div className="rounded-md border border-error/30 bg-error/5 p-3 dark:bg-error/10">+ <p className="text-sm font-semibold text-error">+ {messages.MEMORY_DETAIL_LOAD_FAILED}+ </p>+ <p className="mt-1 text-xs text-muted-foreground">{error}</p>+ </div>+ ) : null}+ {error && memory ? (+ <p className="mb-3 text-xs text-error">{error}</p>+ ) : null}+ {loading && !memory ? (+ <div className="space-y-2">+ <Skeleton className="h-16 rounded-md" />+ <Skeleton className="h-32 rounded-md" />+ </div>+ ) : memory ? (+ <Tabs key={memory.id} defaultValue="details" className="min-w-0">+ <TabsList className="h-9 w-max min-w-full justify-start rounded-md bg-stone-100 p-1 dark:bg-stone-900">+ <TabsTrigger value="details" className="shrink-0 px-3 py-1 text-xs">+ {messages.MEMORY_DETAIL_TAB_DETAILS}+ </TabsTrigger>+ {inputCount ? (+ <TabsTrigger value="input" className="shrink-0 px-3 py-1 text-xs">+ {messages.MEMORY_DETAIL_TAB_INPUT}+ {` (${inputCount})`}+ </TabsTrigger>+ ) : null}+ {changelogCount ? (+ <TabsTrigger value="changelog" className="shrink-0 px-3 py-1 text-xs">+ {messages.MEMORY_DETAIL_TAB_CHANGELOG}+ {` (${changelogCount})`}+ </TabsTrigger>+ ) : null}+ </TabsList>+ <TabsContent value="details" className="mt-3">+ <MemoryDetailsTab+ memory={memory}+ connectorName={connectorName}+ connectorId={connectorId}+ canFeedback={canFeedback}+ onFeedback={(feedback) =>+ setDetail((current) =>+ current+ ? { ...current, feedback }+ : { ...memory, feedback }+ )+ }+ />+ </TabsContent>+ {inputCount ? (+ <TabsContent value="input" className="mt-3">+ <MemoryInputTab messages={memory.input || []} />+ </TabsContent>+ ) : null}+ {changelogCount ? (+ <TabsContent value="changelog" className="mt-3">+ <MemoryChangelogTab events={memory.history || []} />+ </TabsContent>+ ) : null}+ </Tabs>+ ) : null}+ </div>+ </div>+ </ResizableDetailSheet>+ </SheetContent>+ </Sheet>+ <MemoryWriteDialog+ open={editOpen}+ mode="edit"+ content={memory?.content}+ saving={saving}+ onOpenChange={(next) => onNestedOpenChange(setEditOpen, next)}+ onSubmit={handleUpdate}+ />+ <AlertDialog+ open={deleteOpen}+ onOpenChange={(next) => onNestedOpenChange(setDeleteOpen, next)}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{messages.MEMORY_DELETE_TITLE}</AlertDialogTitle>+ <AlertDialogDescription>+ {messages.MEMORY_DELETE_DESCRIPTION}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={saving} size="sm">+ {messages.MEMORY_CANCEL}+ </AlertDialogCancel>+ <AlertDialogAction+ disabled={saving}+ variant="destructive"+ size="sm"+ onClick={(event) => {+ event.preventDefault();+ handleDelete();+ }}+ >+ {messages.MEMORY_DELETE_CONFIRM}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+}++function MemoryDetailsTab({+ memory,+ connectorName,+ connectorId,+ canFeedback,+ onFeedback,+}: {+ memory: MemoryListItem;+ connectorName?: string;+ connectorId?: string;+ canFeedback?: boolean;+ onFeedback?: (feedback: MemoryFeedback) => void;+}) {+ const messages = getMessage();+ const kindLabel = kindMessage(messages, memory.kind);+ return (+ <div className="space-y-4">+ <section>+ <h3 className="mb-1.5 text-[11px] uppercase tracking-wide text-stone-500 dark:text-stone-400">+ {messages.MEMORY_DETAIL_MEMORY}+ </h3>+ <p className="whitespace-pre-wrap rounded-md border border-stone-200 bg-stone-50 px-3 py-2 text-sm text-stone-800 dark:border-stone-800 dark:bg-stone-900 dark:text-stone-200">+ {memory.content}+ </p>+ </section>+ {canFeedback ? (+ <FeatureAccess access="memory.feedback" hideWhenDenied>+ <MemoryFeedbackPanel+ memoryId={memory.id}+ connectorId={connectorId}+ feedback={memory.feedback}+ onFeedback={onFeedback}+ />+ </FeatureAccess>+ ) : null}+ {memory.categories?.length ? (+ <section>+ <h3 className="mb-1.5 text-[11px] uppercase tracking-wide text-stone-500 dark:text-stone-400">+ {messages.MEMORY_DETAIL_CATEGORIES}+ </h3>+ <div className="flex flex-wrap gap-1.5">+ {memory.categories.map((category) => (+ <span+ key={category}+ className="inline-flex items-center gap-1.5 rounded-full border border-stone-200 bg-stone-50 px-2 py-0.5 text-[11px] text-stone-700 dark:border-stone-800 dark:bg-stone-900 dark:text-stone-200"+ >+ <span className={`size-1.5 rounded-full ${categoryDot(category)}`} />+ {category}+ </span>+ ))}+ </div>+ </section>+ ) : null}+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">+ <MetaCard+ label={messages.MEMORY_DETAIL_KIND}+ value={kindLabel}+ dot={KIND_DOT[memory.kind]}+ />+ <MetaCard label={messages.MEMORY_DETAIL_SESSION} value={memory.sessionId} />+ <MetaCard label={messages.MEMORY_DETAIL_AGENT} value={memory.agentId} />+ <MetaCard label={messages.MEMORY_DETAIL_APP} value={memory.appId} />+ <MetaCard+ label={messages.MEMORY_DETAIL_EXPIRATION}+ value={formatBrowserDateTime(memory.expirationDate, "")}+ />+ <MetaCard label={messages.MEMORY_DETAIL_LIFECYCLE} value={memory.lifecycleState} />+ {typeof memory.synthesized === "boolean" ? (+ <MetaCard+ label={messages.MEMORY_DETAIL_SYNTHESIZED}+ value={memory.synthesized ? messages.MEMORY_DETAIL_YES : messages.MEMORY_DETAIL_NO}+ />+ ) : null}+ {typeof memory.score === "number" ? (+ <MetaCard+ label={messages.MEMORY_DETAIL_SCORE}+ value={String(memory.score)}+ />+ ) : null}+ {connectorName ? (+ <MetaCard label={messages.MEMORY_DETAIL_CONNECTOR} value={connectorName} />+ ) : null}+ </div>+ {memory.metadata && Object.keys(memory.metadata).length > 0 ? (+ <section>+ <h3 className="mb-1.5 text-[11px] uppercase tracking-wide text-stone-500 dark:text-stone-400">+ {messages.MEMORY_DETAIL_METADATA}+ </h3>+ <MemoryAttributeTable data={memory.metadata} />+ </section>+ ) : null}+ {memory.structuredAttributes &&+ Object.keys(memory.structuredAttributes).length > 0 ? (+ <section>+ <h3 className="mb-1.5 text-[11px] uppercase tracking-wide text-stone-500 dark:text-stone-400">+ {messages.MEMORY_DETAIL_STRUCTURED}+ </h3>+ <MemoryAttributeTable data={memory.structuredAttributes} />+ </section>+ ) : null}+ </div>+ );+}++function MemoryFeedbackPanel({+ memoryId,+ connectorId,+ feedback,+ onFeedback,+}: {+ memoryId: string;+ connectorId?: string;+ feedback?: MemoryFeedback;+ onFeedback?: (feedback: MemoryFeedback) => void;+}) {+ const messages = getMessage();+ const [reason, setReason] = useState(feedback?.reason || "");+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ setReason(feedback?.reason || "");+ }, [memoryId, feedback?.reason]);++ function submit(rating: MemoryFeedbackRating | null) {+ if (saving) return;+ setSaving(true);+ const params = new URLSearchParams();+ if (connectorId) params.set("connectorId", connectorId);+ fetch(`/api/memory/${encodeURIComponent(memoryId)}/feedback?${params.toString()}`, {+ method: "POST",+ headers: getRequestHeaders({ "Content-Type": "application/json" }),+ body: JSON.stringify({+ rating,+ reason: rating ? reason.trim() || null : null,+ }),+ })+ .then(async (response) => {+ const body = await response.json().catch(() => null);+ if (!response.ok) {+ const message =+ typeof body === "string"+ ? body+ : body?.err || body?.error || messages.MEMORY_DETAIL_FEEDBACK_SAVE_FAILED;+ throw new Error(message);+ }+ return body as { feedback?: MemoryFeedback; memory?: MemoryListItem };+ })+ .then((payload) => {+ const next = payload.memory?.feedback || payload.feedback || {};+ onFeedback?.(next);+ toast.success(+ rating ? messages.MEMORY_DETAIL_FEEDBACK_SAVED : messages.MEMORY_DETAIL_FEEDBACK_CLEARED+ );+ })+ .catch((caught: unknown) => {+ toast.error(+ caught instanceof Error+ ? caught.message+ : messages.MEMORY_DETAIL_FEEDBACK_SAVE_FAILED+ );+ })+ .finally(() => setSaving(false));+ }++ const selected = feedback?.rating;+ const reasonDirty = reason.trim() !== (feedback?.reason || "");++ return (+ <section>+ <h3 className="mb-1.5 text-[11px] uppercase tracking-wide text-stone-500 dark:text-stone-400">+ {messages.MEMORY_DETAIL_FEEDBACK}+ </h3>+ <div className="flex flex-wrap items-center gap-1.5">+ <FeedbackRatingButton+ active={selected === "positive"}+ disabled={saving}+ label={messages.MEMORY_DETAIL_FEEDBACK_POSITIVE}+ onClick={() => submit(selected === "positive" ? null : "positive")}+ icon={<ThumbsUp className="h-3.5 w-3.5" />}+ activeClass="border-emerald-300 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200"+ />+ <FeedbackRatingButton+ active={selected === "negative"}+ disabled={saving}+ label={messages.MEMORY_DETAIL_FEEDBACK_NEGATIVE}+ onClick={() => submit(selected === "negative" ? null : "negative")}+ icon={<ThumbsDown className="h-3.5 w-3.5" />}+ activeClass="border-amber-300 bg-amber-50 text-amber-900 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-200"+ />+ <FeedbackRatingButton+ active={selected === "very_negative"}+ disabled={saving}+ label={messages.MEMORY_DETAIL_FEEDBACK_VERY_NEGATIVE}+ onClick={() => submit(selected === "very_negative" ? null : "very_negative")}+ icon={<Angry className="h-3.5 w-3.5" />}+ activeClass="border-rose-300 bg-rose-50 text-rose-800 dark:border-rose-800 dark:bg-rose-950/40 dark:text-rose-200"+ />+ {selected || feedback?.reason ? (+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="h-7 border-stone-200 bg-white text-stone-600 hover:bg-stone-100 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300"+ disabled={saving}+ onClick={() => {+ setReason("");+ submit(null);+ }}+ >+ {messages.MEMORY_DETAIL_FEEDBACK_CLEAR}+ </Button>+ ) : null}+ </div>+ <div className="mt-2 flex items-center gap-1.5">+ <Input+ value={reason}+ onChange={(event) => setReason(event.target.value)}+ placeholder={messages.MEMORY_DETAIL_FEEDBACK_REASON_PLACEHOLDER}+ maxLength={1000}+ disabled={saving}+ aria-label={messages.MEMORY_DETAIL_FEEDBACK_REASON}+ className="h-8 min-w-0 flex-1 text-xs text-stone-900 placeholder:text-stone-400 dark:text-stone-100 dark:placeholder:text-stone-500"+ />+ <Button+ type="button"+ size="sm"+ className="h-8 shrink-0"+ disabled={saving || !selected || !reasonDirty}+ onClick={() => selected && submit(selected)}+ >+ {messages.MEMORY_DETAIL_FEEDBACK_SUBMIT}+ </Button>+ </div>+ </section>+ );+}++function FeedbackRatingButton({+ active,+ disabled,+ label,+ onClick,+ icon,+ activeClass,+}: {+ active: boolean;+ disabled: boolean;+ label: string;+ onClick: () => void;+ icon: ReactNode;+ activeClass: string;+}) {+ return (+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={disabled}+ onClick={onClick}+ className={`h-7 gap-1.5 ${+ active+ ? activeClass+ : "border-stone-200 bg-white text-stone-600 hover:bg-stone-100 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-300"+ }`}+ >+ {icon}+ {label}+ </Button>+ );+}++function MemoryInputTab({ messages: items }: { messages: MemoryMessage[] }) {+ const copy = getMessage();+ if (!items.length) {+ return (+ <p className="text-sm text-stone-500 dark:text-stone-400">+ {copy.MEMORY_DETAIL_INPUT_EMPTY}+ </p>+ );+ }+ return (+ <ul className="space-y-2">+ {items.map((item, index) => (+ <li+ key={`${item.role}-${index}`}+ className={`rounded-md border px-3 py-2 ${inputBubbleClass(item.role)}`}+ >+ <p className="text-[11px] font-medium uppercase tracking-wide text-stone-500 dark:text-stone-400">+ {item.role}+ </p>+ <p className="mt-1 whitespace-pre-wrap text-sm text-stone-800 dark:text-stone-200">+ {item.content}+ </p>+ </li>+ ))}+ </ul>+ );+}++function MemoryChangelogTab({ events }: { events: MemoryHistoryEvent[] }) {+ const messages = getMessage();+ if (!events.length) {+ return (+ <p className="text-sm text-stone-500 dark:text-stone-400">+ {messages.MEMORY_DETAIL_CHANGELOG_EMPTY}+ </p>+ );+ }+ return (+ <ol className="space-y-3">+ {events.map((event, index) => (+ <li+ key={event.id || `${event.event}-${index}`}+ className="rounded-md border border-stone-200 px-3 py-2 dark:border-stone-800"+ >+ <div className="flex flex-wrap items-center justify-between gap-2">+ <p className="text-xs font-semibold text-stone-900 dark:text-stone-100">+ {eventLabel(event.event, messages)}+ </p>+ <p className="text-[11px] text-stone-500 dark:text-stone-400">+ {formatBrowserDateTime(event.createdAt, "")}+ </p>+ </div>+ {event.oldMemory ? (+ <p className="mt-2 text-xs text-stone-500 dark:text-stone-400">+ <span className="font-medium">{messages.MEMORY_DETAIL_OLD_MEMORY}: </span>+ {event.oldMemory}+ </p>+ ) : null}+ {event.newMemory ? (+ <p className="mt-1 text-sm text-stone-800 dark:text-stone-200">+ <span className="text-xs font-medium text-stone-500 dark:text-stone-400">+ {messages.MEMORY_DETAIL_NEW_MEMORY}:{" "}+ </span>+ {event.newMemory}+ </p>+ ) : null}+ </li>+ ))}+ </ol>+ );+}++function MemoryAttributeTable({ data }: { data: Record<string, unknown> }) {+ const formatted = formatDatePartsValue(data);+ if (formatted) {+ return (+ <p className="rounded-md border border-stone-200 bg-stone-50 px-3 py-2 text-sm text-stone-800 dark:border-stone-800 dark:bg-stone-900 dark:text-stone-200">+ {formatted}+ </p>+ );+ }+ const entries = objectEntries(data);+ if (!entries.length) return null;+ return (+ <div className="overflow-hidden rounded-md border border-stone-200 dark:border-stone-800">+ <AttributeRows entries={entries} />+ </div>+ );+}++function AttributeRows({ entries }: { entries: Array<[string, unknown]> }) {+ return (+ <div className="divide-y divide-stone-200 dark:divide-stone-800">+ {entries.map(([key, value], index) => (+ <div+ key={`${key}-${index}`}+ className={`grid min-w-0 grid-cols-1 gap-1 px-3 py-2 sm:grid-cols-[minmax(140px,32%)_minmax(0,1fr)] sm:items-start sm:gap-3 ${+ index % 2 === 0+ ? "bg-white dark:bg-stone-950"+ : "bg-stone-50 dark:bg-stone-900/70"+ }`}+ >+ <div className="text-xs font-medium text-stone-500 dark:text-stone-400">+ {humanizeAttributeKey(key)}+ </div>+ <div className="min-w-0 break-words text-xs text-stone-900 dark:text-stone-100">+ <AttributeValue value={value} />+ </div>+ </div>+ ))}+ </div>+ );+}++function AttributeValue({ value }: { value: unknown }) {+ const messages = getMessage();+ if (typeof value === "boolean") {+ return (+ <span+ className={`inline-flex rounded-full px-1.5 py-0.5 text-[11px] font-medium ${+ value+ ? "bg-emerald-50 text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-200"+ : "bg-stone-100 text-stone-600 dark:bg-stone-800 dark:text-stone-300"+ }`}+ >+ {value ? messages.MEMORY_DETAIL_YES : messages.MEMORY_DETAIL_NO}+ </span>+ );+ }+ if (typeof value === "number") {+ return <span className="font-medium">{String(value)}</span>;+ }+ if (typeof value === "string") {+ const formatted = formatAttributeDate(value);+ return (+ <span className="whitespace-pre-wrap break-words">{formatted}</span>+ );+ }+ if (Array.isArray(value)) {+ if (!value.length) return null;+ if (value.every((item) => isPrimitive(item))) {+ return (+ <div className="flex flex-wrap gap-1">+ {value.map((item, index) => (+ <span+ key={`${String(item)}-${index}`}+ className="rounded-full border border-stone-200 bg-stone-50 px-2 py-0.5 text-[11px] text-stone-700 dark:border-stone-800 dark:bg-stone-900 dark:text-stone-200"+ >+ {typeof item === "boolean"+ ? item+ ? messages.MEMORY_DETAIL_YES+ : messages.MEMORY_DETAIL_NO+ : formatAttributeDate(String(item))}+ </span>+ ))}+ </div>+ );+ }+ return (+ <div className="space-y-2">+ {value.map((item, index) => (+ <div+ key={index}+ className="overflow-hidden rounded-md border border-stone-200 dark:border-stone-800"+ >+ <div className="border-b border-stone-200 bg-stone-100 px-2.5 py-1 text-[11px] font-medium text-stone-500 dark:border-stone-800 dark:bg-stone-900 dark:text-stone-400">+ {messages.MEMORY_DETAIL_ITEM(index + 1)}+ </div>+ {isPlainObject(item) ? (+ <AttributeRows entries={objectEntries(item)} />+ ) : (+ <div className="px-2.5 py-1.5">+ <AttributeValue value={item} />+ </div>+ )}+ </div>+ ))}+ </div>+ );+ }+ if (isPlainObject(value)) {+ const formatted = formatDatePartsValue(value);+ if (formatted) {+ return <span className="whitespace-pre-wrap break-words">{formatted}</span>;+ }+ const nested = objectEntries(value);+ if (!nested.length) return null;+ return (+ <div className="overflow-hidden rounded-md border border-stone-200 dark:border-stone-800">+ <AttributeRows entries={nested} />+ </div>+ );+ }+ return <span className="whitespace-pre-wrap break-words">{String(value)}</span>;+}++function objectEntries(data: unknown): Array<[string, unknown]> {+ if (!isPlainObject(data)) return [];+ return Object.entries(data).filter(([, value]) => !isEmptyAttribute(value));+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function isPrimitive(value: unknown): boolean {+ return (+ value === null ||+ typeof value === "string" ||+ typeof value === "number" ||+ typeof value === "boolean"+ );+}++function isEmptyAttribute(value: unknown): boolean {+ return value === null || value === undefined || value === "";+}++function humanizeAttributeKey(key: string): string {+ const spaced = key.replace(/_/g, " ").replace(/\s+/g, " ").trim();+ if (!spaced) return key;+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);+}++function formatAttributeDate(value: string): string {+ if (!/^\d{4}-\d{2}-\d{2}(?:[T ]|$)/.test(value)) return value;+ return formatBrowserDateTime(value, value);+}++function inputBubbleClass(role: string): string {+ const key = role.trim().toLowerCase();+ if (key === "assistant" || key === "ai" || key === "model") {+ return "border-violet-200 bg-violet-50/70 dark:border-violet-900/70 dark:bg-violet-950/20";+ }+ if (key === "system") {+ return "border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950";+ }+ return "border-stone-200 bg-stone-50 dark:border-stone-800 dark:bg-stone-900";+}++function HeaderMeta({ label, value }: { label: string; value?: string }) {+ if (!value) return null;+ return (+ <span>+ <span className="text-stone-400">{label}:</span> {value}+ </span>+ );+}++function MetaCard({+ label,+ value,+ dot,+}: {+ label: string;+ value?: string;+ dot?: string;+}) {+ if (!value) return null;+ return (+ <div className="rounded-md border border-stone-200 bg-stone-50 px-2.5 py-1.5 dark:border-stone-800 dark:bg-stone-900">+ <p className="flex items-center gap-1.5 text-[11px] text-stone-500 dark:text-stone-400">+ {dot ? <span className={`size-1.5 rounded-full ${dot}`} /> : null}+ {label}+ </p>+ <p className="mt-0.5 truncate text-xs font-semibold text-stone-900 dark:text-stone-100">+ {value}+ </p>+ </div>+ );+}++function ResizableDetailSheet({ children }: { children: ReactNode }) {+ const [maxWidth, setMaxWidth] = useState(1200);+ const [defaultWidth, setDefaultWidth] = useState(760);++ useEffect(() => {+ const updateBounds = () => {+ const viewportWidth = window.innerWidth;+ const nextMaxWidth = Math.max(420, viewportWidth - 32);+ setMaxWidth(nextMaxWidth);+ setDefaultWidth(Math.min(Math.max(viewportWidth * 0.68, 720), nextMaxWidth));+ };+ updateBounds();+ window.addEventListener("resize", updateBounds);+ return () => window.removeEventListener("resize", updateBounds);+ }, []);++ return (+ <ResizeablePanel+ defaultWidth={defaultWidth}+ minWidth={420}+ maxWidth={maxWidth}+ handlePosition="left"+ className="h-full max-w-[calc(100vw-1rem)] rounded-md bg-white shadow-2xl dark:bg-stone-950"+ handleClassName="opacity-100 border-stone-300 bg-white dark:border-stone-700 dark:bg-stone-900"+ >+ <div className="flex h-full min-h-0 flex-col overflow-hidden">{children}</div>+ </ResizeablePanel>+ );+}++function copyMemoryId(id: string, copiedMessage: string) {+ void navigator.clipboard.writeText(id).then(+ () => toast.success(copiedMessage),+ () => undefined+ );+}++function apiError(body: unknown, fallback: string): string {+ if (typeof body === "string" && body.trim()) return body;+ if (body && typeof body === "object") {+ const record = body as { err?: unknown; error?: unknown };+ if (typeof record.err === "string" && record.err.trim()) return record.err;+ if (typeof record.error === "string" && record.error.trim()) return record.error;+ }+ return fallback;+}++function truncateId(id: string): string {+ if (id.length <= 18) return id;+ return `${id.slice(0, 8)}...${id.slice(-6)}`;+}++function categoryDot(name: string): string {+ let hash = 0;+ for (let index = 0; index < name.length; index += 1) {+ hash = (hash * 31 + name.charCodeAt(index)) | 0;+ }+ return CATEGORY_DOTS[Math.abs(hash) % CATEGORY_DOTS.length];+}++function eventLabel(+ event: string,+ messages: ReturnType<typeof getMessage>+): string {+ const key = event.trim().toUpperCase();+ if (key === "ADD" || key === "ADDED") return messages.MEMORY_DETAIL_EVENT_ADDED;+ if (key === "UPDATE" || key === "UPDATED") return messages.MEMORY_DETAIL_EVENT_UPDATED;+ if (key === "DELETE" || key === "DELETED") return messages.MEMORY_DETAIL_EVENT_DELETED;+ return event;+}++function kindMessage(+ messages: ReturnType<typeof getMessage>,+ kind: MemoryKind+): string {+ if (kind === "temporal") return messages.MEMORY_TEMPORAL;+ if (kind === "profile") return messages.MEMORY_PROFILE;+ return messages.MEMORY_SUMMARY;+}diff --git a/src/client/src/components/(playground)/memory/memory-filter-combobox.tsx b/src/client/src/components/(playground)/memory/memory-filter-combobox.tsxnew file mode 100644index 00000000..2ce4486f--- /dev/null+++ b/src/client/src/components/(playground)/memory/memory-filter-combobox.tsx@@ -0,0 +1,195 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import { Check, ChevronsUpDown } from "lucide-react";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "@/components/ui/command";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import getMessage from "@/constants/messages";+import {+ type MemoryFilterChoice,+ type MemoryFilterField,+ type MemoryFilterOptions,+} from "@/lib/platform/connectors/memory/types";+import { cn } from "@/lib/utils";++export function memoryFilterChoices(+ field: MemoryFilterField,+ filters: MemoryFilterOptions,+ userId?: string+): MemoryFilterChoice[] {+ if (field.key === "userId") return filters.users;+ if (field.key === "agentId") return filters.agents;+ return filters.sessions.filter(+ (session) => !userId || !session.userId || session.userId === userId+ );+}++export default function MemoryFilterCombobox({+ label,+ value,+ options,+ onChange,+ allowCustom,+ disabled,+ required,+ widthClass = "w-[180px]",+ inDialog,+}: {+ label: string;+ value: string;+ options: MemoryFilterChoice[];+ onChange: (value: string) => void;+ allowCustom?: boolean;+ disabled?: boolean;+ required?: boolean;+ widthClass?: string;+ inDialog?: boolean;+}) {+ const messages = getMessage();+ const [open, setOpen] = useState(false);+ const [search, setSearch] = useState("");+ useEffect(() => {+ if (!open) setSearch("");+ }, [open]);++ const selectedLabel =+ options.find((option) => option.id === value)?.label || value || "";+ const listed = useMemo(() => {+ if (!value || options.some((option) => option.id === value)) return options;+ return [...options, { id: value, label: value }];+ }, [options, value]);+ const trimmedSearch = search.trim();+ const filtered = useMemo(() => {+ if (!trimmedSearch) return listed;+ const query = trimmedSearch.toLowerCase();+ return listed.filter((option) =>+ `${option.label} ${option.id}`.toLowerCase().includes(query)+ );+ }, [listed, trimmedSearch]);+ const showCustom =+ !!allowCustom &&+ !!trimmedSearch &&+ !listed.some(+ (option) =>+ option.id === trimmedSearch || option.label === trimmedSearch+ );++ function commit(next: string) {+ onChange(next);+ setSearch("");+ setOpen(false);+ }++ return (+ <Popover open={open} onOpenChange={setOpen} modal={inDialog}>+ <PopoverTrigger asChild>+ <button+ type="button"+ aria-label={label}+ disabled={disabled}+ className={cn(+ "flex h-8 min-w-0 items-center justify-between rounded-md border border-stone-200 bg-white px-3 py-2 text-sm placeholder:text-stone-500 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-200",+ widthClass+ )}+ >+ <span+ title={selectedLabel || undefined}+ className={cn(+ "min-w-0 flex-1 truncate text-left",+ selectedLabel+ ? "text-stone-900 dark:text-stone-100"+ : "text-stone-500 dark:text-stone-400"+ )}+ >+ {selectedLabel ||+ (inDialog ? messages.MEMORY_FILTER_PLACEHOLDER : label)}+ </span>+ <ChevronsUpDown className="ml-2 h-3.5 w-3.5 shrink-0 opacity-50" />+ </button>+ </PopoverTrigger>+ <PopoverContent+ className={cn(+ "p-0",+ inDialog+ ? "w-[var(--radix-popover-trigger-width)]"+ : "w-[min(100vw-2rem,360px)] min-w-[var(--radix-popover-trigger-width)]"+ )}+ align="start"+ collisionPadding={8}+ onOpenAutoFocus={(event) => {+ if (inDialog) event.preventDefault();+ }}+ >+ <Command className="h-auto" shouldFilter={false}>+ <CommandInput+ placeholder={allowCustom ? messages.MEMORY_FILTER_CUSTOM_HINT : label}+ value={search}+ onValueChange={setSearch}+ onKeyDown={(event) => {+ if (event.key === "Enter" && allowCustom && trimmedSearch) {+ event.preventDefault();+ commit(trimmedSearch);+ }+ }}+ />+ <CommandList>+ <CommandEmpty>+ {allowCustom+ ? messages.MEMORY_FILTER_CUSTOM_HINT+ : messages.MEMORY_NO_MATCHES}+ </CommandEmpty>+ <CommandGroup>+ {!required && value ? (+ <CommandItem value="__all__" onSelect={() => commit("")}>+ {messages.MEMORY_FILTER_ALL}+ </CommandItem>+ ) : null}+ {filtered.map((option) => (+ <CommandItem+ key={option.id}+ value={`${option.label} ${option.id}`}+ onSelect={() => commit(option.id)}+ className="gap-2"+ >+ <Check+ className={cn(+ "h-3.5 w-3.5 shrink-0",+ option.id === value ? "opacity-100" : "opacity-0"+ )}+ />+ <span+ className="min-w-0 flex-1 break-all"+ title={option.label}+ >+ {option.label}+ </span>+ </CommandItem>+ ))}+ {showCustom ? (+ <CommandItem+ value={trimmedSearch}+ onSelect={() => commit(trimmedSearch)}+ >+ <span className="min-w-0 flex-1 break-all">+ {messages.MEMORY_FILTER_USE_VALUE(trimmedSearch)}+ </span>+ </CommandItem>+ ) : null}+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ );+}diff --git a/src/client/src/components/(playground)/memory/memory-filter-fields.tsx b/src/client/src/components/(playground)/memory/memory-filter-fields.tsxnew file mode 100644index 00000000..811ac2a9--- /dev/null+++ b/src/client/src/components/(playground)/memory/memory-filter-fields.tsx@@ -0,0 +1,127 @@+"use client";++import { Label } from "@/components/ui/label";+import {+ type MemoryFilterField,+ type MemoryFilterKey,+ type MemoryFilterOptions,+} from "@/lib/platform/connectors/memory/types";+import MemoryFilterCombobox, {+ memoryFilterChoices,+} from "./memory-filter-combobox";++export type MemoryFilterScope = {+ userId: string;+ sessionId: string;+ agentId: string;+};++export function emptyMemoryFilterScope(): MemoryFilterScope {+ return { userId: "", sessionId: "", agentId: "" };+}++export function memoryFilterValue(+ scope: MemoryFilterScope,+ key: MemoryFilterKey+): string {+ if (key === "userId") return scope.userId;+ if (key === "sessionId") return scope.sessionId;+ return scope.agentId;+}++export function applyMemoryFilterChange(+ scope: MemoryFilterScope,+ filters: MemoryFilterOptions,+ key: MemoryFilterKey,+ next: string+): MemoryFilterScope {+ if (key === "userId") {+ const sessionStillValid =+ !scope.sessionId ||+ filters.sessions.some(+ (session) =>+ session.id === scope.sessionId &&+ (!session.userId || session.userId === next)+ );+ return {+ ...scope,+ userId: next,+ sessionId: sessionStillValid ? scope.sessionId : "",+ };+ }+ if (key === "sessionId") {+ const session = filters.sessions.find((item) => item.id === next);+ return {+ ...scope,+ sessionId: next,+ userId:+ session?.userId && session.userId !== scope.userId+ ? session.userId+ : scope.userId,+ };+ }+ return { ...scope, agentId: next };+}++export function memoryFilterRequiredMissing(+ fields: MemoryFilterField[],+ scope: MemoryFilterScope+): boolean {+ return fields.some((field) => {+ if (!field.required && !field.writeRequired) return false;+ return !memoryFilterValue(scope, field.key).trim();+ });+}++export function trimmedMemoryFilterScope(scope: MemoryFilterScope) {+ return {+ userId: scope.userId.trim() || undefined,+ sessionId: scope.sessionId.trim() || undefined,+ agentId: scope.agentId.trim() || undefined,+ };+}++export function keepDialogPopoverOpen(event: {+ target: EventTarget | null;+ preventDefault: () => void;+}) {+ const target = event.target as HTMLElement | null;+ if (target?.closest("[data-radix-popper-content-wrapper]")) {+ event.preventDefault();+ }+}++export function MemoryDialogFilterFields({+ fields,+ filters,+ scope,+ onChange,+ disabled,+}: {+ fields: MemoryFilterField[];+ filters: MemoryFilterOptions;+ scope: MemoryFilterScope;+ onChange: (key: MemoryFilterKey, next: string) => void;+ disabled?: boolean;+}) {+ return (+ <>+ {fields.map((field) => (+ <div key={field.key} className="space-y-1.5">+ <Label>{field.label}</Label>+ <MemoryFilterCombobox+ label={field.label}+ value={memoryFilterValue(scope, field.key)}+ options={memoryFilterChoices(field, filters, scope.userId)}+ onChange={(next) => onChange(field.key, next)}+ allowCustom={field.allowCustom !== false}+ disabled={disabled}+ required={!!field.required || !!field.writeRequired}+ widthClass="w-full"+ inDialog+ />+ </div>+ ))}+ </>+ );+}diff --git a/src/client/src/components/(playground)/memory/memory-graph.tsx b/src/client/src/components/(playground)/memory/memory-graph.tsxnew file mode 100644index 00000000..9160337e--- /dev/null+++ b/src/client/src/components/(playground)/memory/memory-graph.tsx@@ -0,0 +1,427 @@+"use client";++import { useEffect, useMemo, useRef, useState, type PointerEvent } from "react";+import { Minus, Plus, Search } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import getMessage from "@/constants/messages";+import type {+ LaidOutMemoryNode,+ MemoryEntityType,+ MemoryGraphModel,+ MemoryKind,+} from "@/lib/platform/connectors/memory/graph";+import {+ MEMORY_ENTITY_TYPES,+ layoutMemoryGraph,+ radialEdgePoints,+} from "@/lib/platform/connectors/memory/graph";++const KIND_FILL: Record<MemoryKind, string> = {+ temporal: "#14b8a6",+ profile: "#f97316",+ summary: "#84cc16",+};++const ENTITY_FILL: Record<MemoryEntityType, string> = {+ entity: "#f472b6",+ event: "#818cf8",+ location: "#86efac",+ object: "#facc15",+ preference: "#c084fc",+ topic: "#fb923c",+ user: "#2dd4bf",+};++const WIDTH = 840;+const HEIGHT = 520;+const MIN_SPAN = 420;+const PAD = 88;+const MIN_ZOOM = 0.45;+const MAX_ZOOM = 2.6;++type MemoryGraphProps = {+ graph: MemoryGraphModel;+ selectedId?: string | null;+ onSelect?: (memoryId: string) => void;+};++export default function MemoryGraph({ graph, selectedId, onSelect }: MemoryGraphProps) {+ const messages = getMessage();+ const knowledge = graph.kind === "knowledge";+ const laidOut = useMemo(() => layoutMemoryGraph(graph, WIDTH, HEIGHT), [graph]);+ const nodeById = useMemo(() => {+ const map = new Map<string, LaidOutMemoryNode>();+ for (const node of laidOut) map.set(node.id, node);+ return map;+ }, [laidOut]);+ const origin = useMemo(() => {+ const users = laidOut.filter((node) => node.type === "user");+ if (users.length === 1) return { x: users[0].x, y: users[0].y };+ return { x: WIDTH / 2, y: HEIGHT / 2 };+ }, [laidOut]);+ const [camera, setCamera] = useState({ x: 0, y: 0, k: 1 });+ const [query, setQuery] = useState("");+ const [entityFilter, setEntityFilter] = useState("all");+ const drag = useRef<{ x: number; y: number; cx: number; cy: number } | null>(null);+ const svgRef = useRef<SVGSVGElement | null>(null);+ const entityTypes = useMemo(() => {+ const present = new Set<MemoryEntityType>();+ for (const node of graph.nodes) {+ if (node.entityType) present.add(node.entityType);+ }+ return MEMORY_ENTITY_TYPES.filter((type) => present.has(type));+ }, [graph.nodes]);++ useEffect(() => {+ setCamera({ x: 0, y: 0, k: 1 });+ setQuery("");+ setEntityFilter("all");+ }, [graph]);++ useEffect(() => {+ const node = svgRef.current;+ if (!node) return;+ const onWheel = (event: WheelEvent) => {+ event.preventDefault();+ setCamera((current) => ({+ ...current,+ k: clampZoom(current.k * (event.deltaY > 0 ? 0.92 : 1.08)),+ }));+ };+ node.addEventListener("wheel", onWheel, { passive: false });+ return () => node.removeEventListener("wheel", onWheel);+ }, [laidOut.length]);++ const viewBox = useMemo(() => {+ if (!laidOut.length) return { minX: 0, minY: 0, width: WIDTH, height: HEIGHT };+ const xs = laidOut.map((node) => node.x);+ const ys = laidOut.map((node) => node.y);+ let minX = Math.min(...xs) - PAD;+ let maxX = Math.max(...xs) + PAD;+ let minY = Math.min(...ys) - PAD;+ let maxY = Math.max(...ys) + PAD;+ if (maxX - minX < MIN_SPAN) {+ const extra = (MIN_SPAN - (maxX - minX)) / 2;+ minX -= extra;+ maxX += extra;+ }+ if (maxY - minY < MIN_SPAN) {+ const extra = (MIN_SPAN - (maxY - minY)) / 2;+ minY -= extra;+ maxY += extra;+ }+ return { minX, minY, width: maxX - minX, height: maxY - minY };+ }, [laidOut]);++ const search = query.trim().toLowerCase();+ const nodeVisible = (node: LaidOutMemoryNode) => {+ if (entityFilter !== "all" && node.entityType && node.entityType !== entityFilter) {+ return false;+ }+ if (!search) return true;+ return node.label.toLowerCase().includes(search);+ };++ if (laidOut.length === 0) {+ return (+ <div className="flex h-full min-h-[280px] items-center justify-center rounded-md border border-stone-200 bg-white text-sm text-stone-500 dark:border-stone-800 dark:bg-stone-950 dark:text-stone-400">+ {messages.MEMORY_GRAPH_EMPTY}+ </div>+ );+ }++ const onPointerDown = (event: PointerEvent<SVGSVGElement>) => {+ if (event.button !== 0) return;+ event.currentTarget.setPointerCapture(event.pointerId);+ drag.current = { x: event.clientX, y: event.clientY, cx: camera.x, cy: camera.y };+ };++ const onPointerMove = (event: PointerEvent<SVGSVGElement>) => {+ if (!drag.current) return;+ const scale = viewBox.width / Math.max(event.currentTarget.clientWidth, 1);+ setCamera({+ ...camera,+ x: drag.current.cx + (event.clientX - drag.current.x) * scale,+ y: drag.current.cy + (event.clientY - drag.current.y) * scale,+ });+ };++ const onPointerUp = () => {+ drag.current = null;+ };++ const zoomBy = (factor: number) => {+ setCamera((current) => ({ ...current, k: clampZoom(current.k * factor) }));+ };++ return (+ <div className="relative h-full min-h-[280px] overflow-hidden rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950">+ {knowledge ? (+ <div className="absolute right-2 top-2 z-10 flex items-center gap-1.5">+ <div className="relative">+ <Search className="pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-stone-400" />+ <Input+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={messages.MEMORY_GRAPH_SEARCH}+ className="h-7 w-[160px] bg-white/90 pl-7 text-xs dark:bg-stone-950/90"+ />+ </div>+ {entityTypes.length > 1 ? (+ <Select value={entityFilter} onValueChange={setEntityFilter}>+ <SelectTrigger+ className="h-7 w-[108px] bg-white/90 text-xs dark:bg-stone-950/90"+ aria-label={messages.MEMORY_GRAPH_TYPE_FILTER}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">{messages.MEMORY_GRAPH_TYPE_ALL}</SelectItem>+ {entityTypes.map((type) => (+ <SelectItem key={type} value={type}>+ {entityTypeLabel(type, messages)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : null}+ </div>+ ) : null}+ <svg+ ref={svgRef}+ viewBox={`${viewBox.minX} ${viewBox.minY} ${viewBox.width} ${viewBox.height}`}+ className="h-full w-full cursor-grab active:cursor-grabbing"+ role="img"+ aria-label={messages.MEMORY_GRAPH_TITLE}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerUp}+ onPointerCancel={onPointerUp}+ >+ <defs>+ <filter id="memory-node-glow" x="-50%" y="-50%" width="200%" height="200%">+ <feGaussianBlur stdDeviation="3.5" result="blur" />+ <feMerge>+ <feMergeNode in="blur" />+ <feMergeNode in="SourceGraphic" />+ </feMerge>+ </filter>+ </defs>+ <g transform={`translate(${camera.x} ${camera.y}) scale(${camera.k})`}>+ {graph.edges.map((edge, index) => {+ const from = nodeById.get(edge.from);+ const to = nodeById.get(edge.to);+ if (!from || !to) return null;+ const selected = !!edge.memoryId && edge.memoryId === selectedId;+ const dimmed = knowledge && (!nodeVisible(from) || !nodeVisible(to));+ const points = knowledge+ ? `${from.x},${from.y} ${to.x},${to.y}`+ : radialEdgePoints(from, to, origin)+ .map((point) => `${point.x},${point.y}`)+ .join(" ");+ return (+ <polyline+ key={`${edge.from}-${edge.to}-${index}`}+ fill="none"+ points={points}+ className={`cursor-pointer ${+ selected+ ? "stroke-stone-900 dark:stroke-stone-100"+ : "stroke-stone-300 dark:stroke-stone-600"+ }`}+ strokeWidth={selected ? 2.2 : 1.35}+ strokeLinecap="round"+ strokeLinejoin="round"+ opacity={dimmed ? 0.12 : selected ? 1 : 0.85}+ onPointerDown={(event) => {+ if (!edge.memoryId) return;+ event.stopPropagation();+ }}+ onClick={(event) => {+ event.stopPropagation();+ if (edge.memoryId) onSelect?.(edge.memoryId);+ }}+ >+ <title>{edge.label || from.label}</title>+ </polyline>+ );+ })}+ {laidOut.map((node) => {+ const selected =+ (node.memoryId && node.memoryId === selectedId) ||+ graph.edges.some(+ (edge) =>+ edge.memoryId === selectedId &&+ (edge.from === node.id || edge.to === node.id)+ );+ const visible = !knowledge || nodeVisible(node);+ const fill = nodeFill(node);+ const radius =+ node.entityType === "user" || node.type === "user"+ ? 13+ : node.type === "memory"+ ? 9+ : node.type === "session"+ ? 7+ : 8;+ return (+ <g+ key={node.id}+ transform={`translate(${node.x} ${node.y})`}+ className={node.memoryId ? "cursor-pointer" : "cursor-default"}+ filter={selected ? "url(#memory-node-glow)" : undefined}+ opacity={visible ? 1 : 0.12}+ role={node.memoryId ? "button" : undefined}+ tabIndex={node.memoryId ? 0 : undefined}+ onPointerDown={(event) => {+ if (!node.memoryId) return;+ event.stopPropagation();+ }}+ onClick={(event) => {+ event.stopPropagation();+ if (node.memoryId) onSelect?.(node.memoryId);+ }}+ onKeyDown={(event) => {+ if (!node.memoryId) return;+ if (event.key !== "Enter" && event.key !== " ") return;+ event.preventDefault();+ onSelect?.(node.memoryId);+ }}+ >+ {selected ? (+ <circle+ r={radius + 7}+ fill="none"+ className="stroke-stone-900 dark:stroke-stone-100"+ strokeWidth={1.5}+ />+ ) : null}+ {node.type === "memory" && !knowledge ? (+ <polygon+ points={hexPoints(radius + (selected ? 1 : 0))}+ fill={fill}+ className="stroke-white dark:stroke-stone-950"+ strokeWidth={1.25}+ >+ <title>{node.label}</title>+ </polygon>+ ) : (+ <circle+ r={radius}+ fill={fill}+ className="stroke-white dark:stroke-stone-950"+ strokeWidth={1.25}+ >+ <title>{node.label}</title>+ </circle>+ )}+ <text+ y={radius + 14}+ textAnchor="middle"+ className="fill-stone-600 dark:fill-stone-300"+ fontSize={9}+ >+ {truncateLabel(node.label)}+ </text>+ </g>+ );+ })}+ </g>+ </svg>+ <div className="absolute bottom-2 left-2 flex max-w-[70%] flex-wrap items-center gap-2 rounded-md border border-stone-200 bg-white/90 px-2 py-1 text-[10px] text-stone-600 dark:border-stone-700 dark:bg-stone-900/90 dark:text-stone-300">+ <span className="uppercase tracking-wide">+ {knowledge ? messages.MEMORY_GRAPH_ENTITY_TYPES : messages.MEMORY_LEGEND}+ </span>+ {knowledge+ ? (entityTypes.length ? entityTypes : MEMORY_ENTITY_TYPES).map((type) => (+ <LegendDot+ key={type}+ color={ENTITY_FILL[type]}+ label={entityTypeLabel(type, messages)}+ />+ ))+ : (+ <>+ <LegendDot color={KIND_FILL.temporal} label={messages.MEMORY_TEMPORAL} />+ <LegendDot color={KIND_FILL.profile} label={messages.MEMORY_PROFILE} />+ <LegendDot color={KIND_FILL.summary} label={messages.MEMORY_SUMMARY} />+ </>+ )}+ </div>+ <div className="absolute bottom-2 right-2 flex flex-col overflow-hidden rounded-md border border-stone-200 bg-white/90 dark:border-stone-700 dark:bg-stone-900/90">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-7 w-7 rounded-none p-0"+ onClick={() => zoomBy(1.15)}+ title={messages.MEMORY_GRAPH_ZOOM_IN}+ >+ <Plus className="h-3.5 w-3.5" />+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-7 w-7 rounded-none p-0"+ onClick={() => zoomBy(0.87)}+ title={messages.MEMORY_GRAPH_ZOOM_OUT}+ >+ <Minus className="h-3.5 w-3.5" />+ </Button>+ </div>+ </div>+ );+}++function clampZoom(value: number): number {+ return Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, value));+}++function nodeFill(node: LaidOutMemoryNode): string {+ if (node.entityType) return ENTITY_FILL[node.entityType];+ if (node.type === "memory") return KIND_FILL[node.kind || "summary"];+ if (node.type === "session") return "#a8a29e";+ return ENTITY_FILL.user;+}++function entityTypeLabel(+ type: MemoryEntityType,+ messages: ReturnType<typeof getMessage>+): string {+ if (type === "user") return messages.MEMORY_USER;+ if (type === "event") return messages.MEMORY_EVENT;+ if (type === "location") return messages.MEMORY_LOCATION;+ if (type === "object") return messages.MEMORY_OBJECT;+ if (type === "preference") return messages.MEMORY_PREFERENCE;+ if (type === "topic") return messages.MEMORY_TOPIC;+ return messages.MEMORY_ENTITY;+}++function truncateLabel(label: string): string {+ return label.length > 18 ? `${label.slice(0, 16).trimEnd()}…` : label;+}++function hexPoints(radius: number): string {+ return Array.from({ length: 6 }, (_, index) => {+ const angle = (Math.PI / 3) * index - Math.PI / 6;+ return `${radius * Math.cos(angle)},${radius * Math.sin(angle)}`;+ }).join(" ");+}++function LegendDot({ color, label }: { color: string; label: string }) {+ return (+ <span className="inline-flex items-center gap-1">+ <span className="size-2 rounded-full" style={{ backgroundColor: color }} />+ {label}+ </span>+ );+}diff --git a/src/client/src/components/(playground)/memory/memory-list.tsx b/src/client/src/components/(playground)/memory/memory-list.tsxnew file mode 100644index 00000000..523140f3--- /dev/null+++ b/src/client/src/components/(playground)/memory/memory-list.tsx@@ -0,0 +1,206 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import { format } from "date-fns";+import { Search } from "lucide-react";+import { Input } from "@/components/ui/input";+import {+ Pagination,+ PaginationContent,+ PaginationItem,+ PaginationNext,+ PaginationPrevious,+} from "@/components/ui/pagination";+import getMessage from "@/constants/messages";+import type { MemoryListItem } from "@/lib/platform/connectors/memory/read";+import type { MemoryKind } from "@/lib/platform/connectors/memory/graph";++const KIND_DOT: Record<MemoryKind, string> = {+ temporal: "bg-teal-500",+ profile: "bg-orange-500",+ summary: "bg-lime-500",+};++const PAGE_SIZE = 20;++type MemoryListProps = {+ memories: MemoryListItem[];+ search: string;+ onSearchChange: (value: string) => void;+ selectedId?: string | null;+ onSelect: (id: string) => void;+};++export default function MemoryList({+ memories,+ search,+ onSearchChange,+ selectedId,+ onSelect,+}: MemoryListProps) {+ const messages = getMessage();+ const selectedRef = useRef<HTMLButtonElement | null>(null);+ const jumpedForId = useRef<string | null>(null);+ const [page, setPage] = useState(1);+ const query = search.trim().toLowerCase();+ const filtered = useMemo(() => {+ if (!query) return memories;+ return memories.filter((memory) =>+ [memory.content, memory.userId, memory.sessionId, memory.agentId, memory.kind]+ .filter(Boolean)+ .some((value) => String(value).toLowerCase().includes(query))+ );+ }, [memories, query]);+ const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));+ const currentPage = Math.min(page, totalPages);+ const pageItems = filtered.slice(+ (currentPage - 1) * PAGE_SIZE,+ currentPage * PAGE_SIZE+ );++ useEffect(() => {+ jumpedForId.current = null;+ setPage(1);+ }, [query]);++ useEffect(() => {+ if (!selectedId) {+ jumpedForId.current = null;+ return;+ }+ const index = filtered.findIndex((memory) => memory.id === selectedId);+ if (index < 0) return;+ if (jumpedForId.current === selectedId) return;+ jumpedForId.current = selectedId;+ setPage(Math.floor(index / PAGE_SIZE) + 1);+ }, [filtered, selectedId]);++ useEffect(() => {+ if (typeof selectedRef.current?.scrollIntoView !== "function") return;+ selectedRef.current.scrollIntoView({ block: "nearest" });+ }, [selectedId, currentPage]);++ return (+ <section className="flex h-full min-h-0 flex-col border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950">+ <div className="border-b border-stone-200 px-3 py-2 dark:border-stone-800">+ <h2 className="text-sm font-semibold text-stone-950 dark:text-stone-50">+ {messages.MEMORY_LIST_TITLE}+ </h2>+ <div className="relative mt-2">+ <Search className="pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-stone-400" />+ <Input+ value={search}+ onChange={(event) => onSearchChange(event.target.value)}+ placeholder={messages.MEMORY_SEARCH_PLACEHOLDER}+ className="h-8 pl-7"+ />+ </div>+ </div>+ <div className="min-h-0 flex-1 overflow-auto">+ {filtered.length === 0 ? (+ <p className="px-3 py-6 text-center text-xs text-stone-500 dark:text-stone-400">+ {memories.length === 0 ? messages.MEMORY_EMPTY_LIST : messages.MEMORY_NO_MATCHES}+ </p>+ ) : (+ <ul className="divide-y divide-stone-200 dark:divide-stone-800">+ {pageItems.map((memory) => {+ const selected = memory.id === selectedId;+ const kindLabel = kindMessage(messages, memory.kind);+ return (+ <li key={memory.id}>+ <button+ type="button"+ ref={selected ? selectedRef : undefined}+ onClick={() => onSelect(memory.id)}+ className={`flex w-full items-start gap-2 px-3 py-2.5 text-left hover:bg-stone-50 dark:hover:bg-stone-900 ${+ selected ? "bg-stone-100 dark:bg-stone-900" : ""+ }`}+ >+ <span className={`mt-1 size-2 shrink-0 rounded-full ${KIND_DOT[memory.kind]}`} />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-stone-900 dark:text-stone-100">+ {titleFor(memory.content)}+ </span>+ <span className="mt-0.5 block truncate text-[11px] text-stone-500 dark:text-stone-400">+ {kindLabel}+ {memory.userId ? ` · ${memory.userId}` : ""}+ {memory.sessionId ? ` · ${memory.sessionId}` : ""}+ {" · "}+ {formatDate(memory.createdAt || memory.updatedAt, messages.MEMORY_NO_DATE)}+ </span>+ {memory.port ? (+ <span className="mt-0.5 block truncate text-[11px] text-violet-700 dark:text-violet-300">+ {messages.MEMORY_COPY_SOURCE}+ {" · "}+ {memory.port.sourceConnectorName || memory.port.sourceConnectorId}+ </span>+ ) : null}+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ )}+ </div>+ {filtered.length > PAGE_SIZE ? (+ <div className="flex shrink-0 items-center justify-end border-t border-stone-200 px-2 py-1.5 dark:border-stone-800">+ <Pagination className="m-0 w-auto">+ <PaginationContent className="gap-0.5">+ <PaginationItem>+ <PaginationPrevious+ className={`h-7 px-2 py-1 ${+ currentPage === 1+ ? "pointer-events-none cursor-not-allowed text-stone-400"+ : "text-stone-950 dark:text-stone-100"+ }`}+ aria-label={messages.MEMORY_PAGE_PREVIOUS}+ aria-disabled={currentPage === 1}+ onClick={() => setPage((value) => Math.max(1, value - 1))}+ />+ </PaginationItem>+ <PaginationItem>+ <div className="flex items-center whitespace-nowrap px-1 text-xs text-stone-950 dark:text-stone-100">+ {messages.MEMORY_PAGE_OF(currentPage, totalPages)}+ </div>+ </PaginationItem>+ <PaginationItem>+ <PaginationNext+ className={`h-7 px-2 py-1 ${+ currentPage >= totalPages+ ? "pointer-events-none cursor-not-allowed text-stone-400"+ : "text-stone-950 dark:text-stone-100"+ }`}+ aria-label={messages.MEMORY_PAGE_NEXT}+ aria-disabled={currentPage >= totalPages}+ onClick={() => setPage((value) => Math.min(totalPages, value + 1))}+ />+ </PaginationItem>+ </PaginationContent>+ </Pagination>+ </div>+ ) : null}+ </section>+ );+}++function titleFor(content: string): string {+ const line = content.split(/\n/)[0]?.trim() || content;+ return line.length > 72 ? `${line.slice(0, 69).trimEnd()}…` : line;+}++function formatDate(value: string | undefined, fallback: string): string {+ if (!value) return fallback;+ const parsed = new Date(value);+ if (Number.isNaN(parsed.getTime())) return fallback;+ return format(parsed, "MM-dd");+}++function kindMessage(+ messages: ReturnType<typeof getMessage>,+ kind: MemoryKind+): string {+ if (kind === "temporal") return messages.MEMORY_TEMPORAL;+ if (kind === "profile") return messages.MEMORY_PROFILE;+ return messages.MEMORY_SUMMARY;+}diff --git a/src/client/src/components/(playground)/memory/memory-page.tsx b/src/client/src/components/(playground)/memory/memory-page.tsxnew file mode 100644index 00000000..05dc399c--- /dev/null+++ b/src/client/src/components/(playground)/memory/memory-page.tsx@@ -0,0 +1,919 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import Image from "next/image";+import { usePathname, useRouter, useSearchParams } from "next/navigation";+import { usePostHog } from "posthog-js/react";+import { BrainCircuit, Cable, Plus, RefreshCw, ArrowRightLeft } from "lucide-react";+import { toast } from "sonner";+import FeatureAccess from "@/components/rbac/feature-access";+import FeaturePageHeader from "@/components/(playground)/feature-page-header";+import {+ SourceFormDialog,+ type TypeDescriptor,+} from "@/components/(playground)/telemetry-source/data-sources-page";+import { Button } from "@/components/ui/button";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Skeleton } from "@/components/ui/skeleton";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import {+ ResizableHandle,+ ResizablePanel,+ ResizablePanelGroup,+} from "@/components/ui/resizable";+import getMessage from "@/constants/messages";+import { CLIENT_EVENTS } from "@/constants/events";+import { getCurrentProject, getCurrentProjectEnvironment } from "@/selectors/project";+import { useRootStore } from "@/store";+import type {+ MemoryListItem,+ MemoryQueryResult,+} from "@/lib/platform/connectors/memory/read";+import { emptyMemoryStats } from "@/lib/platform/connectors/memory/graph";+import {+ emptyMemoryFilters,+ type MemoryFilterChoice,+ type MemoryFilterField,+ type MemoryFilterKey,+} from "@/lib/platform/connectors/memory/types";+import { connectorIconPath } from "@/lib/platform/connectors/icons";+import { getRequestHeaders } from "@/utils/api";+import MemoryGraph from "./memory-graph";+import MemoryList from "./memory-list";+import MemoryDetailSheet from "./memory-detail-sheet";+import MemoryWriteDialog from "./memory-write-dialog";+import MemoryCopyDialog from "./memory-copy-dialog";+import MemoryFilterCombobox, {+ memoryFilterChoices,+} from "./memory-filter-combobox";+import AskOtterBar from "./ask-otter";++export default function MemoryPage() {+ const messages = getMessage();+ const posthog = usePostHog();+ const router = useRouter();+ const pathname = usePathname();+ const searchParams = useSearchParams();+ const project = useRootStore(getCurrentProject);+ const environment = useRootStore(getCurrentProjectEnvironment) || "production";+ const selectedId = searchParams.get("id");+ const [connectorId, setConnectorId] = useState(+ () => searchParams.get("connectorId") || ""+ );+ const [userId, setUserId] = useState("");+ const [sessionId, setSessionId] = useState("");+ const [agentId, setAgentId] = useState("");+ const [listSearch, setListSearch] = useState("");+ const [loading, setLoading] = useState(true);+ const [loadError, setLoadError] = useState<string | null>(null);+ const [result, setResult] = useState<MemoryQueryResult | null>(null);+ const [addOpen, setAddOpen] = useState(false);+ const [copyOpen, setCopyOpen] = useState(false);+ const [copyIds, setCopyIds] = useState<string[] | undefined>();+ const [addConnectorOpen, setAddConnectorOpen] = useState(false);+ const [memoryDescriptors, setMemoryDescriptors] = useState<TypeDescriptor[]>(+ []+ );+ const [saving, setSaving] = useState(false);+ const autoSelecting = useRef(false);+ const loadSeq = useRef(0);+ const pendingCreated = useRef<MemoryListItem[]>([]);+ const previousEnvironment = useRef(environment);++ const replaceQuery = useCallback(+ (patch: { id?: string | null; connectorId?: string | null }) => {+ const params = new URLSearchParams(searchParams.toString());+ if (patch.id) params.set("id", patch.id);+ else if (patch.id === null) params.delete("id");+ if (patch.connectorId) params.set("connectorId", patch.connectorId);+ else if (patch.connectorId === null) params.delete("connectorId");+ const query = params.toString();+ router.replace(`${pathname}${query ? `?${query}` : ""}`, { scroll: false });+ },+ [pathname, router, searchParams]+ );++ const selectMemory = useCallback(+ (id: string | null) => {+ if (id) {+ replaceQuery({+ id,+ connectorId: connectorId || undefined,+ });+ return;+ }+ replaceQuery({ id: null });+ },+ [connectorId, replaceQuery]+ );++ const connectors = result?.connectors || [];+ const copyTargets = connectors.filter(+ (connector) => connector.id !== connectorId && connector.capabilities?.add+ );+ const selectedMemory = useMemo(+ () => result?.memories.find((memory) => memory.id === selectedId) || null,+ [result?.memories, selectedId]+ );+ const filters = result?.filters || emptyMemoryFilters();+ const filterFields = result?.filterFields || [];++ const loadMemories = useCallback((options?: { silent?: boolean }) => {+ if (!project?.id) {+ setLoading(false);+ return;+ }+ if (!options?.silent) setLoading(true);+ setLoadError(null);+ const seq = ++loadSeq.current;+ const params = new URLSearchParams();+ if (connectorId) params.set("connectorId", connectorId);+ if (userId.trim()) params.set("userId", userId.trim());+ if (sessionId.trim()) params.set("sessionId", sessionId.trim());+ if (agentId.trim()) params.set("agentId", agentId.trim());+ params.set("limit", "100");+ fetch(`/api/memory?${params.toString()}`, {+ headers: getRequestHeaders(),+ })+ .then(async (response) => {+ const body = await response.json().catch(() => null);+ if (!response.ok) {+ throw new Error(apiError(body, messages.MEMORY_LOAD_FAILED));+ }+ return body as MemoryQueryResult;+ })+ .then((payload) => {+ if (seq !== loadSeq.current) return;+ const pending = pendingCreated.current.filter(+ (memory) => !payload.memories.some((item) => item.id === memory.id)+ );+ pendingCreated.current = pending;+ setResult(+ pending.length+ ? {+ ...payload,+ memories: prependMemories(pending, payload.memories),+ }+ : payload+ );+ const nextId = payload.connector?.id ? String(payload.connector.id) : "";+ if (nextId && nextId !== connectorId) setConnectorId(nextId);+ const nextFields = payload.filterFields || [];+ const nextUsers = payload.filters?.users || [];+ const nextSessions = payload.filters?.sessions || [];+ if (!fieldEnabled(nextFields, "userId") && userId) setUserId("");+ if (!fieldEnabled(nextFields, "sessionId") && sessionId) setSessionId("");+ if (!fieldEnabled(nextFields, "agentId") && agentId) setAgentId("");+ const userField = nextFields.find((field) => field.key === "userId");+ const sessionField = nextFields.find((field) => field.key === "sessionId");+ if (userField?.required && !userId && nextUsers.length === 1) {+ autoSelecting.current = true;+ setUserId(nextUsers[0].id);+ } else if (+ sessionField?.required &&+ !sessionId &&+ (payload.hint === "session_required" || payload.hint === "filter_required")+ ) {+ const onlySessions = nextSessions.filter(+ (session) => !userId || !session.userId || session.userId === userId+ );+ if (onlySessions.length === 1) {+ autoSelecting.current = true;+ setSessionId(onlySessions[0].id);+ }+ }+ })+ .catch((caught: unknown) => {+ if (seq !== loadSeq.current) return;+ const message =+ caught instanceof Error ? caught.message : messages.MEMORY_LOAD_FAILED;+ setLoadError(+ /invalid.*api key|authentication_error|authentication failed/i.test(+ message+ )+ ? messages.MEMORY_AUTH_FAILED_HINT+ : messages.MEMORY_UNAVAILABLE_DESCRIPTION+ );+ })+ .finally(() => {+ if (seq !== loadSeq.current) return;+ autoSelecting.current = false;+ setLoading(false);+ });+ }, [+ agentId,+ connectorId,+ environment,+ messages.MEMORY_AUTH_FAILED_HINT,+ messages.MEMORY_LOAD_FAILED,+ messages.MEMORY_UNAVAILABLE_DESCRIPTION,+ project?.id,+ sessionId,+ userId,+ ]);++ useEffect(() => {+ posthog?.capture(CLIENT_EVENTS.MEMORY_PAGE_VISITED);+ }, [posthog]);++ useEffect(() => {+ if (previousEnvironment.current === environment) return;+ previousEnvironment.current = environment;+ setConnectorId("");+ setUserId("");+ setSessionId("");+ setAgentId("");+ setResult(null);+ replaceQuery({ connectorId: null, id: null });+ }, [environment, replaceQuery]);++ useEffect(() => {+ loadMemories();+ }, [loadMemories]);++ useEffect(() => {+ if (!addConnectorOpen) return;+ fetch("/api/connectors/types", { headers: getRequestHeaders() })+ .then(async (response) => {+ const body = await response.json().catch(() => null);+ if (!response.ok) return;+ setMemoryDescriptors(+ ((body?.types || []) as TypeDescriptor[]).filter(+ (descriptor) => descriptor.category === "memory"+ )+ );+ })+ .catch(() => {+ setMemoryDescriptors([]);+ });+ }, [addConnectorOpen]);++ const stats = result?.stats || emptyMemoryStats();+ const statItems = useMemo(+ () => [+ { label: messages.MEMORY_TOTAL, value: stats.total },+ { label: messages.MEMORY_CONNECTIONS, value: stats.connections },+ { label: messages.MEMORY_TEMPORAL, value: stats.temporal, dot: "bg-teal-500" },+ { label: messages.MEMORY_PROFILE, value: stats.profile, dot: "bg-orange-500" },+ { label: messages.MEMORY_SUMMARY, value: stats.summary, dot: "bg-lime-500" },+ ],+ [messages, stats]+ );++ const needsScope =+ result?.hint === "filter_required" || result?.hint === "session_required";+ const connectorError =+ result?.hint === "auth_failed" || result?.hint === "unavailable";+ const hasFilterOptions =+ filterFields.some((field) => field.allowCustom !== false) ||+ filters.users.length + filters.sessions.length + filters.agents.length > 0;+ const showBrowse =+ !loadError && !needsScope && !connectorError && connectors.length > 0;++ function handleConnectorChange(nextId: string) {+ setConnectorId(nextId);+ setUserId("");+ setSessionId("");+ setAgentId("");+ setResult((prev) => {+ if (!prev) return prev;+ return {+ ...prev,+ memories: [] as MemoryListItem[],+ filters: emptyMemoryFilters(),+ filterFields: [],+ graph: { nodes: [], edges: [] },+ hint: undefined,+ connector:+ prev.connectors.find((connector) => connector.id === nextId) ||+ prev.connector,+ };+ });+ replaceQuery({ id: null, connectorId: nextId || null });+ }++ function handleFilterChange(key: MemoryFilterKey, nextId: string) {+ if (key === "userId") {+ handleUserChange(nextId);+ return;+ }+ if (key === "sessionId") {+ setSessionId(nextId);+ return;+ }+ setAgentId(nextId);+ }++ function filterValue(key: MemoryFilterKey): string {+ if (key === "userId") return userId;+ if (key === "sessionId") return sessionId;+ return agentId;+ }++ function filterOptions(field: MemoryFilterField): MemoryFilterChoice[] {+ return memoryFilterChoices(field, filters, userId);+ }++ function handleUserChange(nextId: string) {+ setUserId(nextId);+ if (+ sessionId &&+ !filters.sessions.some(+ (session) =>+ session.id === sessionId && (!session.userId || session.userId === nextId)+ )+ ) {+ setSessionId("");+ }+ }++ function handleAdd(input: {+ content: string;+ userId?: string;+ sessionId?: string;+ agentId?: string;+ }) {+ if (saving) return;+ setSaving(true);+ fetch("/api/memory", {+ method: "POST",+ headers: getRequestHeaders({ "Content-Type": "application/json" }),+ body: JSON.stringify({+ connectorId: connectorId || undefined,+ content: input.content,+ userId: input.userId,+ sessionId: input.sessionId,+ agentId: input.agentId,+ }),+ })+ .then(async (response) => {+ const body = await response.json().catch(() => null);+ if (!response.ok) {+ throw new Error(apiError(body, messages.MEMORY_ADD_FAILED));+ }+ return body as { memories?: MemoryListItem[] };+ })+ .then((payload) => {+ toast.success(messages.MEMORY_ADD_SAVED);+ setAddOpen(false);+ const nextUser = input.userId?.trim() || "";+ const nextSession = input.sessionId?.trim() || "";+ const nextAgent = input.agentId?.trim() || "";+ const filtersChanged =+ (nextUser && nextUser !== userId) ||+ (nextSession && nextSession !== sessionId) ||+ (nextAgent && nextAgent !== agentId);+ if (nextUser) setUserId(nextUser);+ if (nextSession) setSessionId(nextSession);+ if (nextAgent) setAgentId(nextAgent);+ const created = payload.memories || [];+ if (created.length) {+ pendingCreated.current = prependMemories(+ created,+ pendingCreated.current+ );+ setResult((prev) =>+ prev+ ? {+ ...prev,+ memories: prependMemories(created, prev.memories),+ stats: {+ ...prev.stats,+ total:+ prev.stats.total ++ created.filter(+ (memory) =>+ !prev.memories.some((item) => item.id === memory.id)+ ).length,+ },+ }+ : prev+ );+ }+ const createdId = created[0]?.id;+ if (createdId) selectMemory(createdId);+ if (!filtersChanged) loadMemories({ silent: true });+ })+ .catch((caught: unknown) => {+ toast.error(+ caught instanceof Error ? caught.message : messages.MEMORY_ADD_FAILED+ );+ })+ .finally(() => setSaving(false));+ }++ function openCopy(ids?: string[]) {+ setCopyIds(ids);+ setCopyOpen(true);+ }++ function openSourceMemory(sourceConnectorId: string, sourceMemoryId: string) {+ setConnectorId(sourceConnectorId);+ replaceQuery({ id: sourceMemoryId, connectorId: sourceConnectorId });+ }++ function handleCopy(input: {+ targetConnectorId: string;+ userId?: string;+ sessionId?: string;+ agentId?: string;+ }) {+ if (saving) return;+ setSaving(true);+ fetch("/api/memory/copy", {+ method: "POST",+ headers: getRequestHeaders({ "Content-Type": "application/json" }),+ body: JSON.stringify({+ sourceConnectorId: connectorId || undefined,+ targetConnectorId: input.targetConnectorId,+ memoryIds: copyIds,+ userId: userId || undefined,+ sessionId: sessionId || undefined,+ agentId: agentId || undefined,+ targetUserId: input.userId,+ targetSessionId: input.sessionId,+ targetAgentId: input.agentId,+ }),+ })+ .then(async (response) => {+ const body = await response.json().catch(() => null);+ if (!response.ok) {+ throw new Error(apiError(body, messages.MEMORY_COPY_FAILED));+ }+ return body as {+ copied?: number;+ failed?: { id: string }[];+ target?: { name?: string };+ };+ })+ .then((payload) => {+ const copied = payload.copied || 0;+ const failed = payload.failed?.length || 0;+ const targetName = payload.target?.name || messages.MEMORY_COPY_TARGET;+ if (failed && copied) {+ toast.success(messages.MEMORY_COPY_PARTIAL(copied, failed));+ } else {+ toast.success(messages.MEMORY_COPY_SAVED(copied, targetName));+ }+ setCopyOpen(false);+ setConnectorId(input.targetConnectorId);+ replaceQuery({ id: null, connectorId: input.targetConnectorId });+ })+ .catch((caught: unknown) => {+ toast.error(+ caught instanceof Error ? caught.message : messages.MEMORY_COPY_FAILED+ );+ })+ .finally(() => setSaving(false));+ }++ return (+ <div className="flex h-full min-h-0 w-full flex-col overflow-hidden text-stone-700 dark:text-stone-300">+ <FeaturePageHeader+ eyebrow={messages.SIDEBAR_DEVELOP}+ title={messages.FEATURE_MEMORY}+ icon={<BrainCircuit className="h-4 w-4" />}+ tone="border-violet-200 bg-violet-50 text-violet-700 dark:border-violet-900/70 dark:bg-violet-950/40 dark:text-violet-300"+ actions={+ <div className="flex items-center gap-1.5">+ <FeatureAccess access="memory.create" hideWhenDenied>+ {result?.capabilities?.add ? (+ <Button+ size="sm"+ className="h-8 gap-1.5"+ onClick={() => setAddOpen(true)}+ disabled={loading || !project?.id || !connectorId}+ >+ <Plus className="size-3.5" />+ {messages.MEMORY_ADD}+ </Button>+ ) : null}+ {copyTargets.length > 0 ? (+ <Button+ size="sm"+ variant="outline"+ className="h-8 gap-1.5"+ onClick={() => {+ setCopyIds(undefined);+ setCopyOpen(true);+ }}+ disabled={loading || !project?.id || !connectorId || !result?.memories.length}+ >+ <ArrowRightLeft className="size-3.5" />+ {messages.MEMORY_COPY}+ </Button>+ ) : null}+ </FeatureAccess>+ <FeatureAccess access="connectors.create" hideWhenDenied>+ <Button+ size="sm"+ variant="outline"+ className="h-8 gap-1.5"+ onClick={() => setAddConnectorOpen(true)}+ disabled={!project?.id}+ >+ <Cable className="size-3.5" />+ {messages.ADD_CONNECTOR}+ </Button>+ </FeatureAccess>+ <Button+ size="sm"+ variant="outline"+ className="h-8 gap-1.5"+ onClick={() => loadMemories()}+ disabled={loading || !project?.id}+ >+ <RefreshCw className={`size-3.5 ${loading ? "animate-spin" : ""}`} />+ {messages.MEMORY_REFRESH}+ </Button>+ </div>+ }+ />++ <FeatureAccess access="memory.read" requireProject>+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex flex-wrap items-center gap-2 border-b border-stone-200 px-4 py-2 dark:border-stone-800">+ <FilterSelect+ label={messages.MEMORY_CONNECTOR_LABEL}+ value={connectorId}+ options={connectors.map((connector) => ({+ id: connector.id,+ label: connector.name,+ icon: connectorIconPath(connector.type),+ }))}+ onChange={handleConnectorChange}+ disabled={loading || connectors.length === 0}+ widthClass="w-[260px]"+ />+ {filterFields.map((field) => (+ <MemoryFilterCombobox+ key={`${connectorId}-${field.key}`}+ label={field.label}+ value={filterValue(field.key)}+ options={filterOptions(field)}+ onChange={(next) => handleFilterChange(field.key, next)}+ allowCustom={field.allowCustom !== false}+ disabled={loading}+ required={field.required}+ widthClass="w-[240px]"+ />+ ))}+ </div>++ <ResizablePanelGroup+ direction="horizontal"+ autoSaveId="memory-page-split"+ className="min-h-0 flex-1"+ >+ <ResizablePanel defaultSize={70} minSize={50}>+ <div className="flex h-full min-h-0 flex-col overflow-hidden">+ {!loading && connectors.length === 0 ? (+ <EmptyPanel+ title={messages.FEATURE_MEMORY}+ description={messages.MEMORY_EMPTY_CONNECTORS}+ action={+ <FeatureAccess access="connectors.create" hideWhenDenied>+ <Button size="sm" onClick={() => setAddConnectorOpen(true)}>+ {messages.MEMORY_EMPTY_CONNECTORS_ACTION}+ </Button>+ </FeatureAccess>+ }+ />+ ) : loadError || connectorError ? (+ <EmptyPanel+ title={messages.MEMORY_UNAVAILABLE_TITLE}+ description={+ result?.hint === "auth_failed"+ ? messages.MEMORY_AUTH_FAILED_HINT+ : loadError || messages.MEMORY_UNAVAILABLE_DESCRIPTION+ }+ action={+ <Button size="sm" variant="outline" onClick={() => loadMemories()}>+ {messages.MEMORY_RETRY}+ </Button>+ }+ />+ ) : needsScope && !loading ? (+ <EmptyPanel+ title={messages.FEATURE_MEMORY}+ description={+ !hasFilterOptions+ ? messages.MEMORY_FILTER_EMPTY+ : result?.hint === "session_required"+ ? messages.MEMORY_SESSION_REQUIRED_HINT+ : messages.MEMORY_FILTER_REQUIRED_HINT+ }+ />+ ) : showBrowse || loading ? (+ <>+ <div className="grid grid-cols-[repeat(auto-fit,minmax(7.5rem,1fr))] gap-2 px-4 py-3">+ {loading && !result+ ? Array.from({ length: 5 }).map((_, index) => (+ <StatCardSkeleton key={index} />+ ))+ : statItems.map((item) => (+ <StatCard+ key={item.label}+ {...item}+ dimmed={loading}+ />+ ))}+ </div>+ <Tabs+ defaultValue="graph"+ className="flex min-h-0 flex-1 flex-col overflow-hidden px-4 pb-3"+ >+ <TabsList className="h-9 w-max justify-start rounded-md bg-stone-100 p-1 dark:bg-stone-900">+ <TabsTrigger value="graph" className="shrink-0 px-3 py-1 text-xs">+ {messages.MEMORY_GRAPH_TITLE}+ </TabsTrigger>+ <TabsTrigger value="list" className="shrink-0 px-3 py-1 text-xs">+ {messages.MEMORY_LIST_TITLE}+ </TabsTrigger>+ </TabsList>+ <TabsContent+ value="graph"+ forceMount+ className="mt-2 min-h-0 flex-1 overflow-hidden data-[state=inactive]:hidden data-[state=active]:flex data-[state=active]:flex-col"+ >+ {loading && !result ? (+ <div className="flex h-full min-h-[280px] items-center justify-center rounded-md border border-dashed border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950">+ <div className="flex flex-col items-center gap-2 px-4 text-center">+ <Skeleton className="h-8 w-8 rounded-full" />+ <Skeleton className="h-3 w-40" />+ <Skeleton className="h-3 w-28" />+ </div>+ </div>+ ) : (+ <div+ className={`h-full min-h-0 ${+ loading ? "pointer-events-none opacity-60" : ""+ }`}+ >+ <MemoryGraph+ graph={result?.graph || { nodes: [], edges: [] }}+ selectedId={selectedId}+ onSelect={selectMemory}+ />+ </div>+ )}+ </TabsContent>+ <TabsContent+ value="list"+ forceMount+ className="mt-2 min-h-0 flex-1 overflow-hidden data-[state=inactive]:hidden data-[state=active]:flex data-[state=active]:flex-col"+ >+ {loading && !result ? (+ <div className="flex h-full min-h-[280px] flex-col gap-2 rounded-md border border-stone-200 bg-white p-3 dark:border-stone-800 dark:bg-stone-950">+ <Skeleton className="h-8 w-full rounded-md" />+ <Skeleton className="h-12 w-full rounded-md" />+ <Skeleton className="h-12 w-full rounded-md" />+ <Skeleton className="h-12 w-full rounded-md" />+ </div>+ ) : (+ <div+ className={`h-full min-h-0 ${+ loading ? "pointer-events-none opacity-60" : ""+ }`}+ >+ <MemoryList+ memories={result?.memories || []}+ search={listSearch}+ onSearchChange={setListSearch}+ selectedId={selectedId}+ onSelect={selectMemory}+ />+ </div>+ )}+ </TabsContent>+ </Tabs>+ </>+ ) : null}+ </div>+ </ResizablePanel>+ <ResizableHandle+ withHandle+ aria-label={messages.MEMORY_SPLIT_RESIZE}+ />+ <ResizablePanel defaultSize={30} minSize={22} maxSize={42}>+ <div className="h-full min-h-0 overflow-hidden border-l border-stone-200 dark:border-stone-800">+ <AskOtterBar+ layout="fill"+ disabled={connectors.length === 0}+ scope={{+ connectorId,+ userId: fieldEnabled(filterFields, "userId")+ ? userId+ : undefined,+ sessionId: fieldEnabled(filterFields, "sessionId")+ ? sessionId+ : undefined,+ agentId: fieldEnabled(filterFields, "agentId")+ ? agentId+ : undefined,+ memoryId: selectedMemory?.id || selectedId || undefined,+ memoryContent: selectedMemory?.content,+ filterKeys: filterFields.map((field) => field.key),+ canList: result?.capabilities?.list === true,+ canSearch: result?.capabilities?.search === true,+ }}+ />+ </div>+ </ResizablePanel>+ </ResizablePanelGroup>+ <MemoryDetailSheet+ open={!!selectedId}+ memoryId={selectedId}+ memoryIds={(result?.memories || []).map((memory) => memory.id)}+ connectorId={connectorId}+ capabilities={result?.capabilities}+ preview={selectedMemory}+ onSelect={selectMemory}+ onClose={() => selectMemory(null)}+ onChanged={() => loadMemories()}+ onCopy={copyTargets.length ? (id) => openCopy([id]) : undefined}+ onOpenSource={openSourceMemory}+ />+ <MemoryWriteDialog+ open={addOpen}+ mode="add"+ scope={{ userId, sessionId, agentId }}+ filterFields={filterFields}+ filters={filters}+ saving={saving}+ onOpenChange={setAddOpen}+ onSubmit={handleAdd}+ />+ <MemoryCopyDialog+ open={copyOpen}+ count={copyIds?.length || result?.memories.length || 0}+ targets={copyTargets}+ saving={saving}+ onOpenChange={setCopyOpen}+ onSubmit={handleCopy}+ />+ {addConnectorOpen ? (+ <SourceFormDialog+ source={null}+ descriptors={memoryDescriptors}+ initialType=""+ initialEnvironment={environment}+ showRouting={false}+ onClose={() => setAddConnectorOpen(false)}+ onSaved={() => {+ setAddConnectorOpen(false);+ loadMemories({ silent: true });+ }}+ />+ ) : null}+ </div>+ </FeatureAccess>+ </div>+ );+}++function prependMemories(+ incoming: MemoryListItem[],+ existing: MemoryListItem[]+): MemoryListItem[] {+ if (!incoming.length) return existing;+ const seen = new Set(incoming.map((memory) => memory.id));+ return [...incoming, ...existing.filter((memory) => !seen.has(memory.id))];+}++function fieldEnabled(+ fields: MemoryFilterField[],+ key: MemoryFilterKey+): boolean {+ return fields.some((field) => field.key === key);+}++function apiError(body: unknown, fallback: string): string {+ if (typeof body === "string" && body.trim()) return body;+ if (body && typeof body === "object") {+ const record = body as { err?: unknown; error?: unknown };+ if (typeof record.err === "string" && record.err.trim()) return record.err;+ if (typeof record.error === "string" && record.error.trim()) return record.error;+ }+ return fallback;+}++function FilterSelect({+ label,+ value,+ options,+ onChange,+ disabled,+ widthClass = "w-[180px]",+}: {+ label: string;+ value: string;+ options: Array<MemoryFilterChoice & { icon?: string }>;+ onChange: (value: string) => void;+ disabled?: boolean;+ widthClass?: string;+}) {+ const selected = options.find((option) => option.id === value);+ return (+ <Select value={selected?.id} onValueChange={onChange} disabled={disabled}>+ <SelectTrigger className={`h-8 ${widthClass}`} aria-label={label}>+ <SelectValue placeholder={label}>+ {selected ? (+ <span className="flex min-w-0 items-center gap-2">+ {selected.icon ? (+ <Image+ src={selected.icon}+ alt=""+ width={16}+ height={16}+ className="h-4 w-4 shrink-0 object-contain"+ />+ ) : null}+ <span className="truncate">{selected.label}</span>+ </span>+ ) : undefined}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {options.map((option) => (+ <SelectItem key={option.id} value={option.id}>+ <span className="flex min-w-0 items-center gap-2">+ {option.icon ? (+ <Image+ src={option.icon}+ alt=""+ width={16}+ height={16}+ className="h-4 w-4 shrink-0 object-contain"+ />+ ) : null}+ <span className="truncate">{option.label}</span>+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++function EmptyPanel({+ title,+ description,+ action,+}: {+ title: string;+ description: string;+ action?: ReactNode;+}) {+ return (+ <div className="m-4 flex flex-1 flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-stone-200 bg-white px-6 py-12 text-center dark:border-stone-800 dark:bg-stone-950">+ <BrainCircuit className="h-8 w-8 text-stone-400 dark:text-stone-500" />+ <p className="text-sm font-semibold text-stone-900 dark:text-stone-100">{title}</p>+ <p className="max-w-md text-xs text-stone-500 dark:text-stone-400">{description}</p>+ {action ? <div className="mt-2">{action}</div> : null}+ </div>+ );+}++function StatCard({+ label,+ value,+ dot,+ dimmed,+}: {+ label: string;+ value: number;+ dot?: string;+ dimmed?: boolean;+}) {+ return (+ <div+ className={`rounded-md border border-stone-200 bg-white px-3 py-2 dark:border-stone-800 dark:bg-stone-950 ${+ dimmed ? "opacity-60" : ""+ }`}+ >+ <p className="flex items-center gap-1.5 text-[11px] uppercase tracking-wide text-stone-500 dark:text-stone-400">+ {dot ? <span className={`size-1.5 rounded-full ${dot}`} /> : null}+ {label}+ </p>+ <p className="mt-1 text-lg font-semibold tabular-nums text-stone-950 dark:text-stone-50">+ {value}+ </p>+ </div>+ );+}++function StatCardSkeleton() {+ return (+ <div className="rounded-md border border-stone-200 bg-white px-3 py-2 dark:border-stone-800 dark:bg-stone-950">+ <Skeleton className="h-3 w-16" />+ <Skeleton className="mt-2 h-6 w-10" />+ </div>+ );+}diff --git a/src/client/src/components/(playground)/memory/memory-write-dialog.tsx b/src/client/src/components/(playground)/memory/memory-write-dialog.tsxnew file mode 100644index 00000000..2554d14e--- /dev/null+++ b/src/client/src/components/(playground)/memory/memory-write-dialog.tsx@@ -0,0 +1,173 @@+"use client";++import { useEffect, useState } from "react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Label } from "@/components/ui/label";+import { Textarea } from "@/components/ui/textarea";+import getMessage from "@/constants/messages";+import {+ emptyMemoryFilters,+ MEMORY_CONTENT_MAX,+ type MemoryFilterField,+ type MemoryFilterKey,+ type MemoryFilterOptions,+} from "@/lib/platform/connectors/memory/types";+import {+ applyMemoryFilterChange,+ keepDialogPopoverOpen,+ MemoryDialogFilterFields,+ memoryFilterRequiredMissing,+ trimmedMemoryFilterScope,+ type MemoryFilterScope,+} from "./memory-filter-fields";++export type MemoryWriteScope = {+ userId?: string;+ sessionId?: string;+ agentId?: string;+};++type MemoryWriteDialogProps = {+ open: boolean;+ mode: "add" | "edit";+ content?: string;+ scope?: MemoryWriteScope;+ filterFields?: MemoryFilterField[];+ filters?: MemoryFilterOptions;+ saving?: boolean;+ onOpenChange: (open: boolean) => void;+ onSubmit: (input: { content: string } & MemoryWriteScope) => void;+};++export default function MemoryWriteDialog({+ open,+ mode,+ content,+ scope,+ filterFields = [],+ filters = emptyMemoryFilters(),+ saving,+ onOpenChange,+ onSubmit,+}: MemoryWriteDialogProps) {+ const messages = getMessage();+ const [draft, setDraft] = useState(content || "");+ const [filterScope, setFilterScope] = useState<MemoryFilterScope>(() =>+ alignedWriteScope(scope, filters)+ );++ useEffect(() => {+ if (!open) return;+ setDraft(content || "");+ setFilterScope(alignedWriteScope(scope, filters));+ // Hydrate once when the dialog opens so parent list refreshes don't wipe edits.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open]);++ const showScope = mode === "add" && filterFields.length > 0;+ const trimmed = draft.trim();+ const missingRequired =+ mode === "add" && memoryFilterRequiredMissing(filterFields, filterScope);+ const canSave = !!trimmed && !saving && !missingRequired;++ function setFieldValue(key: MemoryFilterKey, next: string) {+ setFilterScope((current) => applyMemoryFilterChange(current, filters, key, next));+ }++ function handleSubmit() {+ if (!canSave) return;+ onSubmit({+ content: trimmed,+ ...trimmedMemoryFilterScope(filterScope),+ });+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ className="sm:max-w-lg"+ onPointerDownOutside={keepDialogPopoverOpen}+ onInteractOutside={keepDialogPopoverOpen}+ >+ <DialogHeader>+ <DialogTitle>+ {mode === "add" ? messages.MEMORY_ADD_TITLE : messages.MEMORY_EDIT_TITLE}+ </DialogTitle>+ {mode === "add" ? (+ <DialogDescription>{messages.MEMORY_ADD_DESCRIPTION}</DialogDescription>+ ) : null}+ </DialogHeader>+ <div className="space-y-3">+ <div className="space-y-1.5">+ <Label htmlFor="memory-content">{messages.MEMORY_DETAIL_MEMORY}</Label>+ <Textarea+ id="memory-content"+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ placeholder={messages.MEMORY_ADD_PLACEHOLDER}+ maxLength={MEMORY_CONTENT_MAX}+ disabled={saving}+ className="min-h-[140px] text-sm text-stone-900 dark:text-stone-100"+ />+ </div>+ {showScope ? (+ <MemoryDialogFilterFields+ fields={filterFields}+ filters={filters}+ scope={filterScope}+ onChange={setFieldValue}+ disabled={saving}+ />+ ) : null}+ </div>+ <DialogFooter>+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={saving}+ onClick={() => onOpenChange(false)}+ >+ {messages.MEMORY_CANCEL}+ </Button>+ <Button type="button" size="sm" disabled={!canSave} onClick={handleSubmit}>+ {mode === "add" ? messages.MEMORY_ADD_SAVE : messages.MEMORY_EDIT_SAVE}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++function alignedWriteScope(+ scope: MemoryWriteScope | undefined,+ filters: MemoryFilterOptions+): MemoryFilterScope {+ const userId = scope?.userId?.trim() || "";+ const sessionId = scope?.sessionId?.trim() || "";+ const agentId = scope?.agentId?.trim() || "";+ const userIds = new Set(filters.users.map((item) => item.id));+ const sessionIds = new Set(filters.sessions.map((item) => item.id));+ const userIsSession = !!userId && sessionIds.has(userId) && !userIds.has(userId);+ const sessionIsUser = !!sessionId && userIds.has(sessionId) && !sessionIds.has(sessionId);+ if (!userIsSession && !sessionIsUser) {+ return { userId, sessionId, agentId };+ }+ return {+ userId: sessionIsUser+ ? sessionId+ : userIsSession+ ? filters.sessions.find((item) => item.id === userId)?.userId || ""+ : userId,+ sessionId: userIsSession ? userId : sessionIsUser ? "" : sessionId,+ agentId,+ };+}diff --git a/src/client/src/components/(playground)/telemetry-source/data-sources-page.tsx b/src/client/src/components/(playground)/telemetry-source/data-sources-page.tsxindex e3c281d8..26aa19b2 100644--- a/src/client/src/components/(playground)/telemetry-source/data-sources-page.tsx+++ b/src/client/src/components/(playground)/telemetry-source/data-sources-page.tsx@@ -12,20 +12,32 @@ import {Settings2,BookOpen,ExternalLink,+ Search,} from "lucide-react";import Image from "next/image";import Link from "next/link";import { Button } from "@/components/ui/button";import DatabaseConfigPage from "@/components/(playground)/database-config/database-config-page";+import { deleteDatabaseConfig } from "@/helpers/client/database-config";+import type { DatabaseConfigWithActive } from "@/constants/dbConfig";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Badge } from "@/components/ui/badge";import { Switch } from "@/components/ui/switch";-import { Separator } from "@/components/ui/separator";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";import {Select,SelectContent,+ SelectGroup,SelectItem,+ SelectLabel,SelectTrigger,SelectValue,} from "@/components/ui/select";@@ -52,17 +64,19 @@ import { useRootStore } from "@/store";import { getCurrentProjectEnvironment } from "@/selectors/project";import { getRequestHeaders } from "@/utils/api";import { isVisibleConnectorType } from "@/lib/platform/connectors/visible-types";+import { configuredConnectorMatches, CONNECTOR_FILTER_ALL_VALUE } from "@/lib/platform/connectors/list-filters";type Signal = "traces" | "logs" | "metrics" | "intelligence";const SIGNALS: Signal[] = ["traces", "logs", "metrics", "intelligence"];const BUILTIN = "builtin";-interface TypeDescriptor {+export interface TypeDescriptor {type: string;displayName: string;description?: string;icon?: string;- declaredSignals: Signal[];+ category?: string;+ declaredSignals?: Signal[];correlation?: { crossSignal: boolean; keys: string[] };configFields?: FieldDef[];authStyle?: "none" | "http" | "api-key" | "custom";@@ -94,6 +108,7 @@ interface SourceRow {settings: string;isDefault: boolean;hasSecret?: boolean;+ category?: string;}interface BindingRow {@@ -179,6 +194,60 @@ async function jsonFetch(url: string, init?: RequestInit) {return body;}+function reportConnectorHealth(+ messages: ReturnType<typeof getMessage>,+ descriptors: TypeDescriptor[],+ type: string,+ res: {+ health?: { ok?: boolean; message?: string };+ validation?: {+ supported?: boolean;+ message?: string;+ ok?: boolean;+ sampleCount?: number;+ };+ }+) {+ const health = res?.health;+ const validation = res?.validation;+ if (!health?.ok) {+ const raw = String(health?.message || "");+ const usesHttpAuth =+ descriptors.find((d) => d.type === type)?.authStyle === "http";+ const hint =+ /401|no credentials|unauthorized/i.test(raw) && usesHttpAuth+ ? ` ${messages.DATA_SOURCE_AUTH_401_HINT}`+ : "";+ toast.error(+ (health?.message || messages.DATA_SOURCE_SAVE_FAILED) + hint,+ { id: "ds-test" }+ );+ return;+ }+ if (validation?.supported === false) {+ toast.success(messages.DATA_SOURCE_TEST_OK, { id: "ds-test" });+ return;+ }+ if (validation?.message) {+ const raw = String(validation.message);+ const hint = /401|no credentials|unauthorized/i.test(raw)+ ? ` ${messages.DATA_SOURCE_AUTH_401_HINT}`+ : "";+ toast.error(+ messages.DATA_SOURCE_TEST_VALIDATION_FAILED(raw) + hint,+ { id: "ds-test" }+ );+ return;+ }+ if (validation?.ok && (validation.sampleCount || 0) > 0) {+ toast.success(messages.DATA_SOURCE_TEST_AI_OK(validation.sampleCount || 0), {+ id: "ds-test",+ });+ return;+ }+ toast.success(messages.DATA_SOURCE_TEST_AI_NONE, { id: "ds-test" });+}+export default function DataSourcesPage({projectId,showRouting = true,@@ -200,13 +269,22 @@ export default function DataSourcesPage({const [descriptors, setDescriptors] = useState<TypeDescriptor[]>([]);const [bindings, setBindings] = useState<BindingRow[]>([]);const [editing, setEditing] = useState<SourceRow | "new" | null>(null);+ const [dbEditing, setDbEditing] = useState<DatabaseConfigWithActive | "new" | null>(null);const [newType, setNewType] = useState<string | undefined>();const [testingId, setTestingId] = useState<string | null>(null);+ const [connectorSearch, setConnectorSearch] = useState("");+ const [typeFilter, setTypeFilter] = useState(CONNECTOR_FILTER_ALL_VALUE);+ const [categoryFilter, setCategoryFilter] = useState(CONNECTOR_FILTER_ALL_VALUE);+ const [signalFilter, setSignalFilter] = useState(CONNECTOR_FILTER_ALL_VALUE);const environment = currentProjectEnvironment || "production";const visibleSources = useMemo(() => sources.filter((source) => (source.environment || "production") === environment),[environment, sources]);+ const routingSources = useMemo(+ () => visibleSources.filter((source) => source.category !== "memory"),+ [visibleSources]+ );const load = useCallback(async () => {setLoading(true);@@ -252,11 +330,14 @@ export default function DataSourcesPage({}, [environment, messages.DATA_SOURCE_LOAD_FAILED]);useEffect(() => {- if (openType) {- setNewType(openType);+ if (openType == null) return;+ if (openType === "clickhouse") {+ setDbEditing("new");+ } else {+ setNewType(openType || undefined);setEditing("new");- onOpenTypeHandled?.();}+ onOpenTypeHandled?.();}, [onOpenTypeHandled, openType]);useEffect(() => {@@ -340,64 +421,137 @@ export default function DataSourcesPage({}};- const testSource = async (row: SourceRow) => {+ const removeClickhouse = async (config: DatabaseConfigWithActive) => {+ if (!config.permissions?.canDelete) return;+ if (!window.confirm(messages.DATA_SOURCE_DELETE_CONFIRM(config.name))) return;+ await deleteDatabaseConfig(config.id);+ await load();+ };++ const testConnector = async (row: SourceRow) => {setTestingId(row.id);toast.loading(messages.DATA_SOURCE_TESTING, { id: "ds-test" });try {const res = await jsonFetch(`/api/connectors/${row.id}/health`, {method: "POST",});- const health = res?.health;- const validation = res?.validation;- if (!health?.ok) {- const raw = String(health?.message || "");- const usesHttpAuth =- descriptors.find((d) => d.type === row.type)?.authStyle === "http";- const hint =- /401|no credentials|unauthorized/i.test(raw) && usesHttpAuth- ? ` ${messages.DATA_SOURCE_AUTH_401_HINT}`- : "";- toast.error(- (health?.message || messages.DATA_SOURCE_SAVE_FAILED) + hint,- { id: "ds-test" }- );- return;- }- // Loki/Mimir (and other non-trace sources) skip AI-span validation.- if (validation?.supported === false) {- toast.success(messages.DATA_SOURCE_TEST_OK, { id: "ds-test" });- return;- }- if (validation?.message) {- const raw = String(validation.message);- const hint = /401|no credentials|unauthorized/i.test(raw)- ? ` ${messages.DATA_SOURCE_AUTH_401_HINT}`- : "";- toast.error(- messages.DATA_SOURCE_TEST_VALIDATION_FAILED(raw) + hint,- { id: "ds-test" }- );- return;- }- if (validation?.ok && validation.sampleCount > 0) {- toast.success(messages.DATA_SOURCE_TEST_AI_OK(validation.sampleCount), {- id: "ds-test",- });- } else {- // Replace the loading toast with a finite, dismissible result. Using- // toast.message here can leave the original loading notification- // visible in Sonner when the validation returns zero samples.- toast.success(messages.DATA_SOURCE_TEST_AI_NONE, { id: "ds-test" });+ reportConnectorHealth(messages, descriptors, row.type, res);+ } catch (e: unknown) {+ toast.error(+ e instanceof Error ? e.message : messages.DATA_SOURCE_SAVE_FAILED,+ { id: "ds-test" }+ );+ } finally {+ setTestingId(null);+ }+ };++ const testClickhouse = async (config: DatabaseConfigWithActive) => {+ setTestingId(`clickhouse:${config.id}`);+ toast.loading(messages.DATA_SOURCE_TESTING, { id: "ds-test" });+ try {+ const response = await fetch("/api/clickhouse", { method: "POST" });+ const body = await response.json().catch(() => ({}));+ if (!response.ok || body?.err) {+ throw new Error(body?.err || messages.DATA_SOURCE_SAVE_FAILED);}- } catch (e: any) {- toast.error(e?.message || messages.DATA_SOURCE_SAVE_FAILED, {- id: "ds-test",- });+ toast.success(messages.DATA_SOURCE_TEST_OK, { id: "ds-test" });+ } catch (e: unknown) {+ toast.error(+ e instanceof Error ? e.message : messages.DATA_SOURCE_SAVE_FAILED,+ { id: "ds-test" }+ );} finally {setTestingId(null);}};+ const clickhouseDescriptor = descriptors.find((d) => d.type === "clickhouse");+ const clickhouseSignals = useMemo(+ (): Signal[] =>+ (clickhouseDescriptor?.declaredSignals || [+ "traces",+ "logs",+ "metrics",+ ]) as Signal[],+ [clickhouseDescriptor]+ );+ const hasRows = environmentDatabases.length > 0 || visibleSources.length > 0;+ const typeOptions = useMemo(() => {+ const types = new Set<string>();+ if (environmentDatabases.length > 0) types.add("clickhouse");+ for (const source of visibleSources) types.add(source.type);+ return Array.from(types)+ .sort()+ .map((type) => ({+ type,+ label: descriptors.find((descriptor) => descriptor.type === type)?.displayName || type,+ }));+ }, [descriptors, environmentDatabases.length, visibleSources]);+ const filteredDatabases = useMemo(+ () =>+ environmentDatabases.filter((config) =>+ configuredConnectorMatches({+ query: connectorSearch,+ typeFilter,+ categoryFilter,+ signalFilter,+ type: "clickhouse",+ category: "datasource",+ signals: clickhouseSignals,+ searchText: [+ config.name,+ "clickhouse",+ config.host,+ config.port,+ config.environment,+ ...clickhouseSignals,+ ].join(" "),+ })+ ),+ [+ categoryFilter,+ clickhouseSignals,+ connectorSearch,+ environmentDatabases,+ signalFilter,+ typeFilter,+ ]+ );+ const filteredSources = useMemo(+ () =>+ visibleSources.filter((source) => {+ const signals = parseSignals(source.signals);+ const category = source.category === "memory" ? "memory" : "datasource";+ return configuredConnectorMatches({+ query: connectorSearch,+ typeFilter,+ categoryFilter,+ signalFilter,+ type: source.type,+ category,+ signals,+ searchText: [+ source.name,+ source.type,+ source.environment,+ source.category,+ source.signals,+ category === "memory" ? messages.CONNECTOR_CATEGORY_MEMORY : "",+ ].join(" "),+ });+ }),+ [+ categoryFilter,+ connectorSearch,+ messages.CONNECTOR_CATEGORY_MEMORY,+ signalFilter,+ typeFilter,+ visibleSources,+ ]+ );+ const hasFilteredRows = filteredDatabases.length > 0 || filteredSources.length > 0;+return (<div className="flex h-full w-full flex-col gap-4 overflow-auto text-stone-700 dark:text-stone-300">{showRouting && (@@ -405,7 +559,7 @@ export default function DataSourcesPage({projectId={projectId}environment={environment}databaseConfigs={databaseConfigs}- sources={visibleSources}+ sources={routingSources}descriptors={descriptors}bindingForSignal={bindingForSignal}onSetBinding={setBinding}@@ -415,37 +569,92 @@ export default function DataSourcesPage({}}/>)}- <section className="grid gap-3 border border-stone-200 bg-white p-4 md:grid-cols-2 dark:border-stone-800 dark:bg-stone-950">- <div className="-mx-4 -mt-4 flex flex-wrap items-start justify-between gap-3 border-b border-stone-200 p-4 md:col-span-2 dark:border-stone-800">- <div>- <div className="flex items-center gap-2">- <Database className="h-4 w-4 text-primary" />- <h2 className="text-sm font-semibold text-stone-950 dark:text-stone-50">Connectors · {environment}</h2>- </div>- <p className="mt-1 text-xs text-muted-foreground">{messages.PROJECT_CONNECTORS_DESCRIPTION} Add multiple ClickHouse targets and external integrations to each environment, then choose the connector used by each signal.</p>- </div>- <div className="flex items-center gap-2">+ <section className="flex flex-col gap-3 border border-stone-200 bg-white p-4 dark:border-stone-800 dark:bg-stone-950">+ <div className="-mx-4 -mt-4 flex flex-col gap-3 border-b border-stone-200 p-4 dark:border-stone-800">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <div className="flex items-center gap-2">+ <Database className="h-4 w-4 text-primary" />+ <h2 className="text-sm font-semibold text-stone-950 dark:text-stone-50">{messages.CONNECTED_CONNECTORS} · {environment}</h2>+ </div>+ <p className="mt-1 text-xs text-muted-foreground">{messages.PROJECT_CONNECTORS_DESCRIPTION}</p>+ </div><FeatureAccess access="connectors.create" hideWhenDenied>- <Button size="sm" onClick={() => setEditing("new")}>+ <Button size="sm" onClick={() => { setNewType(undefined); setEditing("new"); }}><Plus className="mr-1.5 h-3.5 w-3.5" />- {messages.DATA_SOURCE_ADD}+ {messages.ADD_CONNECTOR}</Button></FeatureAccess></div>+ <div className="flex flex-wrap items-center gap-2">+ <div className="relative min-w-[12rem] flex-1">+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />+ <Input+ value={connectorSearch}+ onChange={(event) => setConnectorSearch(event.target.value)}+ placeholder={messages.CONNECTOR_SEARCH_PLACEHOLDER}+ aria-label={messages.CONNECTOR_SEARCH_PLACEHOLDER}+ className="h-8 bg-white pl-8 dark:bg-stone-950"+ />+ </div>+ <Select value={typeFilter} onValueChange={setTypeFilter}>+ <SelectTrigger+ className="h-8 w-[148px] bg-white text-xs dark:bg-stone-950"+ aria-label={messages.CONNECTOR_FILTER_TYPE}+ >+ <SelectValue placeholder={messages.CONNECTOR_FILTER_TYPE} />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={CONNECTOR_FILTER_ALL_VALUE}>{messages.CONNECTOR_FILTER_ALL_TYPES}</SelectItem>+ {typeOptions.map((option) => (+ <SelectItem key={option.type} value={option.type}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Select value={categoryFilter} onValueChange={setCategoryFilter}>+ <SelectTrigger+ className="h-8 w-[148px] bg-white text-xs dark:bg-stone-950"+ aria-label={messages.CONNECTOR_FILTER_CATEGORY}+ >+ <SelectValue placeholder={messages.CONNECTOR_FILTER_CATEGORY} />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={CONNECTOR_FILTER_ALL_VALUE}>{messages.CONNECTOR_FILTER_ALL_CATEGORIES}</SelectItem>+ <SelectItem value="datasource">{messages.CONNECTOR_CATEGORY_DATASOURCE}</SelectItem>+ <SelectItem value="memory">{messages.CONNECTOR_CATEGORY_MEMORY}</SelectItem>+ </SelectContent>+ </Select>+ <Select value={signalFilter} onValueChange={setSignalFilter}>+ <SelectTrigger+ className="h-8 w-[148px] bg-white text-xs dark:bg-stone-950"+ aria-label={messages.CONNECTOR_FILTER_SIGNAL}+ >+ <SelectValue placeholder={messages.CONNECTOR_FILTER_SIGNAL} />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={CONNECTOR_FILTER_ALL_VALUE}>{messages.CONNECTOR_FILTER_ALL_SIGNALS}</SelectItem>+ <SelectItem value="traces">{messages.DATA_SOURCE_SIGNAL_TRACES}</SelectItem>+ <SelectItem value="logs">{messages.DATA_SOURCE_SIGNAL_LOGS}</SelectItem>+ <SelectItem value="metrics">{messages.DATA_SOURCE_SIGNAL_METRICS}</SelectItem>+ <SelectItem value="intelligence">{messages.DATA_SOURCE_SIGNAL_INTELLIGENCE}</SelectItem>+ </SelectContent>+ </Select>+ </div></div>- <div className="contents">- <DatabaseConfigPage hideHeader hideEmpty />- </div>- <div className="contents">- {/* External sources list */}- {loading ? (- <div className="contents">- {[0].map((item) => (- <div key={item} className="flex min-h-[168px] flex-col gap-4 rounded-lg border border-stone-200 bg-stone-50/70 p-4 dark:border-stone-800 dark:bg-stone-900/50">- <div className="flex items-center gap-3"><div className="h-9 w-9 animate-pulse rounded-md bg-stone-200 dark:bg-stone-800" /><div className="space-y-2"><div className="h-3 w-32 animate-pulse rounded bg-stone-200 dark:bg-stone-800" /><div className="h-2.5 w-20 animate-pulse rounded bg-stone-200 dark:bg-stone-800" /></div></div>- <div className="space-y-2"><div className="h-2.5 w-full animate-pulse rounded bg-stone-200 dark:bg-stone-800" /><div className="h-2.5 w-3/4 animate-pulse rounded bg-stone-200 dark:bg-stone-800" /></div>- <div className="mt-auto h-8 animate-pulse rounded bg-stone-200 dark:bg-stone-800" />- </div>+ <DatabaseConfigPage+ hideHeader+ hideEmpty+ hideList+ editing={dbEditing}+ onEditingChange={setDbEditing}+ onConfigSaved={() => void load()}+ />+ {loading ? (+ <div className="space-y-2">+ {[0, 1, 2].map((item) => (+ <div key={item} className="h-12 animate-pulse rounded-md bg-stone-100 dark:bg-stone-900" />))}</div>) : loadError ? (@@ -454,7 +663,7 @@ export default function DataSourcesPage({<p className="mx-auto mt-1 max-w-xl text-xs text-muted-foreground">{loadError}</p><Button size="sm" variant="outline" className="mt-4" onClick={() => void load()}>{messages.DATA_SOURCE_RETRY}</Button></div>- ) : visibleSources.length === 0 ? (+ ) : !hasRows ? (<div className="flex flex-col items-center gap-1 py-10 text-center"><h3 className="text-base font-semibold text-stone-900 dark:text-stone-100">{messages.DATA_SOURCE_EMPTY_TITLE}@@ -463,92 +672,170 @@ export default function DataSourcesPage({{messages.DATA_SOURCE_EMPTY_DESCRIPTION}</p></div>+ ) : !hasFilteredRows ? (+ <div className="flex flex-col items-center gap-1 py-10 text-center">+ <h3 className="text-base font-semibold text-stone-900 dark:text-stone-100">+ {messages.CONNECTOR_NO_MATCHES}+ </h3>+ </div>) : (- <div className="contents">- {visibleSources.map((s) => (- <div- key={s.id}- className="flex min-h-[168px] flex-col justify-between rounded-lg border border-stone-200 bg-stone-50/70 p-3 transition-colors hover:border-primary/40 hover:bg-primary/[0.03] dark:border-stone-800 dark:bg-stone-900/50 dark:hover:border-primary/50"- >- <div>- <div className="flex items-center gap-2">- <div className="flex h-9 w-9 items-center justify-center rounded-md border border-stone-200 bg-white dark:border-stone-700 dark:bg-stone-950">- <Image src={descriptors.find((d) => d.type === s.type)?.icon || "/images/connect.svg"} alt="" width={24} height={24} className="h-6 w-6 object-contain" />- </div>- <span className="text-sm font-medium text-stone-950 dark:text-stone-50">- {s.name}- </span>- <Badge variant="outline" className="text-[10px]">- {s.type}- </Badge>- <Badge variant="secondary" className="text-[10px]">- {s.environment || "production"}- </Badge>- {s.isDefault && (- <Badge className="text-[10px]">default</Badge>- )}- {s.hasSecret && (- <span- className="flex items-center gap-0.5 text-[10px] text-emerald-600 dark:text-emerald-400"- title={messages.DATA_SOURCE_CREDENTIALS_SET}- >- <ShieldCheck className="h-3 w-3" />- </span>- )}- </div>- <p className="mt-2 line-clamp-2 text-xs leading-5 text-muted-foreground">- {descriptors.find((d) => d.type === s.type)?.description || `${s.type} telemetry connector.`}- </p>- <div className="flex flex-wrap gap-1">- {parseSignals(s.signals).map((sig) => (- <Badge- key={sig}- variant="secondary"- className="text-[10px]"- >- {sig}- </Badge>- ))}- </div>- </div>- <div className="mt-3 flex items-center justify-end gap-1 border-t border-stone-200 pt-2 dark:border-stone-800">- <div className="flex items-center gap-1">- <Button- size="sm"- variant="ghost"- disabled={testingId === s.id}- onClick={() => testSource(s)}- >- <Wifi className="mr-1 h-3.5 w-3.5" />- {messages.DATA_SOURCE_TEST}- </Button>- <Button- size="icon"- variant="ghost"- title="Edit connector and signal routing"- aria-label={`Edit ${s.name} connector`}- onClick={() => setEditing(s)}- >- <Pencil className="h-3.5 w-3.5" />- </Button>- <Button- size="sm"- variant="ghost"- onClick={() => removeSource(s)}- >- <Trash2 className="h-3.5 w-3.5 text-error" />- </Button>- </div>- </div>- </div>- ))}+ <div className="overflow-x-auto rounded-md border border-stone-200 dark:border-stone-800">+ <Table>+ <TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">+ <TableRow className="text-xs">+ <TableHead className="h-8 pl-3">{messages.NAME}</TableHead>+ <TableHead className="h-8">{messages.DATA_SOURCE_FIELD_TYPE}</TableHead>+ <TableHead className="h-8">{messages.CONNECTOR_ENVIRONMENT}</TableHead>+ <TableHead className="h-8">{messages.DATA_SOURCE_FIELD_SIGNALS}</TableHead>+ <TableHead className="h-8 text-right">{messages.ACTIONS}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {filteredDatabases.map((config) => (+ <TableRow key={`clickhouse:${config.id}`} className="text-sm">+ <TableCell className="py-2 pl-3">+ <div className="flex min-w-0 items-center gap-2">+ <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded border border-stone-200 bg-white dark:border-stone-700 dark:bg-stone-950">+ <Image src={clickhouseDescriptor?.icon || "/images/connectors/clickhouse.svg"} alt="" width={16} height={16} className="h-4 w-4 object-contain" />+ </div>+ <div className="min-w-0">+ <p className="truncate font-medium text-stone-950 dark:text-stone-50">{config.name}</p>+ <p className="truncate text-[11px] text-muted-foreground">{config.host}:{config.port}</p>+ </div>+ </div>+ </TableCell>+ <TableCell className="py-2">+ <Badge variant="outline" className="text-[10px]">clickhouse</Badge>+ </TableCell>+ <TableCell className="py-2 text-xs text-muted-foreground">+ {config.environment || "production"}+ </TableCell>+ <TableCell className="py-2">+ <div className="flex flex-wrap gap-1">+ {(clickhouseDescriptor?.declaredSignals || ["traces", "logs", "metrics"]).map((sig) => (+ <Badge key={sig} variant="secondary" className="text-[10px]">{sig}</Badge>+ ))}+ </div>+ </TableCell>+ <TableCell className="py-2 text-right">+ <div className="flex items-center justify-end gap-1">+ <Button+ size="icon"+ variant="ghost"+ title={messages.DATA_SOURCE_TEST}+ aria-label={`${messages.DATA_SOURCE_TEST} ${config.name}`}+ disabled={testingId === `clickhouse:${config.id}`}+ onClick={() => void testClickhouse(config)}+ >+ <Wifi className="h-3.5 w-3.5" />+ </Button>+ <Button+ size="icon"+ variant="ghost"+ title={messages.DATA_SOURCE_EDIT_ACTION}+ aria-label={`${messages.DATA_SOURCE_EDIT_ACTION} ${config.name}`}+ disabled={!config.permissions?.canEdit}+ onClick={() => setDbEditing(config)}+ >+ <Pencil className="h-3.5 w-3.5" />+ </Button>+ <Button+ size="icon"+ variant="ghost"+ title={messages.DATA_SOURCE_DELETE_ACTION}+ aria-label={`${messages.DATA_SOURCE_DELETE_ACTION} ${config.name}`}+ disabled={!config.permissions?.canDelete}+ onClick={() => void removeClickhouse(config)}+ >+ <Trash2 className="h-3.5 w-3.5 text-error" />+ </Button>+ </div>+ </TableCell>+ </TableRow>+ ))}+ {filteredSources.map((s) => {+ const descriptor = descriptors.find((d) => d.type === s.type);+ return (+ <TableRow key={s.id} className="text-sm">+ <TableCell className="py-2 pl-3">+ <div className="flex min-w-0 items-center gap-2">+ <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded border border-stone-200 bg-white dark:border-stone-700 dark:bg-stone-950">+ <Image src={descriptor?.icon || "/images/connect.svg"} alt="" width={16} height={16} className="h-4 w-4 object-contain" />+ </div>+ <div className="min-w-0">+ <p className="truncate font-medium text-stone-950 dark:text-stone-50">{s.name}</p>+ {s.hasSecret ? (+ <span className="inline-flex items-center gap-0.5 text-[10px] text-emerald-600 dark:text-emerald-400" title={messages.DATA_SOURCE_CREDENTIALS_SET}>+ <ShieldCheck className="h-3 w-3" />+ {messages.DATA_SOURCE_CREDENTIALS_SET}+ </span>+ ) : null}+ </div>+ </div>+ </TableCell>+ <TableCell className="py-2">+ <Badge variant="outline" className="text-[10px]">{s.type}</Badge>+ </TableCell>+ <TableCell className="py-2 text-xs text-muted-foreground">+ {s.environment || "production"}+ </TableCell>+ <TableCell className="py-2">+ <div className="flex flex-wrap gap-1">+ {parseSignals(s.signals).map((sig) => (+ <Badge key={sig} variant="secondary" className="text-[10px]">{sig}</Badge>+ ))}+ {s.category === "memory" ? (+ <Badge variant="secondary" className="text-[10px]">{messages.CONNECTOR_CATEGORY_MEMORY}</Badge>+ ) : null}+ {s.isDefault ? (+ <Badge className="text-[10px]">default</Badge>+ ) : null}+ </div>+ </TableCell>+ <TableCell className="py-2 text-right">+ <div className="flex items-center justify-end gap-1">+ <Button+ size="icon"+ variant="ghost"+ title={messages.DATA_SOURCE_TEST}+ aria-label={`${messages.DATA_SOURCE_TEST} ${s.name}`}+ disabled={testingId === s.id}+ onClick={() => void testConnector(s)}+ >+ <Wifi className="h-3.5 w-3.5" />+ </Button>+ <Button+ size="icon"+ variant="ghost"+ title={messages.DATA_SOURCE_EDIT_ACTION}+ aria-label={`${messages.DATA_SOURCE_EDIT_ACTION} ${s.name}`}+ onClick={() => setEditing(s)}+ >+ <Pencil className="h-3.5 w-3.5" />+ </Button>+ <Button+ size="icon"+ variant="ghost"+ title={messages.DATA_SOURCE_DELETE_ACTION}+ aria-label={`${messages.DATA_SOURCE_DELETE_ACTION} ${s.name}`}+ onClick={() => removeSource(s)}+ >+ <Trash2 className="h-3.5 w-3.5 text-error" />+ </Button>+ </div>+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table></div>)}- </div></section>{editing && (<SourceFormDialog+ key={editing === "new" ? `new:${newType || ""}` : editing.id}source={editing === "new" ? null : editing}descriptors={descriptors}initialType={editing === "new" ? newType : undefined}@@ -557,7 +844,7 @@ export default function DataSourcesPage({bindingForSignal={bindingForSignal}onSetBinding={setBinding}bindings={bindings}- sources={visibleSources}+ sources={routingSources}databaseConfigs={databaseConfigs}environment={environment}onClose={() => {@@ -668,7 +955,7 @@ function SignalRoutingSection({const value = signalRoutingSelectValue(binding?.sourceId);const options = sources.filter((source) => parseSignals(source.signals).includes(signal));const hasOptions = environmentDatabases.length > 0 || options.length > 0;- const label = signal === "traces" ? messages.DATA_SOURCE_SIGNAL_TRACES : signal === "logs" ? messages.DATA_SOURCE_SIGNAL_LOGS : signal === "metrics" ? messages.DATA_SOURCE_SIGNAL_METRICS : "Intelligence";+ const label = signal === "traces" ? messages.DATA_SOURCE_SIGNAL_TRACES : signal === "logs" ? messages.DATA_SOURCE_SIGNAL_LOGS : signal === "metrics" ? messages.DATA_SOURCE_SIGNAL_METRICS : messages.DATA_SOURCE_SIGNAL_INTELLIGENCE;return (<div key={signal} className="space-y-1.5"><Label className="text-xs uppercase text-muted-foreground">{label}</Label>@@ -750,7 +1037,7 @@ function SignalRoutingEditor({);}-function SourceFormDialog({+export function SourceFormDialog({source,descriptors,initialType,@@ -785,8 +1072,24 @@ function SourceFormDialog({const [name, setName] = useState(source?.name || "");const [environment, setEnvironment] = useState(source?.environment || initialEnvironment || "production");const [environments, setEnvironments] = useState<string[]>(Array.from(new Set(["production", source?.environment, initialEnvironment].filter(Boolean) as string[])));- const externalDescriptors = useMemo(() => descriptors.filter((descriptor) => descriptor.type !== "clickhouse"), [descriptors]);- const [type, setType] = useState(source?.type || initialType || externalDescriptors[0]?.type || "");+ const [type, setType] = useState(source?.type || initialType || "");+ const pickerGroups = useMemo(() => {+ const groups = new Map<string, TypeDescriptor[]>();+ for (const descriptor of descriptors) {+ const key = descriptor.category || "datasource";+ const group = groups.get(key) || [];+ group.push(descriptor);+ groups.set(key, group);+ }+ return Array.from(groups, ([key, items]) => ({+ key,+ label:+ key === "memory"+ ? messages.CONNECTOR_CATEGORY_MEMORY+ : messages.CONNECTOR_CATEGORY_DATASOURCE,+ items,+ }));+ }, [descriptors, messages.CONNECTOR_CATEGORY_DATASOURCE, messages.CONNECTOR_CATEGORY_MEMORY]);const clickHouseFields = useMemo<FieldDef[]>(() => [{ key: "username", label: messages.DB_CONFIG_FIELD_USERNAME, kind: "text", group: "settings", placeholder: "default" },{ key: "host", label: messages.DB_CONFIG_FIELD_HOST, kind: "text", group: "settings", placeholder: "clickhouse.example.com" },@@ -801,6 +1104,7 @@ function SourceFormDialog({const [isDefault, setIsDefault] = useState(!!source?.isDefault);const [values, setValues] = useState<Record<string, string | boolean>>({});const [saving, setSaving] = useState(false);+ const [testing, setTesting] = useState(false);useEffect(() => {fetch("/api/project/environment")@@ -847,6 +1151,8 @@ function SourceFormDialog({(f.key === "authType" || f.group === "credentials") &&isFieldVisible(f, { ...values }));+ const activeDescriptor = descriptors.find((d) => d.type === type);+ const setupGuide = messages.DATA_SOURCE_SETUP_GUIDES[type];const submit = async () => {if (!name.trim()) {@@ -899,6 +1205,7 @@ function SourceFormDialog({environment: environment.trim().toLowerCase() || "production",settings,isDefault,+ category: activeDescriptor?.category || "datasource",};if (Object.keys(credentials).length) payload.credentials = credentials;if (isEdit) {@@ -946,8 +1253,27 @@ function SourceFormDialog({}};- const activeDescriptor = descriptors.find((d) => d.type === type);- const setupGuide = messages.DATA_SOURCE_SETUP_GUIDES[type];+ const testConnection = async () => {+ if (!source?.id) {+ toast.error(messages.DATA_SOURCE_TEST_UNSAVED, { id: "ds-test" });+ return;+ }+ setTesting(true);+ toast.loading(messages.DATA_SOURCE_TESTING, { id: "ds-test" });+ try {+ const res = await jsonFetch(`/api/connectors/${source.id}/health`, {+ method: "POST",+ });+ reportConnectorHealth(messages, descriptors, source.type, res);+ } catch (e: unknown) {+ toast.error(+ e instanceof Error ? e.message : messages.DATA_SOURCE_SAVE_FAILED,+ { id: "ds-test" }+ );+ } finally {+ setTesting(false);+ }+ };return (<Dialog open onOpenChange={(o) => !o && onClose()}>@@ -973,14 +1299,14 @@ function SourceFormDialog({<div className="space-y-1.5"><Label className="text-xs">{messages.DATA_SOURCE_FIELD_TYPE}</Label><Select- value={type}+ value={type || undefined}onValueChange={(nextType) => {setType(nextType);}}disabled={isEdit}><SelectTrigger className="h-auto min-h-14 items-center gap-2 overflow-hidden border-stone-300 bg-white py-2.5 text-left text-stone-950 [&>span]:min-w-0 [&>span]:flex-1 [&>span]:line-clamp-none dark:border-stone-700 dark:bg-stone-900 dark:text-stone-50">- <SelectValue placeholder="Select a connector">+ <SelectValue placeholder={messages.CONNECTOR_TYPE_PLACEHOLDER}>{activeDescriptor ? (<div className="flex min-w-0 items-center gap-2.5"><div className="flex h-8 w-8 shrink-0 items-center justify-center rounded border border-stone-200 bg-white dark:border-stone-700 dark:bg-stone-950">@@ -994,28 +1320,35 @@ function SourceFormDialog({) : undefined}</SelectValue></SelectTrigger>- <SelectContent className="grid max-h-96 min-w-[var(--radix-select-trigger-width)] grid-cols-2 items-stretch gap-2 p-2 sm:min-w-[680px]">- {descriptors.map((d) => (- <SelectItem key={d.type} value={d.type} className="min-h-[72px] items-start py-2 pl-2 pr-8">- <div className="flex items-start gap-3">- <div className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded border border-stone-200 bg-white dark:border-stone-700 dark:bg-stone-950">+ <SelectContent className="max-h-96 min-w-[var(--radix-select-trigger-width)] [&_[data-radix-select-viewport]]:h-auto [&_[data-radix-select-viewport]]:max-h-80">+ {pickerGroups.map((group) => (+ <SelectGroup key={group.key}>+ <SelectLabel className="pl-2 text-[11px] uppercase tracking-wide text-muted-foreground">+ {group.label}+ </SelectLabel>+ {group.items.map((d) => (+ <SelectItem key={d.type} value={d.type} className="items-center py-2 pl-2 pr-8">+ <div className="flex items-center gap-3">+ <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded border border-stone-200 bg-white dark:border-stone-700 dark:bg-stone-950"><Image src={d.icon || "/images/connect.svg"} alt="" width={18} height={18} className="h-[18px] w-[18px] object-contain" /></div><div className="min-w-0"><p className="font-medium">{d.displayName}</p>- <p className="mt-0.5 line-clamp-2 max-w-[220px] whitespace-normal text-[10px] leading-4 text-muted-foreground">{d.description || `${d.displayName} telemetry connector.`}</p>+ <p className="truncate text-[10px] text-muted-foreground">{d.type}</p></div></div></SelectItem>+ ))}+ </SelectGroup>))}</SelectContent></Select>{isEdit && <p className="text-[11px] text-muted-foreground">{messages.DATA_SOURCE_TYPE_LOCKED}</p>}</div>- {activeDescriptor && (+ {activeDescriptor && (activeDescriptor.declaredSignals || []).length > 0 && (<div className="mt-3 flex flex-wrap items-center gap-1.5"><span className="mr-1 text-[11px] text-muted-foreground">{messages.DATA_SOURCE_SIGNALS_SECTION}:</span>- {activeDescriptor.declaredSignals.map((sig) => (+ {(activeDescriptor.declaredSignals || []).map((sig) => (<Badge key={sig} variant="secondary" className="text-[10px]">{sig}</Badge>))}</div>@@ -1118,7 +1451,7 @@ function SourceFormDialog({</section>)}- {showRouting && source && bindingForSignal && onSetBinding && (+ {showRouting && source && activeDescriptor?.category !== "memory" && bindingForSignal && onSetBinding && (<SignalRoutingEditorsources={sources || []}databaseConfigs={databaseConfigs || []}@@ -1129,21 +1462,34 @@ function SourceFormDialog({/>)}+ {activeDescriptor?.category !== "memory" && (<div className="flex items-center justify-between rounded-md border border-stone-200 px-3 py-2 dark:border-stone-800"><Label className="text-xs">{messages.DATA_SOURCE_FIELD_DEFAULT}</Label><Switch checked={isDefault} onCheckedChange={setIsDefault} /></div>+ )}</div>- <DialogFooter>- <Button variant="outline" onClick={onClose} disabled={saving}>+ <DialogFooter className="gap-2 sm:justify-between">+ <Button+ variant="outline"+ onClick={() => void testConnection()}+ disabled={saving || testing || !isEdit}+ title={!isEdit ? messages.DATA_SOURCE_TEST_UNSAVED : undefined}+ >+ <Wifi className="mr-1.5 h-3.5 w-3.5" />+ {testing ? messages.DATA_SOURCE_TESTING : messages.DATA_SOURCE_TEST}+ </Button>+ <div className="flex gap-2">+ <Button variant="outline" onClick={onClose} disabled={saving || testing}>{messages.CANCEL}</Button>- <Button onClick={submit} disabled={saving}>+ <Button onClick={submit} disabled={saving || testing || !type}>{messages.SAVE}</Button>+ </div></DialogFooter></DialogContent></Dialog>diff --git a/src/client/src/components/ui/alert-dialog.tsx b/src/client/src/components/ui/alert-dialog.tsxindex 2a7b548f..ca108df1 100644--- a/src/client/src/components/ui/alert-dialog.tsx+++ b/src/client/src/components/ui/alert-dialog.tsx@@ -3,6 +3,8 @@import * as React from "react"import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"+import { type VariantProps } from "class-variance-authority"+import { cn } from "@/lib/utils"import { buttonVariants } from "@/components/ui/button"@@ -65,7 +67,7 @@ const AlertDialogFooter = ({}: React.HTMLAttributes<HTMLDivElement>) => (<divclassName={cn(- "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",+ "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",className)}{...props}@@ -100,11 +102,12 @@ AlertDialogDescription.displayName =const AlertDialogAction = React.forwardRef<React.ElementRef<typeof AlertDialogPrimitive.Action>,- React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>->(({ className, ...props }, ref) => (+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action> &+ VariantProps<typeof buttonVariants>+>(({ className, variant, size, ...props }, ref) => (<AlertDialogPrimitive.Actionref={ref}- className={cn(buttonVariants(), className)}+ className={cn(buttonVariants({ variant, size }), className)}{...props}/>))@@ -112,15 +115,12 @@ AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayNameconst AlertDialogCancel = React.forwardRef<React.ElementRef<typeof AlertDialogPrimitive.Cancel>,- React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>->(({ className, ...props }, ref) => (+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel> &+ VariantProps<typeof buttonVariants>+>(({ className, variant = "outline", size, ...props }, ref) => (<AlertDialogPrimitive.Cancelref={ref}- className={cn(- buttonVariants({ variant: "outline" }),- "mt-2 sm:mt-0",- className- )}+ className={cn(buttonVariants({ variant, size }), className)}{...props}/>))diff --git a/src/client/src/constants/events.ts b/src/client/src/constants/events.tsindex c8a0d405..e7a9bec9 100644--- a/src/client/src/constants/events.ts+++ b/src/client/src/constants/events.ts@@ -136,6 +136,7 @@ export const CLIENT_EVENTS = {PROMPT_HUB_DETAIL_PAGE_VISITED: "PROMPT_HUB_DETAIL_PAGE_VISITED",OTTER_CHAT_PAGE_VISITED: "OTTER_CHAT_PAGE_VISITED",VAULT_PAGE_VISITED: "VAULT_PAGE_VISITED",+ MEMORY_PAGE_VISITED: "MEMORY_PAGE_VISITED",OPENGROUND_PAGE_VISITED: "OPENGROUND_PAGE_VISITED",OPENGROUND_NEW_PAGE_VISITED: "OPENGROUND_NEW_PAGE_VISITED",OPENGROUND_DETAIL_PAGE_VISITED: "OPENGROUND_DETAIL_PAGE_VISITED",diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.tsindex 74ffbf4b..133ec41e 100644--- a/src/client/src/constants/messages/en.ts+++ b/src/client/src/constants/messages/en.ts@@ -743,6 +743,7 @@ export const RECALCULATE_COST_REQUEST_FAILED = "Failed to recalculate cost";export const FEATURE_OPENGROUND = "Openground";export const FEATURE_PROMPTS = "Prompt Hub";export const FEATURE_VAULT = "Vault";+export const FEATURE_MEMORY = "Memory";export const FEATURE_FLEET_HUB = "Fleet Hub";export const FLEET_HUB_BACK_TO_LIST = "Back to Fleet Hub";export const FEATURE_AGENTS = "Agents";@@ -1849,6 +1850,7 @@ export const NO_DASH = "-";// Chatexport const CHAT_TITLE = "Otter";+export const CHAT_ASK_OTTER = "Ask Otter";export const CHAT_DESCRIPTION = "Ask questions about your observability data using natural language";export const CHAT_SETTINGS_TITLE = "Chat Settings";export const CHAT_SETTINGS_DESCRIPTION = "Configure the AI provider for the chat feature";@@ -2147,6 +2149,21 @@ export const NO_CONNECTED_CONNECTORS = "No connectors are configured for the actexport const CONNECTOR_CATALOG = "Connector catalog";export const CONNECTOR_CATALOG_DESCRIPTION = "Browse connector types and add more integrations to the active project.";export const ADD_CONNECTOR = "Add connector";+export const CONNECTOR_SEARCH_PLACEHOLDER = "Search connectors";+export const CONNECTOR_NO_MATCHES = "No connectors match your search.";+export const CONNECTOR_FILTER_ALL_TYPES = "All types";+export const CONNECTOR_FILTER_ALL_CATEGORIES = "All categories";+export const CONNECTOR_FILTER_ALL_SIGNALS = "All signals";+export const CONNECTOR_FILTER_TYPE = "Type";+export const CONNECTOR_FILTER_CATEGORY = "Category";+export const CONNECTOR_FILTER_SIGNAL = "Signal";+export const CONNECTOR_TYPE_PLACEHOLDER = "Select a connector type";+export const CONNECTOR_CATEGORY_DATASOURCE = "Data sources";+export const CONNECTOR_CATEGORY_MEMORY = "Memory";+export const DATA_SOURCE_TEST_UNSAVED =+ "Save the connector before testing the connection.";+export const DATA_SOURCE_EDIT_ACTION = "Edit connector";+export const DATA_SOURCE_DELETE_ACTION = "Delete connector";export const CONNECTOR_PREMIUM = "Premium";export const CONNECTOR_LOCKED = "Requires a paid plan or license";export const CONNECTOR_LOCKED_ACTION = "License required";@@ -2156,6 +2173,237 @@ export const CONNECTOR_ENVIRONMENT = "Environment";export const CONNECTOR_ENVIRONMENT_PLACEHOLDER = "production";export const CONNECTOR_ENVIRONMENT_DESCRIPTION ="Keep connector assignments separate for production, staging, and other environments.";+export const MEMORY_CONNECTOR_NAME_REQUIRED = "A memory connector name is required.";+export const MEMORY_CONNECTOR_NAME_TAKEN = (name: string, environment: string) =>+ `A memory connector named "${name}" already exists in the ${environment} environment. Choose a different name.`;+export const MEMORY_CONNECTOR_TYPE_UNKNOWN = (type: string) =>+ `Unknown memory connector type "${type}".`;+export const MEMORY_CONNECTOR_NO_PROJECT = "No current project is selected.";+export const MEMORY_CONNECTOR_NOT_FOUND =+ "Memory connector not found in the current project.";+export const MEMORY_CONNECTOR_CONTENT_REQUIRED =+ "Memory content or messages are required.";+export const MEMORY_CONNECTOR_QUERY_REQUIRED = "A memory search query is required.";+export const MEMORY_CONNECTOR_SESSION_REQUIRED =+ "A session id is required for this memory connector.";+export const MEMORY_CONNECTOR_FILTER_REQUIRED =+ "A user, agent, or session is required to list memories.";+export const MEMORY_CONNECTOR_INLINE_SECRET_REQUIRED =+ "This memory connector must store its API key on the connector. Edit the connector and save the API key again.";+export const MEMORY_CONNECTOR_CLAUDE_DESCRIPTION =+ "Browse and edit memories in Anthropic Claude memory stores.";+export const MEMORY_CONNECTOR_MEM0_DESCRIPTION =+ "Store and search long-term agent memories with Mem0.";+export const MEMORY_CONNECTOR_ZEP_DESCRIPTION =+ "Store and search session memory and a knowledge graph with Zep.";+export const MEMORY_CONNECTOR_FIELD_ORG_ID = "Mem0 organization ID";+export const MEMORY_CONNECTOR_FIELD_PROJECT_ID = "Mem0 project ID";+export const MEMORY_CONNECTOR_FIELD_STORE_ID = "Memory store";+export const MEMORY_CONNECTOR_AUTH_HELP_CLAUDE =+ "Use an Anthropic API key. Memory store calls send x-api-key with the agent-memory beta header.";+export const MEMORY_CONNECTOR_AUTH_HELP_MEM0 =+ "Use a Mem0 Platform API key. Self-hosted Mem0 can use a custom endpoint with the same Token authentication.";+export const MEMORY_CONNECTOR_AUTH_HELP_ZEP =+ "Use a Zep Cloud API key. Self-hosted Zep can use a custom endpoint with the same Api-Key authentication.";+export const MEMORY_CONNECTOR_SETUP_CLAUDE_SUMMARY =+ "Claude memory stores keep agent notes across Managed Agents sessions.";+export const MEMORY_CONNECTOR_SETUP_MEM0_SUMMARY =+ "Mem0 stores long-term memories scoped by user, run, or agent.";+export const MEMORY_CONNECTOR_SETUP_ZEP_SUMMARY =+ "Zep stores session memory and a knowledge graph for agents.";+export const MEMORY_PAGE_DESCRIPTION =+ "Browse stored agent memories and ask Otter to search them.";+export const MEMORY_TOTAL = "Total memories";+export const MEMORY_CONNECTIONS = "Connections";+export const MEMORY_TEMPORAL = "Temporal";+export const MEMORY_PROFILE = "Profile";+export const MEMORY_SUMMARY = "Summary";+export const MEMORY_SEARCH_PLACEHOLDER = "Search memories…";+export const MEMORY_ASK_TITLE = "Ask Otter";+export const MEMORY_ASK_EMPTY =+ "Ask Otter about stored facts, users, or what to remember.";+export const MEMORY_ASK_PLACEHOLDER = "Ask anything about your memories…";+export const MEMORY_ASK_HINT =+ "Otter searches this connector and answers here.";+export const MEMORY_ASK_SEND = "Ask Otter";+export const MEMORY_ASK_OTTER_PROMPT =+ "Use add_memory / update_memory / delete_memory only when asked to remember, change, or forget something.";+export const MEMORY_ASK_TOOLS_PROMPT =+ "Memory page: fetch data with list_memories or search_memories (connector API). Prefer list_memories for inventory; search_memories for a specific fact. Do not invent memories.";+export const MEMORY_ASK_FALLBACK_PROMPT =+ "Memory page: this connector has no list/search API. Answer briefly from chat context only; say when you lack connector data.";+export const MEMORY_ASK_REQUIRED_FILTERS = (filters: string) =>+ `Pass these tool args when calling memory tools: ${filters}.`;+export const MEMORY_ASK_SELECTED_CHIP = (summary: string) => `Selected: ${summary}`;+export const MEMORY_ASK_SELECTED_PROMPT = (id: string, excerpt: string) =>+ excerpt+ ? `Selected memory_id=${id}: ${excerpt}`+ : `Selected memory_id=${id}.`;+export const MEMORY_SPLIT_RESIZE = "Resize memories and Ask Otter panels";+export const MEMORY_REFRESH = "Load";+export const MEMORY_GRAPH_TITLE = "Memory graph";+export const MEMORY_LIST_TITLE = "Memories";+export const MEMORY_PAGE_OF = (current: number, total: number) =>+ `${current} of ${total}`;+export const MEMORY_PAGE_PREVIOUS = "Previous page";+export const MEMORY_PAGE_NEXT = "Next page";+export const MEMORY_CONNECTOR_LABEL = "Memory connector";+export const MEMORY_USER_FILTER = "User";+export const MEMORY_SESSION_FILTER = "Session";+export const MEMORY_RUN_FILTER = "Run";+export const MEMORY_AGENT_FILTER = "Agent";+export const MEMORY_FILTER_ALL = "All";+export const MEMORY_FILTER_USE_VALUE = (value: string) => `Use “${value}”`;+export const MEMORY_FILTER_CUSTOM_HINT = "Type a value and press Enter.";+export const MEMORY_FILTER_PLACEHOLDER = "Select";+export const MEMORY_SESSION_REQUIRED_HINT =+ "Select a session to load memories from this connector.";+export const MEMORY_FILTER_REQUIRED_HINT =+ "Select a user, session, or agent to load memories.";+export const MEMORY_FILTER_EMPTY =+ "This connector has no users or sessions yet.";+export const MEMORY_GRAPH_EMPTY = "No graph data to display.";+export const MEMORY_EMPTY_CONNECTORS =+ "Add a memory connector to browse and ask Otter about stored memories.";+export const MEMORY_EMPTY_CONNECTORS_ACTION = "Add memory connector";+export const MEMORY_EMPTY_LIST = "No memories matched these filters.";+export const MEMORY_NO_MATCHES = "No memories match this search.";+export const MEMORY_LOAD_FAILED = "Failed to load memories.";+export const MEMORY_UNAVAILABLE_TITLE = "Memories are unavailable";+export const MEMORY_UNAVAILABLE_DESCRIPTION =+ "We couldn't load memories from this connector. Check the connector and try again.";+export const MEMORY_AUTH_FAILED_HINT =+ "This connector rejected the API key. Edit the connector, save a valid key, and try again.";+export const MEMORY_RETRY = "Retry";+export const MEMORY_UNKNOWN_USER = "Unknown user";+export const MEMORY_NO_DATE = "—";+export const MEMORY_LEGEND = "Legend";+export const MEMORY_GRAPH_ENTITY_TYPES = "Entity types";+export const MEMORY_GRAPH_SEARCH = "Search graph";+export const MEMORY_GRAPH_TYPE_ALL = "All";+export const MEMORY_GRAPH_ZOOM_IN = "Zoom in";+export const MEMORY_GRAPH_ZOOM_OUT = "Zoom out";+export const MEMORY_GRAPH_TYPE_FILTER = "Entity type";+export const MEMORY_ENTITY = "Entity";+export const MEMORY_EVENT = "Event";+export const MEMORY_LOCATION = "Location";+export const MEMORY_OBJECT = "Object";+export const MEMORY_PREFERENCE = "Preference";+export const MEMORY_TOPIC = "Topic";+export const MEMORY_USER = "User";+export const MEMORY_INVALID_FILTER = "A memory filter value is invalid.";+export const MEMORY_INVALID_LIMIT = "Limit must be a number between 1 and 100.";+export const MEMORY_INVALID_JSON = "Request body must be valid JSON.";+export const MEMORY_FEEDBACK_INVALID =+ "Feedback must be positive, negative, very negative, or empty to clear.";+export const MEMORY_FEEDBACK_REASON_TOO_LONG =+ "Feedback reason must be 1000 characters or fewer.";+export const MEMORY_DETAIL_TITLE = "Memory";+export const MEMORY_DETAIL_NOT_FOUND = "This memory could not be found.";+export const MEMORY_DETAIL_LOAD_FAILED = "Failed to load memory details.";+export const MEMORY_DETAIL_UNSUPPORTED =+ "This connector cannot fetch a memory by id. Showing the listed record.";+export const MEMORY_DETAIL_CONTENT = "Content";+export const MEMORY_DETAIL_MEMORY = "Memory";+export const MEMORY_DETAIL_METADATA = "Metadata";+export const MEMORY_DETAIL_ID = "ID";+export const MEMORY_DETAIL_KIND = "Kind";+export const MEMORY_DETAIL_USER = "User";+export const MEMORY_DETAIL_SESSION = "Session";+export const MEMORY_DETAIL_AGENT = "Agent";+export const MEMORY_DETAIL_CREATED = "Created";+export const MEMORY_DETAIL_UPDATED = "Updated";+export const MEMORY_DETAIL_SCORE = "Score";+export const MEMORY_DETAIL_CONNECTOR = "Connector";+export const MEMORY_DETAIL_CATEGORIES = "Categories";+export const MEMORY_DETAIL_TAB_DETAILS = "Details";+export const MEMORY_DETAIL_TAB_INPUT = "Input";+export const MEMORY_DETAIL_TAB_CHANGELOG = "Changelog";+export const MEMORY_DETAIL_PREVIOUS = "Previous memory";+export const MEMORY_DETAIL_NEXT = "Next memory";+export const MEMORY_DETAIL_COPY_ID = "Copy memory id";+export const MEMORY_DETAIL_EXPIRATION = "Expires";+export const MEMORY_DETAIL_APP = "App";+export const MEMORY_DETAIL_LIFECYCLE = "Lifecycle";+export const MEMORY_DETAIL_SYNTHESIZED = "Synthesized";+export const MEMORY_DETAIL_STRUCTURED = "Structured attributes";+export const MEMORY_DETAIL_INPUT_EMPTY = "No source messages for this memory.";+export const MEMORY_DETAIL_CHANGELOG_EMPTY = "No changelog for this memory.";+export const MEMORY_DETAIL_EVENT_ADDED = "Added";+export const MEMORY_DETAIL_EVENT_UPDATED = "Updated";+export const MEMORY_DETAIL_EVENT_DELETED = "Deleted";+export const MEMORY_DETAIL_OLD_MEMORY = "Previous";+export const MEMORY_DETAIL_NEW_MEMORY = "Updated to";+export const MEMORY_DETAIL_YES = "Yes";+export const MEMORY_DETAIL_NO = "No";+export const MEMORY_DETAIL_ITEM = (index: number) => `#${index}`;+export const MEMORY_DETAIL_FEEDBACK = "Feedback";+export const MEMORY_DETAIL_FEEDBACK_HELP =+ "Tell the memory provider whether this memory is useful.";+export const MEMORY_DETAIL_FEEDBACK_POSITIVE = "Positive";+export const MEMORY_DETAIL_FEEDBACK_NEGATIVE = "Negative";+export const MEMORY_DETAIL_FEEDBACK_VERY_NEGATIVE = "Very negative";+export const MEMORY_DETAIL_FEEDBACK_REASON = "Reason";+export const MEMORY_DETAIL_FEEDBACK_REASON_PLACEHOLDER =+ "Why is this memory useful or not?";+export const MEMORY_DETAIL_FEEDBACK_SUBMIT = "Save reason";+export const MEMORY_DETAIL_FEEDBACK_CLEAR = "Clear feedback";+export const MEMORY_DETAIL_FEEDBACK_SAVED = "Feedback saved";+export const MEMORY_DETAIL_FEEDBACK_CLEARED = "Feedback cleared";+export const MEMORY_DETAIL_FEEDBACK_SAVE_FAILED = "Failed to save memory feedback.";+export const MEMORY_DETAIL_FEEDBACK_UNSUPPORTED =+ "This connector does not support memory feedback.";+export const MEMORY_ADD = "Add memory";+export const MEMORY_ADD_TITLE = "Add memory";+export const MEMORY_ADD_DESCRIPTION =+ "Write a fact to the selected memory connector.";+export const MEMORY_ADD_PLACEHOLDER = "What should this connector remember?";+export const MEMORY_ADD_SAVE = "Save memory";+export const MEMORY_ADD_SAVED = "Memory saved";+export const MEMORY_ADD_FAILED = "Failed to add memory.";+export const MEMORY_ADD_UNSUPPORTED =+ "This connector does not support adding memories.";+export const MEMORY_COPY = "Copy to connector";+export const MEMORY_COPY_TITLE = "Copy memories";+export const MEMORY_COPY_DESCRIPTION =+ "Copy the loaded memories into another connector. OpenLIT stores a link back to the source memory.";+export const MEMORY_COPY_TARGET = "Destination connector";+export const MEMORY_COPY_SAVE = "Copy memories";+export const MEMORY_COPY_SAVED = (copied: number, target: string) =>+ copied === 1+ ? `Copied 1 memory to ${target}.`+ : `Copied ${copied} memories to ${target}.`;+export const MEMORY_COPY_PARTIAL = (copied: number, failed: number) =>+ `Copied ${copied} ${copied === 1 ? "memory" : "memories"}, ${failed} failed.`;+export const MEMORY_COPY_FAILED = "Failed to copy memories.";+export const MEMORY_COPY_EMPTY = "Select memories to copy, or load a list first.";+export const MEMORY_COPY_SAME_CONNECTOR =+ "Choose a different destination connector.";+export const MEMORY_COPY_TOO_MANY =+ "Copy up to 50 memories at a time.";+export const MEMORY_COPY_NO_TARGETS =+ "Add another memory connector that can store memories to copy into.";+export const MEMORY_COPY_SOURCE = "Copied from";+export const MEMORY_COPY_OPEN_SOURCE = "Open source memory";+export const MEMORY_EDIT = "Edit";+export const MEMORY_EDIT_TITLE = "Edit memory";+export const MEMORY_EDIT_SAVE = "Save changes";+export const MEMORY_EDIT_SAVED = "Memory updated";+export const MEMORY_EDIT_FAILED = "Failed to update memory.";+export const MEMORY_EDIT_UNSUPPORTED =+ "This connector does not support updating memories.";+export const MEMORY_DELETE = "Delete";+export const MEMORY_DELETE_TITLE = "Delete this memory?";+export const MEMORY_DELETE_DESCRIPTION =+ "This removes the memory from the connected store. This cannot be undone.";+export const MEMORY_DELETE_CONFIRM = "Delete memory";+export const MEMORY_DELETED = "Memory deleted";+export const MEMORY_DELETE_FAILED = "Failed to delete memory.";+export const MEMORY_DELETE_UNSUPPORTED =+ "This connector does not support deleting memories.";+export const MEMORY_CANCEL = "Cancel";+export const MEMORY_CONTENT_TOO_LONG = "Memory content is too long.";+export const MEMORY_INVALID_METADATA = "Memory metadata must be a JSON object.";export const DATA_SOURCE_BUILTIN_TITLE = "ClickHouse connector";export const DATA_SOURCE_BUILTIN_DERIVED ="ClickHouse is optional for telemetry viewing. It becomes the execution target for evaluations, AI analysis, costing, and other features that require OpenLIT-managed storage.";@@ -2170,6 +2418,7 @@ export const DATA_SOURCE_SIGNAL_ROUTING_DIALOG_FOOTER = (name: string, environmeexport const DATA_SOURCE_SIGNAL_TRACES = "Traces";export const DATA_SOURCE_SIGNAL_LOGS = "Logs";export const DATA_SOURCE_SIGNAL_METRICS = "Metrics";+export const DATA_SOURCE_SIGNAL_INTELLIGENCE = "Intelligence";export const DATA_SOURCE_SIGNAL_BUILTIN_OPTION = "ClickHouse connector";export const DATA_SOURCE_SOURCES_TITLE = "External sources";export const DATA_SOURCE_SOURCES_DESCRIPTION =@@ -2204,6 +2453,21 @@ export const DATA_SOURCE_SETUP_GUIDES: Record<string, { summary: string; steps:steps: ["Enter the Jaeger Query Service URL, commonly port 16686.", "Use the configured Basic/Bearer credentials if the query service is protected.", "Ensure the OpenLIT server can reach the query service over the network."],docsUrl: "https://www.jaegertracing.io/docs/1.24/apis/",},+ claude: {+ summary: "Connect OpenLIT to Claude memory stores.",+ steps: ["Create an Anthropic API key with access to Memory Stores.", "Paste the API key into the credentials field.", "Save the connector, then pick a memory store when browsing or adding memories."],+ docsUrl: "https://platform.claude.com/docs/en/managed-agents/memory",+ },+ mem0: {+ summary: "Connect OpenLIT to Mem0 for long-term agent memory.",+ steps: ["Create a Mem0 Platform API key, or point the endpoint at a self-hosted Mem0 service.", "Paste the API key into the credentials field. It is stored in the OpenLIT vault.", "Optionally set organization and project IDs for a Mem0 Platform workspace, then test the connection."],+ docsUrl: "https://docs.mem0.ai/api-reference",+ },+ zep: {+ summary: "Connect OpenLIT to Zep for session memory and graph search.",+ steps: ["Create a Zep Cloud API key, or point the endpoint at a self-hosted Zep service.", "Paste the API key into the credentials field. It is stored in the OpenLIT vault.", "Save the connector, then test the connection before using it from agents."],+ docsUrl: "https://help.getzep.com/sdk-reference",+ },};export const DATA_SOURCE_EMPTY_TITLE = "No external sources yet";export const DATA_SOURCE_EMPTY_DESCRIPTION =diff --git a/src/client/src/constants/sidebar.tsx b/src/client/src/constants/sidebar.tsxindex 3ba2d0b7..17c4ae02 100644--- a/src/client/src/constants/sidebar.tsx+++ b/src/client/src/constants/sidebar.tsx@@ -10,6 +10,7 @@ import {BookText,Bot,Boxes,+ BrainCircuit,Building2,CircleDollarSign,Component,@@ -103,6 +104,12 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [link: "/context",type: "action",},+ {+ icon: <BrainCircuit className={ICON_CLASSES} />,+ text: m.FEATURE_MEMORY,+ link: "/memory",+ type: "action",+ },{icon: <SlidersHorizontal className={ICON_CLASSES} />,text: "Rule Engine",diff --git a/src/client/src/lib/access/memory-route.ts b/src/client/src/lib/access/memory-route.tsnew file mode 100644index 00000000..c0e7a0c0--- /dev/null+++ b/src/client/src/lib/access/memory-route.ts@@ -0,0 +1,38 @@+/**+ * CE fallback for memory route protection and audit hooks.+ * Enterprise replaces this neutral module through its path aliases.+ *+ * Library callers (Otter chat tools) use requireMemoryAccess /+ * recordMemoryMutationAudit because they do not go through HTTP wrappers.+ */+export type MemoryAction = "read" | "create" | "update" | "delete" | "feedback";++export type MemoryMutationAuditInput = {+ action: Exclude<MemoryAction, "read">;+ targetId?: string;+ connectorId?: string;+ userId?: string;+ sessionId?: string;+ agentId?: string;+ contentLength?: number;+ rating?: unknown;+ hasReason?: boolean;+ source?: string;+};++export function withMemoryAccess<THandler>(+ _action: MemoryAction,+ handler: THandler+): THandler {+ return handler;+}++export function withMemoryAudit<THandler>(handler: THandler): THandler {+ return handler;+}++export async function requireMemoryAccess(_action: MemoryAction): Promise<void> {}++export async function recordMemoryMutationAudit(+ _input: MemoryMutationAuditInput+): Promise<void> {}diff --git a/src/client/src/lib/audit/route.ts b/src/client/src/lib/audit/route.tsindex 9c1dae09..23f3ff89 100644--- a/src/client/src/lib/audit/route.ts+++ b/src/client/src/lib/audit/route.ts@@ -3,8 +3,17 @@ type RouteHandler = (context: any) => Promise<Response> | Response;+export type DirectAuditEvent = {+ action: string;+ targetType?: string;+ targetId?: string;+ metadata?: Record<string, unknown>;+};+export function withAudit<THandler extends RouteHandler>(handler: THandler): THandler {return handler;}++export async function recordAuditEvent(_event: DirectAuditEvent): Promise<void> {}diff --git a/src/client/src/lib/platform/chat/schema-context.ts b/src/client/src/lib/platform/chat/schema-context.tsindex ad5a6f07..cb3e2ca9 100644--- a/src/client/src/lib/platform/chat/schema-context.ts+++ b/src/client/src/lib/platform/chat/schema-context.ts@@ -2,7 +2,7 @@ export function getChatSystemPrompt(): string {return `You are an AI assistant for OpenLIT, an OpenTelemetry-native observability platform. You have two capabilities:1. **Data Queries**: Convert natural language questions into ClickHouse SQL queries to analyze observability data (traces, metrics, costs, tokens, etc.)-2. **Platform Management**: Create and manage platform resources using the available tools — rules, alerts, contexts, prompts, vault secrets, custom models, and trace analysis.+2. **Platform Management**: Create and manage platform resources using the available tools — rules, alerts, contexts, prompts, vault secrets, custom models, memory, and trace analysis.3. **Connector-routed telemetry**: Use the query_telemetry tool for current traces, logs, or metrics. It reads from the connector selected by the project's signal routing, so do not use ClickHouse SQL for telemetry when an external source is configured.When the user asks which connector, data source, database, or backend is being used, you MUST call get_telemetry_routing first and answer from its returned routing values. Never infer the connector from the SQL schema, the ClickHouse table names, or the fact that SQL is available. When the user asks a question about current traces, logs, or metrics, use query_telemetry. Use SQL only for ClickHouse-backed platform data and derived analytics that require SQL. When the user asks to create or manage a resource, use the appropriate tool. If unclear, ask for clarification.@@ -14,6 +14,7 @@ When the user asks which connector, data source, database, or backend is being u**Context** — create_context, update_context, delete_context, list_contexts**Prompt Hub** — create_prompt, get_prompt, update_prompt_version, delete_prompt, list_prompts**Vault** — create_vault_secret, update_vault_secret, delete_vault_secret, list_vault_secrets+**Memory** — list_memories, search_memories, add_memory, update_memory, delete_memory**Models** — create_custom_model, update_custom_model, delete_custom_model, list_custom_models**Trace analysis** — analyze_trace, get_trace_analysis, analyze_trace_batch, analyze_traces_by_attribute**Telemetry** — get_telemetry_routing (reports the active connector per signal), query_telemetry (reads traces, logs, and metrics through signal routing)@@ -23,6 +24,8 @@ Guidelines:- When creating resources, confirm what was created with the key details (name, ID, status).- When creating alerts, prefer existing alert destinations when available. If none exist, create an alert destination first when the user provides connector details.- When listing, summarize the results concisely.+- When the user asks about stored memories, preferences, past agent knowledge, or what the project remembers, use list_memories or search_memories (memory connector APIs). Prefer list_memories for inventory; search_memories for a specific fact. If search returns count=0, try list_memories before saying nothing is stored. Do not invent memories the tools did not return.+- When the user asks to remember, store, update, or forget a memory, use add_memory, update_memory, or delete_memory. Some connectors require a user_id or session_id. If a memory tool returns a permission error, tell the user they cannot perform that action.- When a user asks to help improve, review, critique, or suggest edits for an existing prompt, first load it with get_prompt and then respond with suggested improvements. Do not call update_prompt_version unless the user explicitly asks to save, update, apply, publish, or create a new version.- When the user asks to link a context or prompt to a rule, use link_entity_to_rule.- Vault keys are auto-normalized to UPPER_SNAKE_CASE.@@ -68,6 +71,7 @@ URL mappings per entity type:- **context**: \`/context/{id}\`- **prompt**: \`/prompt-hub/{id}\`- **vault**: \`/vault\` (no ID in URL)+- **memory**: \`/memory?id={id}&connectorId={connectorId}\` (omit unknown query params)- **model**: \`/costs?tab=models\` (no ID in URL)- **evaluation**: \`/evaluations\` (no ID in URL)diff --git a/src/client/src/lib/platform/chat/tools.ts b/src/client/src/lib/platform/chat/tools.tsindex 049442f9..aac09e39 100644--- a/src/client/src/lib/platform/chat/tools.ts+++ b/src/client/src/lib/platform/chat/tools.ts@@ -41,6 +41,17 @@ import { listTraceRecords } from "../traces/read";import { getLogs } from "../logs/read";import { listMetricRecords } from "../metrics/read";import { resolveSignalSource } from "@/lib/telemetry-source";+import {+ recordMemoryMutationAudit,+ requireMemoryAccess,+ type MemoryMutationAuditInput,+} from "@/lib/access/memory-route";+import { queryProjectMemories } from "@/lib/platform/connectors/memory/read";+import {+ addProjectMemories,+ deleteProjectMemory,+ updateProjectMemory,+} from "@/lib/platform/connectors/memory/write";import Sanitizer from "@/utils/sanitizer";import {createAlertDestinationTool,@@ -923,6 +934,196 @@ export function getChatTools(userId: string, databaseConfigId: string, environme},}),+ // ==================== MEMORY ====================++ list_memories: tool<any, any>({+ description:+ "List stored agent memories from the project's memory connectors. Prefer this for inventory questions (who are the users, what is remembered, summarize memories). Pass connector_id and user_id/session_id/agent_id when the user or Memory page provided them. The result includes memories[].userId and filters.users.",+ inputSchema: jsonSchema({+ type: "object" as const,+ properties: {+ connector_id: { type: "string", description: "Memory connector id (memory:…)" },+ user_id: { type: "string" },+ agent_id: { type: "string" },+ session_id: { type: "string", description: "Session, store, or run id when the connector requires one" },+ limit: { type: "number", description: "Max memories to return (1-100)" },+ },+ }) as any,+ execute: async (params: any) => {+ try {+ await requireMemoryAccess("read");+ const result = await queryProjectMemories({+ connectorId: params.connector_id,+ userId: params.user_id,+ agentId: params.agent_id,+ sessionId: params.session_id,+ limit: params.limit,+ });+ return summarizeMemoryToolResult(result);+ } catch (e: any) {+ return { success: false, error: e.message || "Failed to list memories" };+ }+ },+ }),++ search_memories: tool<any, any>({+ description:+ "Semantic search over stored agent memories. Use for a specific fact lookup, not for listing users or browsing everything. If search returns count=0, call list_memories with the same connector_id/user_id before saying nothing is stored. Always pass connector_id and user_id when provided.",+ inputSchema: jsonSchema({+ type: "object" as const,+ properties: {+ query: { type: "string", description: "Natural-language search query" },+ connector_id: { type: "string" },+ user_id: { type: "string" },+ agent_id: { type: "string" },+ session_id: { type: "string" },+ limit: { type: "number" },+ },+ required: ["query"],+ }) as any,+ execute: async (params: any) => {+ try {+ await requireMemoryAccess("read");+ const result = await queryProjectMemories({+ query: params.query,+ connectorId: params.connector_id,+ userId: params.user_id,+ agentId: params.agent_id,+ sessionId: params.session_id,+ limit: params.limit,+ });+ return summarizeMemoryToolResult(result);+ } catch (e: any) {+ return { success: false, error: e.message || "Failed to search memories" };+ }+ },+ }),++ add_memory: tool<any, any>({+ description: "Create a stored memory on the project's memory connector. Use this when the user asks to remember a fact.",+ inputSchema: jsonSchema({+ type: "object" as const,+ properties: {+ content: { type: "string", description: "Memory text to store" },+ connector_id: { type: "string" },+ user_id: { type: "string" },+ agent_id: { type: "string" },+ session_id: { type: "string", description: "Required for some connectors such as Zep" },+ },+ required: ["content"],+ }) as any,+ execute: async (params: any) => {+ try {+ await requireMemoryAccess("create");+ const result = await addProjectMemories({+ content: params.content,+ connectorId: params.connector_id,+ userId: params.user_id,+ agentId: params.agent_id,+ sessionId: params.session_id,+ });+ const first = result.memories[0];+ await auditMemoryToolMutation({+ action: "create",+ targetId: first?.id,+ connectorId: result.connector?.id,+ userId: params.user_id,+ agentId: params.agent_id,+ sessionId: params.session_id,+ contentLength: typeof params.content === "string" ? params.content.length : undefined,+ });+ return {+ success: true,+ message: "Memory saved",+ url: memoryEntityUrl(first?.id, result.connector?.id),+ connector: result.connector+ ? { id: result.connector.id, name: result.connector.name, type: result.connector.type }+ : null,+ memories: result.memories.map((memory) => ({+ id: memory.id,+ content: memory.content,+ userId: memory.userId,+ sessionId: memory.sessionId,+ agentId: memory.agentId,+ url: memoryEntityUrl(memory.id, result.connector?.id),+ })),+ };+ } catch (e: any) {+ return { success: false, error: e.message || "Failed to add memory" };+ }+ },+ }),++ update_memory: tool<any, any>({+ description: "Update the text of an existing stored memory. Use list_memories or search_memories first to get the id.",+ inputSchema: jsonSchema({+ type: "object" as const,+ properties: {+ id: { type: "string", description: "Memory id" },+ content: { type: "string", description: "Replacement memory text" },+ connector_id: { type: "string" },+ },+ required: ["id", "content"],+ }) as any,+ execute: async (params: any) => {+ try {+ await requireMemoryAccess("update");+ const result = await updateProjectMemory({+ id: params.id,+ content: params.content,+ connectorId: params.connector_id,+ });+ await auditMemoryToolMutation({+ action: "update",+ targetId: result.memory.id,+ connectorId: result.connector?.id || params.connector_id,+ contentLength: typeof params.content === "string" ? params.content.length : undefined,+ });+ return {+ success: true,+ message: "Memory updated",+ url: memoryEntityUrl(result.memory.id, result.connector?.id),+ memory: {+ id: result.memory.id,+ content: result.memory.content,+ url: memoryEntityUrl(result.memory.id, result.connector?.id),+ },+ };+ } catch (e: any) {+ return { success: false, error: e.message || "Failed to update memory" };+ }+ },+ }),++ delete_memory: tool<any, any>({+ description: "Delete a stored memory by id. Confirm the id with the user when possible.",+ inputSchema: jsonSchema({+ type: "object" as const,+ properties: {+ id: { type: "string", description: "Memory id" },+ connector_id: { type: "string" },+ },+ required: ["id"],+ }) as any,+ execute: async (params: any) => {+ try {+ await requireMemoryAccess("delete");+ const result = await deleteProjectMemory({+ id: params.id,+ connectorId: params.connector_id,+ });+ await auditMemoryToolMutation({+ action: "delete",+ targetId: params.id,+ connectorId: result.connector?.id || params.connector_id,+ });+ return { success: true, message: "Memory deleted", id: params.id };+ } catch (e: any) {+ return { success: false, error: e.message || "Failed to delete memory" };+ }+ },+ }),+// ==================== CUSTOM MODELS ====================create_custom_model: tool<any, any>({@@ -1341,3 +1542,65 @@ export function getChatTools(userId: string, databaseConfigId: string, environme};}++function memoryEntityUrl(id?: string, connectorId?: string) {+ const params = new URLSearchParams();+ if (id) params.set("id", id);+ if (connectorId) params.set("connectorId", connectorId);+ const query = params.toString();+ return query ? `/memory?${query}` : "/memory";+}++async function auditMemoryToolMutation(input: MemoryMutationAuditInput) {+ try {+ await recordMemoryMutationAudit({ ...input, source: input.source || "chat" });+ } catch {+ // HTTP audit also fails open so a logging outage cannot block the write.+ }+}++function summarizeMemoryToolResult(result: Awaited<ReturnType<typeof queryProjectMemories>>) {+ const memories = result.memories.slice(0, 25).map((memory) => ({+ id: memory.id,+ content:+ memory.content.length > 280+ ? `${memory.content.slice(0, 277).trimEnd()}…`+ : memory.content,+ userId: memory.userId,+ agentId: memory.agentId,+ sessionId: memory.sessionId,+ kind: memory.kind,+ createdAt: memory.createdAt,+ score: memory.score,+ url: memoryEntityUrl(memory.id, result.connector?.id),+ }));+ const knownUserIds = Array.from(+ new Set(+ [+ ...(result.filters?.users || []),+ ...memories.map((memory) => memory.userId).filter(Boolean),+ ].map((value) => String(value))+ )+ );+ return {+ success: true,+ hint: result.hint,+ connector: result.connector+ ? {+ id: result.connector.id,+ name: result.connector.name,+ type: result.connector.type,+ environment: result.connector.environment,+ }+ : null,+ count: result.memories.length,+ stats: result.stats,+ filters: result.filters,+ knownUserIds,+ guidance:+ result.memories.length === 0 && knownUserIds.length > 0+ ? "No memory rows matched this query, but knownUserIds lists users present on this connector. Call list_memories (without a semantic query) with connector_id/user_id to load their memories."+ : undefined,+ memories,+ };+}diff --git a/src/client/src/lib/platform/connectors/bootstrap.ts b/src/client/src/lib/platform/connectors/bootstrap.tsnew file mode 100644index 00000000..1315a521--- /dev/null+++ b/src/client/src/lib/platform/connectors/bootstrap.ts@@ -0,0 +1,14 @@+/**+ * Register every connector category that this build can serve.+ *+ * Datasource adapters remain the source of truth for telemetry vendors;+ * memory adapters register through the same generic connector registry.+ */++import { ensureAdaptersRegistered } from "./datasource/bootstrap";+import { ensureMemoryAdaptersRegistered } from "./memory/bootstrap";++export function ensureConnectorsRegistered(): void {+ ensureAdaptersRegistered();+ ensureMemoryAdaptersRegistered();+}diff --git a/src/client/src/lib/platform/connectors/catalog.ts b/src/client/src/lib/platform/connectors/catalog.tsnew file mode 100644index 00000000..c1c53828--- /dev/null+++ b/src/client/src/lib/platform/connectors/catalog.ts@@ -0,0 +1,19 @@+import { ensureConnectorsRegistered } from "./bootstrap";+import { availableSourceTypeDescriptors } from "@/lib/telemetry-source-crud";+import { availableMemoryTypeDescriptors } from "./memory/crud";+import { isVisibleConnectorType } from "@/lib/platform/connectors/visible-types";+import { connectorIconPath } from "./icons";++/** Full type descriptors for every connector category this build can serve. */+export function availableConnectorTypeDescriptors() {+ ensureConnectorsRegistered();+ return [+ ...availableSourceTypeDescriptors().map((descriptor) => ({+ ...descriptor,+ icon: descriptor.icon || connectorIconPath(descriptor.type),+ category: "datasource" as const,+ scope: "project" as const,+ })),+ ...availableMemoryTypeDescriptors(),+ ].filter((descriptor) => isVisibleConnectorType(descriptor.type));+}diff --git a/src/client/src/lib/platform/connectors/datasource/http/endpoint-url.ts b/src/client/src/lib/platform/connectors/datasource/http/endpoint-url.tsindex a29a7e12..93f40487 100644--- a/src/client/src/lib/platform/connectors/datasource/http/endpoint-url.ts+++ b/src/client/src/lib/platform/connectors/datasource/http/endpoint-url.ts@@ -5,15 +5,46 @@* (single slash). `URL` can still parse that, but we store the canonical form.*/-import { existsSync } from "fs";-const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "::1"]);-/** Fix `http:/host` / `https:/host` and trim trailing slashes. */+/** Resolve `fs.existsSync` only at call time so client bundles never import `fs`. */+function defaultExists(path: string): boolean {+ try {+ // Keep Node `fs` out of client bundles; resolve only when `require` exists.+ if (typeof require !== "function") return false;+ // eslint-disable-next-line+ const fs = require("fs") as {+ existsSync?: (filePath: string) => boolean;+ };+ return Boolean(fs.existsSync?.(path));+ } catch {+ return false;+ }+}++/** Repair `http:/host` / `https:/host` (single slash) without changing the path. */+export function canonicalizeFetchUrl(raw: string): string {+ return String(raw || "").trim().replace(/^(https?:)\/(?!\/)/i, "$1//");+}++/**+ * Join a stored endpoint base with a request path. Preserves a trailing slash+ * on the path — `new URL(path, base)` is safe for the join itself, but callers+ * that later normalize the result must not strip resource slashes (Mem0 get+ * requires `/v1/memories/{id}/`).+ */+export function joinDatasourceRequestUrl(baseUrl: string, path: string): string {+ const base = String(baseUrl || "").replace(/\/+$/, "");+ const suffix = String(path || "").replace(/^\//, "");+ if (!base) return suffix;+ if (!suffix) return base;+ return `${base}/${suffix}`;+}++/** Fix `http:/host` / `https:/host` and trim trailing slashes on stored endpoint bases. */export function normalizeDatasourceEndpointUrl(raw: string): string {- const trimmed = String(raw || "").trim();- if (!trimmed) return trimmed;- const withAuthority = trimmed.replace(/^(https?:)\/(?!\/)/i, "$1//");+ const withAuthority = canonicalizeFetchUrl(raw);+ if (!withAuthority) return withAuthority;try {const url = new URL(withAuthority);if (url.protocol !== "http:" && url.protocol !== "https:") {@@ -27,7 +58,7 @@ export function normalizeDatasourceEndpointUrl(raw: string): string {/** True when the OpenLIT process is running inside a Docker container. */export function isRunningInDocker(- exists: (path: string) => boolean = existsSync+ exists: (path: string) => boolean = defaultExists): boolean {try {return exists("/.dockerenv");@@ -51,14 +82,17 @@ export function rewriteLoopbackEndpointForDocker(): string {const enabled = options.enabled ?? isRunningInDocker();if (!enabled) return rawUrl;- const normalized = normalizeDatasourceEndpointUrl(rawUrl);- if (!normalized) return rawUrl;+ const repaired = canonicalizeFetchUrl(rawUrl);+ if (!repaired) return rawUrl;try {- const url = new URL(normalized);+ const url = new URL(repaired);const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");- if (!LOOPBACK_HOSTNAMES.has(hostname)) return normalized;+ if (!LOOPBACK_HOSTNAMES.has(hostname)) return repaired;url.hostname = options.dockerHost || "host.docker.internal";- return url.toString().replace(/\/+$/, "");+ const rewritten = url.toString();+ const originalPath = repaired.split("?")[0].split("#")[0];+ if (originalPath.endsWith("/")) return rewritten;+ return rewritten.replace(/\/+$/, "");} catch {return rawUrl;}diff --git a/src/client/src/lib/platform/connectors/datasource/http/secret.ts b/src/client/src/lib/platform/connectors/datasource/http/secret.tsindex e3ad9d47..f0f71c7a 100644--- a/src/client/src/lib/platform/connectors/datasource/http/secret.ts+++ b/src/client/src/lib/platform/connectors/datasource/http/secret.ts@@ -13,6 +13,7 @@ import {DATA_SOURCE_SECRET_NOT_FOUND,DATA_SOURCE_SECRET_UNAVAILABLE,} from "@/constants/messages/en";+import { decryptValue, isEncrypted } from "@/utils/crypto";export interface ResolvedSecret {/** Raw decrypted secret string. */@@ -72,16 +73,28 @@ export function __resetSourceSecretCacheForTests(): void {export async function resolveSourceSecret(secretRef: string | null | undefined,dbConfigId?: string,- projectId?: string | null+ projectId?: string | null,+ options: { clickHouseVault?: boolean } = {}): Promise<ResolvedSecret> {- if (!secretRef) return { raw: "", credentials: {} };- const cacheKey = sourceSecretCacheKey(secretRef, dbConfigId, projectId);+ const ref = String(secretRef || "").trim();+ if (!ref) return { raw: "", credentials: {} };+ const cacheKey = sourceSecretCacheKey(ref, dbConfigId, projectId);const cached = sourceSecretCache.get(cacheKey);if (cached && cached.expiresAt > Date.now()) return cached.value;+ if (isEncrypted(ref)) {+ const raw = decryptValue(ref, { logErrors: false });+ if (isEncrypted(raw)) throw new Error(DATA_SOURCE_SECRET_DECRYPT_FAILED);+ return cacheResolvedSecret(cacheKey, parseSecretPayload(raw));+ }++ if (options.clickHouseVault === false) {+ throw new Error(DATA_SOURCE_SECRET_UNAVAILABLE);+ }+let result: Awaited<ReturnType<typeof getSecretById>>;try {- result = await getSecretById(secretRef, dbConfigId, false, {+ result = await getSecretById(ref, dbConfigId, false, {logDecryptErrors: false,projectId: projectId || undefined,});@@ -97,12 +110,16 @@ export async function resolveSourceSecret(const raw = typeof row?.value === "string" ? row.value : "";if (!row || !raw) throw new Error(DATA_SOURCE_SECRET_NOT_FOUND);+ if (isEncrypted(raw)) {+ throw new Error(DATA_SOURCE_SECRET_DECRYPT_FAILED);+ }++ return cacheResolvedSecret(cacheKey, parseSecretPayload(raw));+}++function parseSecretPayload(raw: string): ResolvedSecret {let credentials: Record<string, string> = {};if (raw) {- // decryptValue returns the ciphertext unchanged when decryption fails.- if (raw.startsWith("enc:v1:")) {- throw new Error(DATA_SOURCE_SECRET_DECRYPT_FAILED);- }try {const parsed = JSON.parse(raw);if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {@@ -111,12 +128,13 @@ export async function resolveSourceSecret();}} catch {- // A manually selected vault value may be a single opaque bearer token.credentials = { token: raw };}}+ return { raw, credentials };+}- const value = { raw, credentials };+function cacheResolvedSecret(cacheKey: string, value: ResolvedSecret): ResolvedSecret {sourceSecretCache.set(cacheKey, {value,expiresAt: Date.now() + SOURCE_SECRET_CACHE_TTL_MS,diff --git a/src/client/src/lib/platform/connectors/descriptions.ts b/src/client/src/lib/platform/connectors/descriptions.tsindex 66d9c8a3..a5520d22 100644--- a/src/client/src/lib/platform/connectors/descriptions.ts+++ b/src/client/src/lib/platform/connectors/descriptions.ts@@ -4,6 +4,9 @@ const CONNECTOR_DESCRIPTIONS: Record<string, string> = {loki: "Logs from Grafana Loki.",prometheus: "Metrics from Prometheus or a compatible query API.",jaeger: "Distributed traces from a Jaeger endpoint.",+ claude: "Agent memory from Claude memory stores.",+ mem0: "Long-term agent memory from Mem0.",+ zep: "Session and graph memory from Zep.",};export function connectorDescription(type: string, displayName?: string): string {diff --git a/src/client/src/lib/platform/connectors/icons.ts b/src/client/src/lib/platform/connectors/icons.tsindex c175feb6..164b5aaf 100644--- a/src/client/src/lib/platform/connectors/icons.ts+++ b/src/client/src/lib/platform/connectors/icons.ts@@ -5,6 +5,9 @@ const CONNECTOR_ICONS: Record<string, string> = {loki: "/images/connectors/grafana.svg",prometheus: "/images/connectors/grafana.svg",jaeger: "/images/connectors/jaeger.svg",+ claude: "/images/connectors/claude.svg",+ mem0: "/images/connectors/mem0.svg",+ zep: "/images/connectors/zep.svg",};export function connectorIconPath(type: string): string | undefined {diff --git a/src/client/src/lib/platform/connectors/instances.ts b/src/client/src/lib/platform/connectors/instances.tsindex 1274d133..c7ec1b7c 100644--- a/src/client/src/lib/platform/connectors/instances.ts+++ b/src/client/src/lib/platform/connectors/instances.ts@@ -96,16 +96,21 @@ export async function listProjectConnectorInstances(projectId: string) {...sources.map(syncTelemetrySourceConnector),]);const connectors = await prisma.connectorInstance.findMany({- where: { projectId, category: "datasource" },+ where: { projectId },orderBy: [{ environment: "asc" }, { createdAt: "asc" }],});return connectors.map((connector) => {let metadata: Record<string, unknown> = {};try { metadata = JSON.parse(connector.metadata || "{}") || {}; } catch { /* keep defaults */ }+ const isDatasource = connector.category === "datasource";return {...connector,- signals: connector.type === "clickhouse" ? "traces,logs,metrics,intelligence" : metadata.signals || "traces,logs,metrics",- isDefault: metadata.isDefault === true,+ signals: isDatasource+ ? (connector.type === "clickhouse"+ ? "traces,logs,metrics,intelligence"+ : metadata.signals || "traces,logs,metrics")+ : "",+ isDefault: isDatasource && metadata.isDefault === true,hasSecret: !!connector.secretRef,};});diff --git a/src/client/src/lib/platform/connectors/list-filters.ts b/src/client/src/lib/platform/connectors/list-filters.tsnew file mode 100644index 00000000..7b53aa78--- /dev/null+++ b/src/client/src/lib/platform/connectors/list-filters.ts@@ -0,0 +1,26 @@+export const CONNECTOR_FILTER_ALL_VALUE = "all";++export function configuredConnectorMatches(input: {+ query: string;+ typeFilter: string;+ categoryFilter: string;+ signalFilter: string;+ type: string;+ category: string;+ signals: string[];+ searchText: string;+}): boolean {+ if (input.typeFilter !== CONNECTOR_FILTER_ALL_VALUE && input.type !== input.typeFilter) return false;+ if (input.categoryFilter !== CONNECTOR_FILTER_ALL_VALUE && input.category !== input.categoryFilter) {+ return false;+ }+ if (+ input.signalFilter !== CONNECTOR_FILTER_ALL_VALUE &&+ !input.signals.includes(input.signalFilter)+ ) {+ return false;+ }+ const query = input.query.trim().toLowerCase();+ if (!query) return true;+ return input.searchText.toLowerCase().includes(query);+}diff --git a/src/client/src/lib/platform/connectors/memory/README.md b/src/client/src/lib/platform/connectors/memory/README.mdnew file mode 100644index 00000000..5a274ef5--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/README.md@@ -0,0 +1,56 @@+# Memory connectors — add-a-vendor checklist++This layer is **vendor-agnostic**: OpenLIT talks to external memory providers+(Claude, Mem0, and Zep today) through one adapter + a self-describing+descriptor. The+shared forms, Prisma `ConnectorInstance` rows, and the connector catalog are+driven by that descriptor, so **adding a new memory vendor must not require+editing shared forms, the schema, or any UI**.++## What a new memory connector needs (and nothing more)++1. **`memory/<vendor>/adapter.ts`** — a class extending `BaseMemoryAdapter`+ that implements the `MemoryAdapter` methods its `capabilities()` advertises.+ Reuse `http.ts` (which calls `http/safe-fetch`) for every outbound call and+ resolve credentials with `http/secret`. Methods for unsupported capabilities+ should throw `UnsupportedMemoryCapabilityError`. Override `listFilters()` when+ the vendor can enumerate users, sessions, or agents for Memory page dropdowns.+ Typed and used filter ids are also remembered on the connector+ (`metadata.memoryFilters`, stripped from public responses) so vendors without+ an entities API still populate the dropdown.+ Override `feedback()` when the vendor accepts per-memory ratings (Mem0-style+ positive / negative / very negative plus an optional reason).+ Writes (`add` / `update` / `delete`) are exposed on the Memory page,+ `/api/memory`, and Otter chat tools (`list_memories`, `search_memories`,+ `add_memory`, `update_memory`, `delete_memory`) only when `capabilities()`+ advertises them. Copying between connectors (`POST /api/memory/copy`) writes+ `metadata.openlit.port` on the destination and stores the same link on the+ destination connector so the source can be opened later. The copy HTTP route+ is wrapped with `withMemoryAudit` / `withMemoryAccess`.+ Otter tools call `requireMemoryAccess` /+ `recordMemoryMutationAudit` from `@/lib/access/memory-route` so Enterprise+ RBAC and audit apply the same way as the HTTP routes.+2. **A `describe(): MemoryTypeDescriptor`** on the factory. This is the single+ source of truth for the add/edit form. Set:+ - `type`, `displayName`, `capabilities`+ - `configFields` — reuse `config-fields.ts` helpers (`memoryHttpVendorFields`)+ so labels come from `constants/messages/en.ts`+ - `filterFields` — Memory page filters for this vendor (`memoryPageFilters`).+ Empty means the page shows no user/session/agent controls. Set `allowCustom`+ so operators can type ids the vendor did not enumerate.+ - `authStyle` (`"api-key"` for hosted memory APIs) plus optional `authHelp`+ and `docsUrl`+3. **Register the factory** in `bootstrap.ts` (`VENDOR_FACTORIES`), or ship it+ from the private repo via the `getExternalMemoryAdapters()` hook for+ EE-only vendors.++Credentials are encrypted onto `ConnectorInstance.secretRef` (`enc:v1:…`) so+memory connectors do not depend on the ClickHouse vault.++## What you must NOT touch++- No new form fields in `data-sources-page.tsx` — it renders `configFields`.+- No Prisma migration or enum — `ConnectorInstance.type` is a free string and+ `category` is `"memory"`.+- No per-vendor `switch` anywhere — capability gating + descriptors handle it.+- No `@/ee/**` import from CE; keep vendor strings in `constants/messages/en.ts`.diff --git a/src/client/src/lib/platform/connectors/memory/ask.ts b/src/client/src/lib/platform/connectors/memory/ask.tsnew file mode 100644index 00000000..eebeb47e--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/ask.ts@@ -0,0 +1,80 @@+/**+ * Compact prompt builder for Ask Otter on the Memory page.+ * Only passes identity filters the active connector declares.+ * Data should come from memory connector tools (list/search) when available.+ */++import {+ MEMORY_ASK_FALLBACK_PROMPT,+ MEMORY_ASK_OTTER_PROMPT,+ MEMORY_ASK_REQUIRED_FILTERS,+ MEMORY_ASK_SELECTED_PROMPT,+ MEMORY_ASK_TOOLS_PROMPT,+} from "@/constants/messages/en";+import type { MemoryFilterKey } from "./types";++export interface MemoryAskScope {+ connectorId?: string;+ userId?: string;+ agentId?: string;+ sessionId?: string;+ memoryId?: string;+ memoryContent?: string;+ /** Identity keys this connector supports (from filterFields). */+ filterKeys?: MemoryFilterKey[];+ /** Connector capabilities — prefer tools when list/search exist. */+ canList?: boolean;+ canSearch?: boolean;+}++const SELECTED_CONTENT_MAX = 120;+const SELECTED_CHIP_MAX = 48;++export function memoryAskExcerpt(value?: string, max = SELECTED_CONTENT_MAX): string {+ const text = String(value || "").replace(/\s+/g, " ").trim();+ if (!text) return "";+ return text.length > max ? `${text.slice(0, max)}…` : text;+}++export function memoryAskSelectedSummary(scope: MemoryAskScope = {}): string | undefined {+ const summary = memoryAskExcerpt(scope.memoryContent, SELECTED_CHIP_MAX);+ return summary || scope.memoryId || undefined;+}++export function buildMemoryAskPrompt(question: string, scope: MemoryAskScope = {}): string {+ const text = question.trim();+ const canList = scope.canList === true;+ const canSearch = scope.canSearch === true;+ const useConnectorApi = canList || canSearch;+ const keys = new Set(scope.filterKeys || []);+ const allow = (key: MemoryFilterKey) =>+ keys.size === 0 ? true : keys.has(key);++ const filters = [+ scope.connectorId ? `connector_id=${scope.connectorId}` : "",+ allow("userId") && scope.userId ? `user_id=${scope.userId}` : "",+ allow("agentId") && scope.agentId ? `agent_id=${scope.agentId}` : "",+ allow("sessionId") && scope.sessionId ? `session_id=${scope.sessionId}` : "",+ ].filter(Boolean);++ const lines: string[] = [+ useConnectorApi ? MEMORY_ASK_TOOLS_PROMPT : MEMORY_ASK_FALLBACK_PROMPT,+ MEMORY_ASK_OTTER_PROMPT,+ ];++ if (filters.length) {+ lines.push(MEMORY_ASK_REQUIRED_FILTERS(filters.join(", ")));+ }++ if (scope.memoryId) {+ lines.push(+ MEMORY_ASK_SELECTED_PROMPT(+ scope.memoryId,+ memoryAskExcerpt(scope.memoryContent, SELECTED_CONTENT_MAX)+ )+ );+ }++ lines.push("", text);+ return lines.join("\n");+}diff --git a/src/client/src/lib/platform/connectors/memory/base-adapter.ts b/src/client/src/lib/platform/connectors/memory/base-adapter.tsnew file mode 100644index 00000000..44a154bd--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/base-adapter.ts@@ -0,0 +1,71 @@+/**+ * Base class for memory connectors.+ *+ * Every method defaults to throwing `UnsupportedMemoryCapabilityError`, so a+ * vendor adapter only implements what its backend actually supports.+ */++import type { ConnectorHealthResult } from "../types";+import {+ UnsupportedMemoryCapabilityError,+ type MemoryAdapter,+ type MemoryCapabilities,+ emptyMemoryFilters,+ type MemoryFeedback,+ type MemoryFeedbackInput,+ type MemoryFilterOptions,+ type MemoryListFilter,+ type MemoryRecord,+ type MemorySearchQuery,+ type MemorySourceDescriptor,+ type MemoryUpdateInput,+ type MemoryWriteInput,+} from "./types";++export abstract class BaseMemoryAdapter implements MemoryAdapter {+ abstract readonly type: string;+ protected readonly descriptor: MemorySourceDescriptor;++ constructor(descriptor: MemorySourceDescriptor) {+ this.descriptor = descriptor;+ }++ abstract capabilities(): MemoryCapabilities;+ abstract healthCheck(): Promise<ConnectorHealthResult>;++ protected unsupported(capability: string): never {+ throw new UnsupportedMemoryCapabilityError(this.type, capability);+ }++ async add(_input: MemoryWriteInput): Promise<MemoryRecord[]> {+ this.unsupported("add");+ }++ async search(_query: MemorySearchQuery): Promise<MemoryRecord[]> {+ this.unsupported("search");+ }++ async get(_id: string): Promise<MemoryRecord | null> {+ this.unsupported("get");+ }++ async list(_filter: MemoryListFilter): Promise<MemoryRecord[]> {+ this.unsupported("list");+ }++ async listFilters(): Promise<MemoryFilterOptions> {+ return emptyMemoryFilters();+ }++ async update(_id: string, _input: MemoryUpdateInput): Promise<MemoryRecord> {+ this.unsupported("update");+ }++ async delete(_id: string): Promise<void> {+ this.unsupported("delete");+ }++ async feedback(_id: string, _input: MemoryFeedbackInput): Promise<MemoryFeedback> {+ this.unsupported("feedback");+ }+}diff --git a/src/client/src/lib/platform/connectors/memory/bootstrap.ts b/src/client/src/lib/platform/connectors/memory/bootstrap.tsnew file mode 100644index 00000000..b18261e0--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/bootstrap.ts@@ -0,0 +1,53 @@+/**+ * Adapter bootstrap for CE memory connectors: Claude, Mem0, and Zep.+ * Enterprise builds may contribute additional factories through the+ * neutral extension hook.+ */++import { getExternalMemoryAdapters } from "./enterprise";+import { claudeAdapterFactory } from "./claude/adapter";+import { mem0AdapterFactory } from "./mem0/adapter";+import {+ hasMemoryAdapterFactory,+ registerMemoryAdapterFactory,+} from "./registry";+import { zepAdapterFactory } from "./zep/adapter";+import { registerMemoryConnectorTypes } from "./index";++const VENDOR_FACTORIES = [+ claudeAdapterFactory,+ mem0AdapterFactory,+ zepAdapterFactory,+];++let registered = false;++/**+ * Register CE (+ external) memory adapter factories.+ *+ * Re-registers when the registry Map is empty even if this module previously+ * marked itself registered, matching datasource bootstrap HMR behaviour.+ */+export function ensureMemoryAdaptersRegistered(): void {+ if (+ registered &&+ hasMemoryAdapterFactory("claude") &&+ hasMemoryAdapterFactory("mem0") &&+ hasMemoryAdapterFactory("zep")+ ) {+ return;+ }+ registered = true;+ for (const factory of VENDOR_FACTORIES) {+ registerMemoryAdapterFactory(factory);+ }+ for (const factory of getExternalMemoryAdapters()) {+ registerMemoryAdapterFactory(factory);+ }+ registerMemoryConnectorTypes();+}++/** Test-only: allow re-registration. */+export function __resetMemoryBootstrapForTests(): void {+ registered = false;+}diff --git a/src/client/src/lib/platform/connectors/memory/claude/adapter.ts b/src/client/src/lib/platform/connectors/memory/claude/adapter.tsnew file mode 100644index 00000000..852f0a88--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/claude/adapter.ts@@ -0,0 +1,464 @@+/**+ * Claude (Anthropic) memory connector.+ *+ * Talks to Anthropic Memory Stores (`https://api.anthropic.com`) using the+ * `agent-memory-2026-07-22` beta. Stores are exposed as session filters; there+ * is no dedicated search endpoint, so search filters listed memories locally.+ */++import getMessage from "@/constants/messages";+import type { ConnectorHealthResult } from "../../types";+import type { ResolvedSecret } from "../../datasource/http/secret";+import { BaseMemoryAdapter } from "../base-adapter";+import { memoryHttpVendorFields, memoryPageFilters } from "../config-fields";+import { memoryBaseUrl, memoryRequest } from "../http";+import type {+ MemoryCapabilities,+ MemoryFilterOptions,+ MemoryHistoryEvent,+ MemoryListFilter,+ MemoryRecord,+ MemorySearchQuery,+ MemorySourceDescriptor,+ MemoryTypeDescriptor,+ MemoryUpdateInput,+ MemoryWriteInput,+} from "../types";+import { emptyMemoryFilters } from "../types";++const DEFAULT_URL = "https://api.anthropic.com";+const ANTHROPIC_VERSION = "2023-06-01";+const MEMORY_BETA = "agent-memory-2026-07-22";+const FULL_VIEW_LIMIT = 20;+const MAX_PAGES = 8;++const CLAUDE_CAPABILITIES: MemoryCapabilities = {+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: false,+};++const HISTORY_EVENTS: Record<string, string> = {+ created: "ADD",+ modified: "UPDATE",+ deleted: "DELETE",+};++function asRecord(value: unknown): Record<string, unknown> {+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}++function stringValue(value: unknown): string | undefined {+ if (typeof value !== "string") return undefined;+ const trimmed = value.trim();+ return trimmed || undefined;+}++function objectValue(value: unknown): Record<string, unknown> | undefined {+ const record = asRecord(value);+ return Object.keys(record).length ? record : undefined;+}++function slug(value: string): string {+ return (+ value+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 48) || "memory"+ );+}++function setting(descriptor: MemorySourceDescriptor, key: string): string | undefined {+ return stringValue(descriptor.settings[key]);+}++function encodeMemoryRef(storeId: string, memoryId: string): string {+ return `${storeId}:${memoryId}`;+}++function parseMemoryRef(+ id: string,+ configuredStore?: string+): { storeId: string; memoryId: string } | null {+ const trimmed = id.trim();+ if (!trimmed) return null;+ const colon = trimmed.indexOf(":");+ if (colon > 0) {+ const storeId = trimmed.slice(0, colon).trim();+ const memoryId = trimmed.slice(colon + 1).trim();+ if (storeId && memoryId) return { storeId, memoryId };+ }+ if (configuredStore) return { storeId: configuredStore, memoryId: trimmed };+ return null;+}++function pathCategories(path: string | undefined): string[] | undefined {+ if (!path) return undefined;+ const segments = path+ .split("/")+ .map((part) => part.trim())+ .filter(Boolean);+ return segments.length ? segments : undefined;+}++function actorId(raw: unknown): string | undefined {+ const actor = asRecord(raw);+ return (+ stringValue(actor.session_id) ||+ stringValue(actor.api_key_id) ||+ stringValue(actor.user_id)+ );+}++function writeContent(input: MemoryWriteInput): string {+ const content = stringValue(input.content);+ if (content) return content;+ const joined = (input.messages || [])+ .map((message) => stringValue(message.content))+ .filter((item): item is string => !!item)+ .join("\n")+ .trim();+ return joined;+}++function writePath(input: MemoryWriteInput, content: string): string {+ const raw = stringValue(input.metadata?.path);+ if (raw) return raw.startsWith("/") ? raw : `/${raw}`;+ return `/openlit/${slug(content)}.md`;+}++function matchesQuery(record: MemoryRecord, query: string): boolean {+ const haystack = [+ record.content,+ record.id,+ ...(record.categories || []),+ ...Object.values(record.metadata || {}).map((value) => String(value)),+ ]+ .join(" ")+ .toLowerCase();+ return haystack.includes(query.toLowerCase());+}++function normalizeRecord(+ raw: unknown,+ extras: { storeId?: string; userId?: string; history?: MemoryHistoryEvent[] } = {}+): MemoryRecord | null {+ const row = asRecord(raw);+ if (stringValue(row.type) === "memory_prefix") return null;+ const memoryId = stringValue(row.id);+ const storeId =+ stringValue(row.memory_store_id) || extras.storeId;+ if (!memoryId || !storeId) return null;+ const path = stringValue(row.path);+ const content = stringValue(row.content) || path || "";+ const versionId = stringValue(row.memory_version_id);+ const sha = stringValue(row.content_sha256);+ return {+ id: encodeMemoryRef(storeId, memoryId),+ content,+ userId: extras.userId,+ sessionId: storeId,+ categories: pathCategories(path),+ metadata: {+ ...(path ? { path } : {}),+ memory_id: memoryId,+ memory_store_id: storeId,+ ...(versionId ? { memory_version_id: versionId } : {}),+ ...(sha ? { content_sha256: sha } : {}),+ ...(typeof row.content_size_bytes === "number"+ ? { content_size_bytes: row.content_size_bytes }+ : {}),+ },+ history: extras.history,+ createdAt: stringValue(row.created_at),+ updatedAt: stringValue(row.updated_at),+ };+}++function normalizeHistory(raw: unknown): MemoryHistoryEvent[] {+ const body = asRecord(raw);+ const rows = Array.isArray(raw)+ ? raw+ : Array.isArray(body.data)+ ? body.data+ : [];+ const events: MemoryHistoryEvent[] = [];+ for (const item of rows) {+ const row = asRecord(item);+ const operation = stringValue(row.operation) || "";+ const event = HISTORY_EVENTS[operation] || operation.toUpperCase() || "UPDATE";+ const content = stringValue(row.content);+ events.push({+ id: stringValue(row.id),+ event,+ newMemory: content,+ createdAt: stringValue(row.created_at),+ actorId: actorId(row.created_by),+ });+ }+ return events;+}++function pageRows(raw: unknown): unknown[] {+ const body = asRecord(raw);+ return Array.isArray(body.data) ? body.data : Array.isArray(raw) ? raw : [];+}++function nextPage(raw: unknown): string | undefined {+ return stringValue(asRecord(raw).next_page);+}++export class ClaudeAdapter extends BaseMemoryAdapter {+ readonly type = "claude";++ private get baseUrl(): string {+ return memoryBaseUrl(this.descriptor, DEFAULT_URL);+ }++ private get configuredStoreId(): string | undefined {+ return setting(this.descriptor, "storeId");+ }++ private request<T>(+ path: string,+ opts: {+ method?: string;+ body?: unknown;+ timeoutMs?: number;+ } = {}+ ) {+ return memoryRequest<T>(this.descriptor, this.baseUrl, path, {+ ...opts,+ authHeaders: (secret: ResolvedSecret): Record<string, string> => {+ const apiKey = secret.credentials.apiKey || secret.raw;+ return {+ "anthropic-version": ANTHROPIC_VERSION,+ "anthropic-beta": MEMORY_BETA,+ ...(apiKey ? { "x-api-key": apiKey } : {}),+ };+ },+ });+ }++ private async collectPages(+ buildPath: (page?: string) => string,+ maxPages = MAX_PAGES+ ): Promise<unknown[]> {+ const rows: unknown[] = [];+ let page: string | undefined;+ for (let i = 0; i < maxPages; i++) {+ const body = await this.request(buildPath(page));+ rows.push(...pageRows(body));+ const next = nextPage(body);+ if (!next) break;+ page = next;+ }+ return rows;+ }++ private async listStores(): Promise<{ id: string; name: string }[]> {+ const rows = await this.collectPages((page) => {+ const params = new URLSearchParams();+ params.set("limit", "100");+ if (page) params.set("page", page);+ return `v1/memory_stores?${params.toString()}`;+ });+ const stores: { id: string; name: string }[] = [];+ for (const item of rows) {+ const row = asRecord(item);+ const id = stringValue(row.id);+ if (!id) continue;+ stores.push({+ id,+ name: stringValue(row.name) || id,+ });+ }+ return stores;+ }++ private async resolveStoreId(filter: {+ sessionId?: string;+ }): Promise<string> {+ const selected = stringValue(filter.sessionId) || this.configuredStoreId;+ if (selected) return selected;+ const stores = await this.listStores();+ if (stores.length === 1) return stores[0].id;+ throw new Error(getMessage().MEMORY_CONNECTOR_FILTER_REQUIRED);+ }++ private async listMemories(storeId: string): Promise<MemoryRecord[]> {+ const rows = await this.collectPages((page) => {+ const params = new URLSearchParams();+ params.set("path_prefix", "/");+ params.set("view", "full");+ params.set("limit", String(FULL_VIEW_LIMIT));+ if (page) params.set("page", page);+ return `v1/memory_stores/${encodeURIComponent(storeId)}/memories?${params.toString()}`;+ });+ return rows+ .map((row) => normalizeRecord(row, { storeId }))+ .filter((row): row is MemoryRecord => !!row);+ }++ capabilities(): MemoryCapabilities {+ return { ...CLAUDE_CAPABILITIES };+ }++ async healthCheck(): Promise<ConnectorHealthResult> {+ const started = Date.now();+ try {+ const storeId = this.configuredStoreId;+ if (storeId) {+ await this.request(`v1/memory_stores/${encodeURIComponent(storeId)}`, {+ timeoutMs: 10_000,+ });+ } else {+ const params = new URLSearchParams();+ params.set("limit", "1");+ await this.request(`v1/memory_stores?${params.toString()}`, {+ timeoutMs: 10_000,+ });+ }+ return { ok: true, latencyMs: Date.now() - started };+ } catch (error) {+ return {+ ok: false,+ latencyMs: Date.now() - started,+ message: String((error as Error)?.message || error),+ };+ }+ }++ async add(input: MemoryWriteInput): Promise<MemoryRecord[]> {+ const content = writeContent(input);+ if (!content) {+ throw new Error(getMessage().MEMORY_CONNECTOR_CONTENT_REQUIRED);+ }+ const storeId = await this.resolveStoreId(input);+ const body = await this.request(+ `v1/memory_stores/${encodeURIComponent(storeId)}/memories`,+ {+ method: "POST",+ body: {+ path: writePath(input, content),+ content,+ },+ }+ );+ const record = normalizeRecord(body, { storeId });+ return record ? [record] : [];+ }++ async search(query: MemorySearchQuery): Promise<MemoryRecord[]> {+ const q = query.query.trim();+ if (!q) throw new Error(getMessage().MEMORY_CONNECTOR_QUERY_REQUIRED);+ const records = await this.list(query);+ return records.filter((record) => matchesQuery(record, q));+ }++ async get(id: string): Promise<MemoryRecord | null> {+ const ref = parseMemoryRef(id, this.configuredStoreId);+ if (!ref) return null;+ const body = await this.request(+ `v1/memory_stores/${encodeURIComponent(ref.storeId)}/memories/${encodeURIComponent(ref.memoryId)}?view=full`+ );+ let history: MemoryHistoryEvent[] = [];+ try {+ const params = new URLSearchParams();+ params.set("memory_id", ref.memoryId);+ params.set("view", "full");+ params.set("limit", "50");+ history = normalizeHistory(+ await this.request(+ `v1/memory_stores/${encodeURIComponent(ref.storeId)}/memory_versions?${params.toString()}`+ )+ );+ } catch {+ history = [];+ }+ return normalizeRecord(body, { storeId: ref.storeId, history });+ }++ async list(filter: MemoryListFilter): Promise<MemoryRecord[]> {+ const storeId = await this.resolveStoreId(filter);+ const records = await this.listMemories(storeId);+ return records.slice(0, filter.limit || 50);+ }++ async listFilters(): Promise<MemoryFilterOptions> {+ const filters = emptyMemoryFilters();+ try {+ const stores = await this.listStores();+ // Claude memory is store-scoped; there is no first-class user id.+ filters.sessions = stores.map((store) => ({+ id: store.id,+ label: store.name,+ }));+ } catch {+ return emptyMemoryFilters();+ }+ return filters;+ }++ async update(id: string, input: MemoryUpdateInput): Promise<MemoryRecord> {+ const ref = parseMemoryRef(id, this.configuredStoreId);+ if (!ref) throw new Error(getMessage().MEMORY_DETAIL_NOT_FOUND);+ const path = stringValue(input.metadata?.path);+ const body = await this.request(+ `v1/memory_stores/${encodeURIComponent(ref.storeId)}/memories/${encodeURIComponent(ref.memoryId)}?view=full`,+ {+ method: "POST",+ body: {+ content: input.content,+ ...(path ? { path: path.startsWith("/") ? path : `/${path}` } : {}),+ },+ }+ );+ return (+ normalizeRecord(body, { storeId: ref.storeId }) || {+ id: encodeMemoryRef(ref.storeId, ref.memoryId),+ content: input.content,+ sessionId: ref.storeId,+ metadata: input.metadata,+ }+ );+ }++ async delete(id: string): Promise<void> {+ const ref = parseMemoryRef(id, this.configuredStoreId);+ if (!ref) throw new Error(getMessage().MEMORY_DETAIL_NOT_FOUND);+ await this.request(+ `v1/memory_stores/${encodeURIComponent(ref.storeId)}/memories/${encodeURIComponent(ref.memoryId)}`,+ { method: "DELETE" }+ );+ }+}++export const claudeAdapterFactory = {+ type: "claude",+ create: (descriptor: MemorySourceDescriptor) => new ClaudeAdapter(descriptor),+ describe: (): MemoryTypeDescriptor => ({+ type: "claude",+ displayName: "Claude",+ description: getMessage().MEMORY_CONNECTOR_CLAUDE_DESCRIPTION,+ capabilities: { ...CLAUDE_CAPABILITIES },+ configFields: [...memoryHttpVendorFields({ placeholder: DEFAULT_URL })],+ filterFields: memoryPageFilters([+ {+ key: "sessionId",+ label: getMessage().MEMORY_CONNECTOR_FIELD_STORE_ID,+ required: true,+ },+ ]),+ authStyle: "api-key",+ authHelp: getMessage().MEMORY_CONNECTOR_AUTH_HELP_CLAUDE,+ docsUrl: "https://platform.claude.com/docs/en/managed-agents/memory",+ }),+};diff --git a/src/client/src/lib/platform/connectors/memory/config-fields.ts b/src/client/src/lib/platform/connectors/memory/config-fields.tsnew file mode 100644index 00000000..39f01741--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/config-fields.ts@@ -0,0 +1,70 @@+/**+ * Shared config-field builders for memory connector descriptors.+ *+ * Reuse the HTTP endpoint/SSRF toggles from the datasource field helpers so+ * memory vendors stay on the same form schema. Labels come from the CE+ * message catalog.+ */++import getMessage from "@/constants/messages";+import {+ allowHttpField,+ allowPrivateNetworkField,+ endpointField,+} from "../datasource/config-fields";+import type { FieldDef } from "../datasource/types";+import type { MemoryFilterField, MemoryFilterKey } from "./types";++export function memoryApiKeyField(): FieldDef {+ const messages = getMessage();+ return {+ key: "apiKey",+ label: messages.DATA_SOURCE_FIELD_API_KEY,+ kind: "password",+ group: "credentials",+ };+}++/** Standard HTTP memory vendor: endpoint, SSRF toggles, and an API key. */+export function memoryHttpVendorFields(opts: { placeholder?: string } = {}): FieldDef[] {+ return [+ {+ ...endpointField(opts.placeholder),+ defaultValue: opts.placeholder,+ },+ allowHttpField(),+ allowPrivateNetworkField(),+ memoryApiKeyField(),+ ];+}++/** Memory page filters declared on a vendor `describe()`. Custom values are allowed by default. */+export function memoryPageFilters(+ fields: Array<+ | MemoryFilterKey+ | (Pick<MemoryFilterField, "key"> &+ Partial<+ Pick<+ MemoryFilterField,+ "label" | "required" | "writeRequired" | "allowCustom"+ >+ >)+ >+): MemoryFilterField[] {+ const messages = getMessage();+ const labels: Record<MemoryFilterKey, string> = {+ userId: messages.MEMORY_USER_FILTER,+ sessionId: messages.MEMORY_SESSION_FILTER,+ agentId: messages.MEMORY_AGENT_FILTER,+ };+ return fields.map((field) => {+ const spec = typeof field === "string" ? { key: field } : field;+ return {+ key: spec.key,+ label: spec.label || labels[spec.key],+ required: spec.required,+ writeRequired: spec.writeRequired,+ allowCustom: spec.allowCustom !== false,+ };+ });+}diff --git a/src/client/src/lib/platform/connectors/memory/crud.ts b/src/client/src/lib/platform/connectors/memory/crud.tsnew file mode 100644index 00000000..0e10fe6e--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/crud.ts@@ -0,0 +1,580 @@+/**+ * Project-scoped CRUD for memory connector instances.+ *+ * Memory connectors persist on Prisma `ConnectorInstance`. API keys are+ * encrypted onto `secretRef` (same `enc:v1:` scheme as vault values) so adding+ * Claude/Mem0/Zep does not require ClickHouse. Raw keys never appear in API+ * responses.+ */++import { randomUUID } from "crypto";+import { headers } from "next/headers";+import prisma from "@/lib/prisma";+import { createProjectEnvironment } from "@/lib/project-environment";+import {+ getCurrentOrganisation,+ getCurrentProjectForOrganisation,+} from "@/lib/organisation";+import { assertPremiumConnectorAllowed } from "@/lib/access/connector-entitlement";+import { OPENLIT_CONTEXT_HEADERS } from "@/constants/openlit-context";+import { normalizeDatasourceEndpointUrl } from "@/lib/platform/connectors/datasource/http/endpoint-url";+import { invalidateSourceSecretCache } from "@/lib/platform/connectors/datasource/http/secret";+import { encryptValue, isEncrypted } from "@/utils/crypto";+import { ensureMemoryAdaptersRegistered } from "./bootstrap";+import {+ createMemoryAdapter,+ getMemoryTypeDescriptor,+ hasMemoryAdapterFactory,+ listMemoryTypeDescriptors,+} from "./registry";+import type { MemoryPortLink, MemorySourceDescriptor } from "./types";+import { connectorDescription } from "../descriptions";+import { connectorIconPath } from "../icons";+import {+ MEMORY_CONNECTOR_NAME_REQUIRED,+ MEMORY_CONNECTOR_NAME_TAKEN,+ MEMORY_CONNECTOR_NO_PROJECT,+ MEMORY_CONNECTOR_NOT_FOUND,+ MEMORY_CONNECTOR_TYPE_UNKNOWN,+ MEMORY_CONNECTOR_INLINE_SECRET_REQUIRED,+ TELEMETRY_SOURCE_INVALID_SETTINGS,+} from "@/constants/messages/en";++export const MEMORY_CONNECTOR_PREFIX = "memory:";++export function memoryConnectorId(id: string): string {+ const trimmed = String(id || "").trim();+ return trimmed.startsWith(MEMORY_CONNECTOR_PREFIX)+ ? trimmed+ : `${MEMORY_CONNECTOR_PREFIX}${trimmed}`;+}++export function isMemoryConnectorId(id: unknown): boolean {+ return String(id || "").startsWith(MEMORY_CONNECTOR_PREFIX);+}++export interface MemoryConnectorInput {+ name?: unknown;+ environment?: unknown;+ type?: unknown;+ settings?: unknown;+ secretRef?: unknown;+ credentials?: unknown;+}++/** Public memory connector row — never includes secretRef. */+export type MemoryConnectorPublic = {+ id: string;+ name: string;+ type: string;+ environment: string;+ organisationId: string | null;+ projectId: string | null;+ settings: string;+ status: string;+ metadata: string;+ createdAt: Date;+ updatedAt: Date;+ hasSecret: boolean;+ category: "memory";+ scope: "project";+ signals: string;+ isDefault: boolean;+};++function sanitize(row: {+ id: string;+ name: string;+ type: string;+ environment: string;+ organisationId: string | null;+ projectId: string | null;+ settings: string;+ secretRef?: string | null;+ status: string;+ metadata: string;+ createdAt: Date;+ updatedAt: Date;+}): MemoryConnectorPublic {+ return {+ id: row.id,+ name: row.name,+ type: row.type,+ environment: row.environment,+ organisationId: row.organisationId,+ projectId: row.projectId,+ settings: row.settings,+ status: row.status,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ metadata: publicConnectorMetadata(row.metadata ?? "{}"),+ hasSecret: !!row.secretRef,+ category: "memory",+ scope: "project",+ signals: "",+ isDefault: false,+ };+}++async function requireCurrentProject(): Promise<{+ organisationId: string;+ projectId: string;+}> {+ const org = await getCurrentOrganisation();+ if (!org?.id) throw new Error(MEMORY_CONNECTOR_NO_PROJECT);+ const project = await getCurrentProjectForOrganisation(org.id);+ if (!project?.id) throw new Error(MEMORY_CONNECTOR_NO_PROJECT);+ return { organisationId: org.id, projectId: project.id };+}++function normalizeEnvironment(value: unknown): string {+ const environment = String(value || "production").trim().toLowerCase();+ if (!/^[a-z0-9][a-z0-9._-]{0,62}$/.test(environment)) {+ throw new Error(+ "Environment must use letters, numbers, dots, hyphens, or underscores."+ );+ }+ return environment;+}++/**+ * Memory connectors are environment-scoped (same hierarchy as datasources).+ * Prefer an explicit argument, then the request `x-openlit-environment` header,+ * else production.+ */+async function resolveMemoryEnvironment(environment?: string): Promise<string> {+ if (environment != null && String(environment).trim()) {+ return normalizeEnvironment(environment);+ }+ try {+ const headerStore = await headers();+ const fromHeader = headerStore.get(OPENLIT_CONTEXT_HEADERS.environment);+ if (fromHeader?.trim()) return normalizeEnvironment(fromHeader);+ } catch {+ /* outside a Next.js request (unit tests / scripts) */+ }+ return "production";+}++function normalizeSettingsObject(settings: Record<string, unknown>): Record<string, unknown> {+ const next = { ...settings };+ if (typeof next.url === "string" && next.url.trim()) {+ next.url = normalizeDatasourceEndpointUrl(next.url);+ }+ return next;+}++function normalizeSettings(settings: unknown): string {+ if (settings === undefined || settings === null) return "{}";+ if (typeof settings === "string") {+ try {+ const parsed = JSON.parse(settings);+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ throw new Error(TELEMETRY_SOURCE_INVALID_SETTINGS);+ }+ return JSON.stringify(normalizeSettingsObject(parsed as Record<string, unknown>));+ } catch (error) {+ if (error instanceof Error && error.message === TELEMETRY_SOURCE_INVALID_SETTINGS) {+ throw error;+ }+ throw new Error(TELEMETRY_SOURCE_INVALID_SETTINGS);+ }+ }+ if (typeof settings === "object" && !Array.isArray(settings)) {+ return JSON.stringify(normalizeSettingsObject(settings as Record<string, unknown>));+ }+ throw new Error(TELEMETRY_SOURCE_INVALID_SETTINGS);+}++function credentialsToSecretRef(+ credentials: unknown+): string | undefined {+ if (!credentials || typeof credentials !== "object" || Array.isArray(credentials)) {+ return undefined;+ }+ const entries = Object.entries(credentials as Record<string, unknown>).filter(+ ([, v]) => typeof v === "string" && v.trim() !== ""+ );+ if (entries.length === 0) return undefined;+ return encryptValue(JSON.stringify(Object.fromEntries(entries)));+}++async function validateSecretReference(secretRef: string | null) {+ if (!secretRef) return;+ if (isEncrypted(secretRef)) return;+ throw new Error(MEMORY_CONNECTOR_INLINE_SECRET_REQUIRED);+}++function validateType(type: unknown): string {+ ensureMemoryAdaptersRegistered();+ const t = String(type || "").trim();+ if (!t || !hasMemoryAdapterFactory(t) || getMemoryTypeDescriptor(t)?.internal) {+ throw new Error(MEMORY_CONNECTOR_TYPE_UNKNOWN(String(type)));+ }+ return t;+}++export function isMemoryConnectorType(type: unknown): boolean {+ ensureMemoryAdaptersRegistered();+ return hasMemoryAdapterFactory(String(type || "").trim());+}++export function availableMemoryTypeDescriptors() {+ ensureMemoryAdaptersRegistered();+ return listMemoryTypeDescriptors().map((descriptor) => ({+ ...descriptor,+ category: "memory" as const,+ scope: "project" as const,+ declaredSignals: [] as string[],+ description:+ descriptor.description ||+ connectorDescription(descriptor.type, descriptor.displayName),+ icon: descriptor.icon || connectorIconPath(descriptor.type),+ }));+}++function parseJsonObject(raw: string): Record<string, unknown> {+ try {+ const parsed = JSON.parse(raw || "{}");+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {+ return parsed as Record<string, unknown>;+ }+ } catch {+ /* keep empty */+ }+ return {};+}++function publicConnectorMetadata(raw: string): string {+ const parsed = parseJsonObject(raw);+ delete parsed.memoryPorts;+ delete parsed.memoryFilters;+ return JSON.stringify(parsed);+}++function asPortLink(value: unknown): MemoryPortLink | null {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const row = value as Record<string, unknown>;+ const sourceConnectorId = String(row.sourceConnectorId || "").trim();+ const sourceMemoryId = String(row.sourceMemoryId || "").trim();+ if (!sourceConnectorId || !sourceMemoryId) return null;+ return {+ sourceConnectorId,+ sourceConnectorType: String(row.sourceConnectorType || "") || undefined,+ sourceConnectorName: String(row.sourceConnectorName || "") || undefined,+ sourceMemoryId,+ originConnectorId: String(row.originConnectorId || "") || undefined,+ originMemoryId: String(row.originMemoryId || "") || undefined,+ copiedAt: String(row.copiedAt || ""),+ contentFingerprint: String(row.contentFingerprint || ""),+ destMemoryId: String(row.destMemoryId || "") || undefined,+ };+}++export async function readMemoryPortLinks(id: string): Promise<MemoryPortLink[]> {+ const row = await getMemoryConnector(id);+ const ports = parseJsonObject(row.metadata || "{}").memoryPorts;+ if (!Array.isArray(ports)) return [];+ return ports.map(asPortLink).filter((link): link is MemoryPortLink => !!link);+}++export async function recordMemoryPortLinks(+ id: string,+ links: MemoryPortLink[]+): Promise<void> {+ if (!links.length) return;+ const { projectId } = await requireCurrentProject();+ const instanceId = memoryConnectorId(id);+ const existing = await prisma.connectorInstance.findFirst({+ where: { id: instanceId, projectId, category: "memory" },+ });+ if (!existing) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ const metadata = parseJsonObject(existing.metadata || "{}");+ const current = Array.isArray(metadata.memoryPorts) ? metadata.memoryPorts : [];+ const merged = new Map<string, MemoryPortLink>();+ for (const item of [...current, ...links]) {+ const link = asPortLink(item);+ if (!link) continue;+ merged.set(`${link.sourceConnectorId}:${link.sourceMemoryId}`, link);+ }+ const next = Array.from(merged.values()).slice(-500);+ await prisma.connectorInstance.update({+ where: { id: instanceId },+ data: { metadata: JSON.stringify({ ...metadata, memoryPorts: next }) },+ });+}++const MAX_REMEMBERED_FILTERS = 100;++export interface RememberedMemoryFilters {+ users: string[];+ sessions: string[];+ agents: string[];+}++export function emptyRememberedMemoryFilters(): RememberedMemoryFilters {+ return { users: [], sessions: [], agents: [] };+}++function uniqueFilterIds(values: unknown): string[] {+ const seen = new Set<string>();+ const next: string[] = [];+ const rows = Array.isArray(values) ? values : [];+ for (const value of rows) {+ const id =+ typeof value === "string"+ ? value.trim()+ : value && typeof value === "object" && !Array.isArray(value)+ ? String((value as { id?: unknown }).id || "").trim()+ : "";+ if (!id || seen.has(id)) continue;+ seen.add(id);+ next.push(id);+ }+ return next.slice(-MAX_REMEMBERED_FILTERS);+}++function asRememberedFilters(raw: unknown): RememberedMemoryFilters {+ const row =+ raw && typeof raw === "object" && !Array.isArray(raw)+ ? (raw as Record<string, unknown>)+ : {};+ return {+ users: uniqueFilterIds(row.users),+ sessions: uniqueFilterIds(row.sessions),+ agents: uniqueFilterIds(row.agents),+ };+}++export async function readRememberedMemoryFilters(+ id: string+): Promise<RememberedMemoryFilters> {+ const row = await getMemoryConnector(id);+ return asRememberedFilters(parseJsonObject(row.metadata || "{}").memoryFilters);+}++export async function rememberMemoryFilters(+ id: string,+ patch: Partial<RememberedMemoryFilters>+): Promise<void> {+ const extra = asRememberedFilters(patch);+ if (!extra.users.length && !extra.sessions.length && !extra.agents.length) {+ return;+ }+ const { projectId } = await requireCurrentProject();+ const instanceId = memoryConnectorId(id);+ const existing = await prisma.connectorInstance.findFirst({+ where: { id: instanceId, projectId, category: "memory" },+ });+ if (!existing) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ const metadata = parseJsonObject(existing.metadata || "{}");+ const current = asRememberedFilters(metadata.memoryFilters);+ const next = {+ users: uniqueFilterIds([...current.users, ...extra.users]),+ sessions: uniqueFilterIds([...current.sessions, ...extra.sessions]),+ agents: uniqueFilterIds([...current.agents, ...extra.agents]),+ };+ if (+ next.users.length === current.users.length &&+ next.sessions.length === current.sessions.length &&+ next.agents.length === current.agents.length &&+ next.users.every((id, index) => id === current.users[index]) &&+ next.sessions.every((id, index) => id === current.sessions[index]) &&+ next.agents.every((id, index) => id === current.agents[index])+ ) {+ return;+ }+ await prisma.connectorInstance.update({+ where: { id: instanceId },+ data: { metadata: JSON.stringify({ ...metadata, memoryFilters: next }) },+ });+}++function parseSettings(settings: string): Record<string, unknown> {+ try {+ const parsed = JSON.parse(settings || "{}");+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {+ return parsed as Record<string, unknown>;+ }+ } catch {+ /* keep empty */+ }+ return {};+}++function toRuntimeDescriptor(row: {+ id: string;+ type: string;+ name: string;+ settings: string;+ secretRef?: string | null;+ projectId?: string | null;+ environment?: string | null;+}): MemorySourceDescriptor {+ return {+ type: row.type,+ id: row.id,+ settings: parseSettings(row.settings),+ secretRef: row.secretRef,+ projectId: row.projectId ?? null,+ name: row.name,+ environment: row.environment || undefined,+ };+}++export async function createMemoryConnector(input: MemoryConnectorInput) {+ const { organisationId, projectId } = await requireCurrentProject();+ const name = String(input.name || "").trim();+ if (!name) throw new Error(MEMORY_CONNECTOR_NAME_REQUIRED);+ const type = validateType(input.type);+ await assertPremiumConnectorAllowed(type);+ const environment = normalizeEnvironment(input.environment);+ await createProjectEnvironment(environment);+ const settings = normalizeSettings(input.settings);+ const credentialSecretRef = credentialsToSecretRef(input.credentials);+ const secretRef =+ credentialSecretRef ??+ (typeof input.secretRef === "string" ? input.secretRef : null);+ await validateSecretReference(secretRef);++ const existing = await prisma.connectorInstance.findFirst({+ where: { projectId, name, environment },+ select: { id: true },+ });+ if (existing) throw new Error(MEMORY_CONNECTOR_NAME_TAKEN(name, environment));++ const created = await prisma.connectorInstance.create({+ data: {+ id: memoryConnectorId(randomUUID()),+ category: "memory",+ type,+ name,+ environment,+ organisationId,+ projectId,+ settings,+ secretRef,+ status: "active",+ metadata: JSON.stringify({ category: "memory" }),+ },+ });+ return sanitize(created);+}++export async function updateMemoryConnector(id: string, input: MemoryConnectorInput) {+ const { projectId } = await requireCurrentProject();+ const instanceId = memoryConnectorId(id);+ const existing = await prisma.connectorInstance.findFirst({+ where: { id: instanceId, projectId, category: "memory" },+ });+ if (!existing) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);++ const name = input.name === undefined ? existing.name : String(input.name || "").trim();+ if (!name) throw new Error(MEMORY_CONNECTOR_NAME_REQUIRED);+ const environment =+ input.environment === undefined+ ? existing.environment+ : normalizeEnvironment(input.environment);+ await createProjectEnvironment(environment);+ const settings =+ input.settings === undefined ? existing.settings : normalizeSettings(input.settings);+ const credentialSecretRef = credentialsToSecretRef(input.credentials);+ const secretRef =+ credentialSecretRef ??+ (typeof input.secretRef === "string" ? input.secretRef : existing.secretRef);+ await validateSecretReference(secretRef || null);++ if (name !== existing.name || environment !== existing.environment) {+ const clash = await prisma.connectorInstance.findFirst({+ where: {+ projectId,+ name,+ environment,+ NOT: { id: instanceId },+ },+ select: { id: true },+ });+ if (clash) throw new Error(MEMORY_CONNECTOR_NAME_TAKEN(name, environment));+ }++ const updated = await prisma.connectorInstance.update({+ where: { id: instanceId },+ data: {+ name,+ environment,+ settings,+ secretRef,+ status: "active",+ },+ });+ if (credentialSecretRef || input.secretRef) {+ invalidateSourceSecretCache(existing.secretRef || undefined);+ }+ return sanitize(updated);+}++export async function deleteMemoryConnector(id: string) {+ const { projectId } = await requireCurrentProject();+ const instanceId = memoryConnectorId(id);+ const existing = await prisma.connectorInstance.findFirst({+ where: { id: instanceId, projectId, category: "memory" },+ select: { id: true, secretRef: true },+ });+ if (!existing) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ await prisma.connectorInstance.delete({ where: { id: instanceId } });+ invalidateSourceSecretCache(existing.secretRef || undefined);+ return { ok: true };+}++export async function getMemoryConnector(id: string) {+ const { projectId } = await requireCurrentProject();+ const instanceId = memoryConnectorId(id);+ const existing = await prisma.connectorInstance.findFirst({+ where: { id: instanceId, projectId, category: "memory" },+ });+ if (!existing) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ return existing;+}++export async function listMemoryConnectors(environment?: string) {+ ensureMemoryAdaptersRegistered();+ const { projectId } = await requireCurrentProject();+ const env = await resolveMemoryEnvironment(environment);+ const rows = await prisma.connectorInstance.findMany({+ where: { projectId, category: "memory", environment: env },+ orderBy: [{ createdAt: "asc" }],+ });+ return rows.filter((row) => hasMemoryAdapterFactory(row.type)).map(sanitize);+}++export async function getMemoryRuntime(id?: string, environment?: string) {+ ensureMemoryAdaptersRegistered();+ const { projectId } = await requireCurrentProject();+ const env = await resolveMemoryEnvironment(environment);+ const instanceId = id ? memoryConnectorId(id) : undefined;+ const row = instanceId+ ? await prisma.connectorInstance.findFirst({+ where: {+ id: instanceId,+ projectId,+ category: "memory",+ environment: env,+ },+ })+ : await prisma.connectorInstance.findFirst({+ where: { projectId, category: "memory", environment: env },+ orderBy: [{ createdAt: "asc" }],+ });+ if (!row) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ const adapter = createMemoryAdapter(toRuntimeDescriptor(row));+ if (!adapter) throw new Error(MEMORY_CONNECTOR_TYPE_UNKNOWN(row.type));+ return { adapter, connector: sanitize(row) };+}++export async function healthCheckMemoryConnector(id: string) {+ ensureMemoryAdaptersRegistered();+ const row = await getMemoryConnector(id);+ const adapter = createMemoryAdapter(toRuntimeDescriptor(row));+ if (!adapter) throw new Error(MEMORY_CONNECTOR_TYPE_UNKNOWN(row.type));+ return adapter.healthCheck();+}diff --git a/src/client/src/lib/platform/connectors/memory/enterprise.ts b/src/client/src/lib/platform/connectors/memory/enterprise.tsnew file mode 100644index 00000000..633b9d60--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/enterprise.ts@@ -0,0 +1,14 @@+/**+ * Neutral extension hook for additional memory connector adapters.+ *+ * CE memory vendors (Claude, Mem0, Zep) are registered via `bootstrap.ts`. This hook+ * stays empty in CE so a private fork can contribute extra factories without+ * importing `@/ee/**` from shared code.+ */++import type { MemoryAdapterFactory } from "./types";++/** CE no-op: no extra private memory adapters beyond the CE bootstrap set. */+export function getExternalMemoryAdapters(): MemoryAdapterFactory[] {+ return [];+}diff --git a/src/client/src/lib/platform/connectors/memory/graph.ts b/src/client/src/lib/platform/connectors/memory/graph.tsnew file mode 100644index 00000000..71c75704--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/graph.ts@@ -0,0 +1,478 @@+/**+ * Pure helpers that turn memory records into page stats and a graph model.+ * Kept free of Prisma/adapters so the Memory page and Otter tools share one+ * classification without pulling connector runtime into client bundles.+ */++import type { MemoryRecord } from "./types";+import { MEMORY_UNKNOWN_USER } from "@/constants/messages/en";++export type MemoryKind = "temporal" | "profile" | "summary";++export const MEMORY_ENTITY_TYPES = [+ "user",+ "entity",+ "event",+ "location",+ "object",+ "preference",+ "topic",+] as const;++export type MemoryEntityType = (typeof MEMORY_ENTITY_TYPES)[number];++export interface MemoryStats {+ total: number;+ connections: number;+ users: number;+ sessions: number;+ temporal: number;+ profile: number;+ summary: number;+}++export interface MemoryGraphNode {+ id: string;+ type: "user" | "session" | "memory" | "entity";+ label: string;+ memoryId?: string;+ kind?: MemoryKind;+ entityType?: MemoryEntityType;+}++export interface MemoryGraphEdge {+ from: string;+ to: string;+ memoryId?: string;+ label?: string;+}++export interface MemoryGraphModel {+ nodes: MemoryGraphNode[];+ edges: MemoryGraphEdge[];+ kind?: "knowledge" | "tree";+}++export interface LaidOutMemoryNode extends MemoryGraphNode {+ x: number;+ y: number;+}++const MAX_GRAPH_MEMORIES = 80;++export function emptyMemoryStats(): MemoryStats {+ return {+ total: 0,+ connections: 0,+ users: 0,+ sessions: 0,+ temporal: 0,+ profile: 0,+ summary: 0,+ };+}++function metaString(record: MemoryRecord, keys: string[]): string {+ const metadata = record.metadata || {};+ for (const key of keys) {+ const value = metadata[key];+ if (typeof value === "string" && value.trim()) return value.trim().toLowerCase();+ }+ return "";+}++export function classifyMemoryKind(record: MemoryRecord): MemoryKind {+ const type = [+ metaString(record, [+ "memory_type",+ "memoryType",+ "category",+ "domain",+ "type",+ "kind",+ ]),+ ...(record.categories || []),+ ]+ .join(" ")+ .toLowerCase();+ if (/(temporal|episodic|event)/.test(type)) return "temporal";+ if (/(profile|identity|preference|user)/.test(type)) return "profile";+ if (/(summary|semantic|general|original)/.test(type)) return "summary";++ const content = String(record.content || "").toLowerCase();+ if (/\b(yesterday|today|last week|on \d{4}|at \d{1,2}:\d{2})\b/.test(content)) {+ return "temporal";+ }+ if (/\b(is a|likes|prefers|works at|name is)\b/.test(content)) {+ return "profile";+ }+ return "summary";+}++export function summarizeMemoryStats(records: MemoryRecord[]): MemoryStats {+ const users = new Set<string>();+ const sessions = new Set<string>();+ const links = new Set<string>();+ const stats = emptyMemoryStats();+ stats.total = records.length;+ for (const record of records) {+ const kind = classifyMemoryKind(record);+ stats[kind] += 1;+ if (record.userId) users.add(record.userId);+ if (record.sessionId) sessions.add(record.sessionId);+ if (record.userId || record.sessionId) {+ links.add(`${record.userId || "_"}:${record.sessionId || "_"}`);+ }+ }+ stats.users = users.size;+ stats.sessions = sessions.size;+ stats.connections = links.size;+ return stats;+}++function titleFromContent(content: string, fallback: string): string {+ const line = content.split(/\n/)[0]?.trim() || fallback;+ return line.length > 48 ? `${line.slice(0, 45).trimEnd()}…` : line;+}++export function classifyEntityType(types?: string[]): MemoryEntityType {+ const labels = (types || [])+ .map((value) => value.trim().toLowerCase())+ .filter((value) => value && value !== "node");+ for (const type of MEMORY_ENTITY_TYPES) {+ if (type === "entity") continue;+ if (labels.includes(type)) return type;+ }+ return "entity";+}++export function buildMemoryGraph(+ records: MemoryRecord[],+ options?: { maxMemories?: number }+): MemoryGraphModel {+ const maxMemories = options?.maxMemories ?? MAX_GRAPH_MEMORIES;+ const facts = records.filter((record) => !record.graphOnly).slice(0, maxMemories);+ const extras = records.filter((record) => record.graphOnly);+ if (facts.some((record) => record.relation?.source && record.relation?.target)) {+ return buildKnowledgeGraph(facts, extras);+ }+ return buildSessionTreeGraph(facts);+}++function buildKnowledgeGraph(+ facts: MemoryRecord[],+ extras: MemoryRecord[]+): MemoryGraphModel {+ const nodes: MemoryGraphNode[] = [];+ const edges: MemoryGraphEdge[] = [];+ const seen = new Set<string>();++ const pushEndpoint = (endpoint: {+ id: string;+ label: string;+ types?: string[];+ }) => {+ const id = endpoint.id.trim();+ if (!id || seen.has(id)) return;+ seen.add(id);+ const entityType = classifyEntityType(endpoint.types);+ nodes.push({+ id,+ type: entityType === "user" ? "user" : "entity",+ entityType,+ label: endpoint.label.trim() || id,+ memoryId: id,+ });+ };++ for (const record of facts) {+ const relation = record.relation;+ if (!relation?.source?.id || !relation.target?.id) continue;+ pushEndpoint(relation.source);+ pushEndpoint(relation.target);+ edges.push({+ from: relation.source.id,+ to: relation.target.id,+ memoryId: record.id,+ label: relation.name,+ });+ }++ for (const record of extras) {+ pushEndpoint({+ id: record.id,+ label:+ (typeof record.metadata?.name === "string" && record.metadata.name) ||+ titleFromContent(record.content, record.id),+ types: record.categories,+ });+ }++ return { nodes, edges, kind: "knowledge" };+}++function buildSessionTreeGraph(records: MemoryRecord[]): MemoryGraphModel {+ const nodes: MemoryGraphNode[] = [];+ const edges: MemoryGraphEdge[] = [];+ const seen = new Set<string>();++ const pushNode = (node: MemoryGraphNode) => {+ if (seen.has(node.id)) return;+ seen.add(node.id);+ nodes.push(node);+ };++ for (const record of records) {+ const userKey = record.userId?.trim() || "";+ const sessionKey = record.sessionId?.trim() || "";+ const userId = userKey ? `user:${userKey}` : "user:unknown";+ pushNode({+ id: userId,+ type: "user",+ label: userKey || MEMORY_UNKNOWN_USER,+ });++ let parentId = userId;+ if (sessionKey) {+ const sessionId = `session:${sessionKey}`;+ pushNode({+ id: sessionId,+ type: "session",+ label: sessionKey,+ });+ edges.push({ from: userId, to: sessionId });+ parentId = sessionId;+ }++ const memoryId = `memory:${record.id}`;+ pushNode({+ id: memoryId,+ type: "memory",+ label: titleFromContent(record.content, record.id),+ memoryId: record.id,+ kind: classifyMemoryKind(record),+ });+ edges.push({ from: parentId, to: memoryId, memoryId: record.id });+ }++ return { nodes, edges };+}++function hashUnit(value: string): number {+ let hash = 2166136261;+ for (let index = 0; index < value.length; index += 1) {+ hash ^= value.charCodeAt(index);+ hash = Math.imul(hash, 16777619);+ }+ return (hash >>> 0) / 4294967295;+}++function layoutKnowledgeGraph(+ model: MemoryGraphModel,+ width: number,+ height: number+): LaidOutMemoryNode[] {+ if (model.nodes.length === 0) return [];+ const cx = width / 2;+ const cy = height / 2;+ const users = model.nodes.filter(+ (node) => node.entityType === "user" || node.type === "user"+ );+ const pinned = new Set(users.slice(0, 1).map((node) => node.id));+ const pos = new Map<string, { x: number; y: number }>();+ for (const node of model.nodes) {+ if (pinned.has(node.id)) {+ pos.set(node.id, { x: cx, y: cy });+ continue;+ }+ const angle = hashUnit(node.id) * Math.PI * 2;+ const radius = 90 + hashUnit(`${node.id}:r`) * 220;+ pos.set(node.id, {+ x: cx + radius * Math.cos(angle),+ y: cy + radius * Math.sin(angle),+ });+ }++ const ids = model.nodes.map((node) => node.id);+ const iterations = Math.min(90, 40 + ids.length);+ for (let iter = 0; iter < iterations; iter += 1) {+ const disp = new Map(ids.map((id) => [id, { x: 0, y: 0 }]));+ for (let i = 0; i < ids.length; i += 1) {+ for (let j = i + 1; j < ids.length; j += 1) {+ const a = pos.get(ids[i]);+ const b = pos.get(ids[j]);+ if (!a || !b) continue;+ let dx = a.x - b.x;+ let dy = a.y - b.y;+ const dist = Math.hypot(dx, dy) || 0.01;+ const force = 2800 / dist;+ dx /= dist;+ dy /= dist;+ const da = disp.get(ids[i]);+ const db = disp.get(ids[j]);+ if (da) {+ da.x += dx * force;+ da.y += dy * force;+ }+ if (db) {+ db.x -= dx * force;+ db.y -= dy * force;+ }+ }+ }+ for (const edge of model.edges) {+ const a = pos.get(edge.from);+ const b = pos.get(edge.to);+ if (!a || !b) continue;+ let dx = b.x - a.x;+ let dy = b.y - a.y;+ const dist = Math.hypot(dx, dy) || 0.01;+ const force = (dist - 118) * 0.06;+ dx /= dist;+ dy /= dist;+ const da = disp.get(edge.from);+ const db = disp.get(edge.to);+ if (da) {+ da.x += dx * force;+ da.y += dy * force;+ }+ if (db) {+ db.x -= dx * force;+ db.y -= dy * force;+ }+ }+ const cooling = 0.55 * (1 - iter / iterations);+ for (const id of ids) {+ if (pinned.has(id)) continue;+ const current = pos.get(id);+ const delta = disp.get(id);+ if (!current || !delta) continue;+ const mag = Math.hypot(delta.x, delta.y) || 1;+ const step = Math.min(mag, 28) * cooling;+ current.x += (delta.x / mag) * step;+ current.y += (delta.y / mag) * step;+ }+ }++ return model.nodes.map((node) => {+ const point = pos.get(node.id) || { x: cx, y: cy };+ return { ...node, x: point.x, y: point.y };+ });+}++/**+ * Superopen-style radial tree: roots near the origin, children on equal+ * angular slots, so memories fan out instead of collapsing into a cluster.+ */+export function layoutMemoryGraph(+ model: MemoryGraphModel,+ width = 800,+ height = 480+): LaidOutMemoryNode[] {+ if (model.kind === "knowledge") {+ return layoutKnowledgeGraph(model, width, height);+ }+ const cx = width / 2;+ const cy = height / 2;+ if (model.nodes.length === 0) return [];++ const byId = new Map(model.nodes.map((node) => [node.id, node]));+ const parentByChild = new Map<string, string>();+ const childrenByParent = new Map<string, string[]>();+ for (const edge of model.edges) {+ parentByChild.set(edge.to, edge.from);+ const siblings = childrenByParent.get(edge.from) || [];+ siblings.push(edge.to);+ childrenByParent.set(edge.from, siblings);+ }+ for (const siblings of Array.from(childrenByParent.values())) siblings.sort();++ const users = model.nodes.filter((node) => node.type === "user");+ const roots = model.nodes.filter((node) => !parentByChild.has(node.id));+ const startNodes = users.length ? users : roots;++ const leafCountCache = new Map<string, number>();+ const leafCount = (id: string): number => {+ const cached = leafCountCache.get(id);+ if (cached !== undefined) return cached;+ const kids = childrenByParent.get(id) || [];+ const count = kids.length ? kids.reduce((sum, kid) => sum + leafCount(kid), 0) : 1;+ leafCountCache.set(id, count);+ return count;+ };++ const totalLeaves = Math.max(+ startNodes.reduce((sum, node) => sum + leafCount(node.id), 0),+ 1+ );+ let maxDepth = 1;+ const walkDepth = (id: string, depth: number) => {+ maxDepth = Math.max(maxDepth, depth);+ for (const kid of childrenByParent.get(id) || []) walkDepth(kid, depth + 1);+ };+ const rootDepth = startNodes.length <= 1 ? 0 : 1;+ for (const node of startNodes) walkDepth(node.id, rootDepth);+ maxDepth = Math.max(maxDepth, 1);++ const radius = Math.max(180, Math.sqrt(totalLeaves) * 42);+ const step = radius / maxDepth;+ const slotAngle = (Math.PI * 2) / totalLeaves;+ const laid = new Map<string, LaidOutMemoryNode>();+ let cursor = 0;++ const polar = (r: number, angle: number) => ({+ x: cx + r * Math.cos(angle),+ y: cy + r * Math.sin(angle),+ });++ const place = (node: MemoryGraphNode, depth: number) => {+ const leaves = leafCount(node.id);+ const angle = (cursor + leaves / 2) * slotAngle;+ const pos = polar(depth === 0 ? 0 : depth * step, angle);+ laid.set(node.id, { ...node, x: pos.x, y: pos.y });+ const kids = childrenByParent.get(node.id) || [];+ for (const kidId of kids) {+ const kid = byId.get(kidId);+ if (kid) place(kid, depth + 1);+ }+ if (!kids.length) cursor += 1;+ };++ for (const node of startNodes) place(node, rootDepth);+ for (const node of model.nodes) {+ if (laid.has(node.id)) continue;+ const pos = polar(step, cursor * slotAngle);+ laid.set(node.id, { ...node, x: pos.x, y: pos.y });+ cursor += 1;+ }++ return Array.from(laid.values());+}++export function radialEdgePoints(+ from: { x: number; y: number },+ to: { x: number; y: number },+ origin: { x: number; y: number },+ segments = 8+): { x: number; y: number }[] {+ const r1 = Math.hypot(from.x - origin.x, from.y - origin.y);+ const r2 = Math.hypot(to.x - origin.x, to.y - origin.y);+ const a1 = Math.atan2(from.y - origin.y, from.x - origin.x);+ const a2 = Math.atan2(to.y - origin.y, to.x - origin.x);+ const startAngle = r1 < 1e-6 ? a2 : a1;+ let delta = a2 - startAngle;+ while (delta > Math.PI) delta -= Math.PI * 2;+ while (delta < -Math.PI) delta += Math.PI * 2;+ const points: { x: number; y: number }[] = [];+ for (let step = 0; step <= segments; step += 1) {+ const t = step / segments;+ const ease = t * t * (3 - 2 * t);+ const radius = r1 + (r2 - r1) * t;+ const angle = startAngle + delta * ease;+ points.push({+ x: origin.x + radius * Math.cos(angle),+ y: origin.y + radius * Math.sin(angle),+ });+ }+ return points;+}diff --git a/src/client/src/lib/platform/connectors/memory/http.ts b/src/client/src/lib/platform/connectors/memory/http.tsnew file mode 100644index 00000000..83c984f8--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/http.ts@@ -0,0 +1,68 @@+/**+ * Shared HTTP helpers for memory connector adapters.+ *+ * Outbound calls reuse the datasource SSRF-safe fetch and self-hosted+ * network toggles. API keys are decrypted from inline `enc:v1:` secretRef+ * values and never loaded from the ClickHouse vault.+ */++import {+ safeFetch,+ selfHostedNetworkOptions,+} from "../datasource/http/safe-fetch";+import {+ redactableSecretValues,+ resolveSourceSecret,+ type ResolvedSecret,+} from "../datasource/http/secret";+import {+ joinDatasourceRequestUrl,+ normalizeDatasourceEndpointUrl,+} from "../datasource/http/endpoint-url";+import type { MemorySourceDescriptor } from "./types";++export function memoryBaseUrl(+ descriptor: MemorySourceDescriptor,+ fallback: string+): string {+ const raw = String(descriptor.settings.url || "").trim();+ return normalizeDatasourceEndpointUrl(raw || fallback);+}++export async function memoryRequest<T>(+ descriptor: MemorySourceDescriptor,+ baseUrl: string,+ path: string,+ opts: {+ method?: string;+ headers?: Record<string, string>;+ body?: unknown;+ authHeaders: (secret: ResolvedSecret) => Record<string, string>;+ timeoutMs?: number;+ }+): Promise<T> {+ const secret = await resolveSourceSecret(+ descriptor.secretRef,+ undefined,+ descriptor.projectId,+ { clickHouseVault: false }+ );+ const network = selfHostedNetworkOptions(descriptor.settings);+ const url = joinDatasourceRequestUrl(baseUrl, path);+ return safeFetch<T>(url, {+ method: opts.method || "GET",+ headers: {+ Accept: "application/json",+ ...(opts.body ? { "Content-Type": "application/json" } : {}),+ ...opts.authHeaders(secret),+ ...opts.headers,+ },+ body: opts.body === undefined ? undefined : JSON.stringify(opts.body),+ timeoutMs: opts.timeoutMs ?? 15_000,+ allowHttp: network.allowHttp,+ allowPrivateNetwork: network.allowPrivateNetwork,+ redactValues: redactableSecretValues(secret),+ concurrencyKey: descriptor.id,+ retry: true,+ });+}diff --git a/src/client/src/lib/platform/connectors/memory/index.ts b/src/client/src/lib/platform/connectors/memory/index.tsnew file mode 100644index 00000000..09f42171--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/index.ts@@ -0,0 +1,91 @@+import {+ createMemoryAdapter,+ listMemoryTypeDescriptors,+} from "./registry";+import type { MemoryAdapter, MemorySourceDescriptor } from "./types";+import { registerConnectorType } from "../registry";+import type { ConnectorField, ConnectorInstanceDescriptor } from "../types";+import { connectorIconPath } from "../icons";+import { connectorDescription } from "../descriptions";++function parseSettings(settings: unknown): Record<string, unknown> {+ if (settings && typeof settings === "object" && !Array.isArray(settings)) {+ return settings as Record<string, unknown>;+ }+ if (typeof settings === "string") {+ try {+ const parsed = JSON.parse(settings);+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {+ return parsed as Record<string, unknown>;+ }+ } catch {+ return {};+ }+ }+ return {};+}++function fields(descriptor: ReturnType<typeof listMemoryTypeDescriptors>[number]): ConnectorField[] {+ return descriptor.configFields.map((field) => ({+ key: field.key,+ label: field.label,+ kind:+ field.kind === "switch"+ ? "boolean"+ : field.kind === "password"+ ? "password"+ : field.kind === "url"+ ? "url"+ : field.kind === "select"+ ? "select"+ : "text",+ secret: field.group === "credentials",+ placeholder: field.placeholder,+ options: field.options,+ defaultValue: field.defaultValue,+ }));+}++function toMemoryDescriptor(+ instance: ConnectorInstanceDescriptor+): MemorySourceDescriptor {+ return {+ type: instance.type,+ id: instance.id,+ settings: parseSettings(instance.settings),+ secretRef: instance.secretRef,+ projectId: instance.projectId ?? null,+ name: instance.name,+ environment: instance.environment,+ };+}++/** Register memory types in the generic connector registry. */+export function registerMemoryConnectorTypes(): void {+ for (const descriptor of listMemoryTypeDescriptors({ includeInternal: true })) {+ registerConnectorType({+ descriptor: {+ type: descriptor.type,+ category: "memory",+ displayName: descriptor.displayName,+ description:+ descriptor.description ||+ connectorDescription(descriptor.type, descriptor.displayName),+ icon: descriptor.icon || connectorIconPath(descriptor.type),+ scope: "project",+ configFields: fields(descriptor),+ capabilities: { ...descriptor.capabilities },+ internal: descriptor.internal,+ },+ create: (instance: ConnectorInstanceDescriptor) => {+ const adapter = createMemoryAdapter(toMemoryDescriptor(instance)) as+ | MemoryAdapter+ | undefined;+ if (!adapter) {+ throw new Error(`Connector adapter unavailable: ${instance.type}`);+ }+ return adapter;+ },+ });+ }+}diff --git a/src/client/src/lib/platform/connectors/memory/mem0/adapter.ts b/src/client/src/lib/platform/connectors/memory/mem0/adapter.tsnew file mode 100644index 00000000..74b4a32f--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/mem0/adapter.ts@@ -0,0 +1,556 @@+/**+ * Mem0 memory connector.+ *+ * Talks to the Mem0 Platform REST API (hosted `https://api.mem0.ai` or a+ * self-hosted compatible endpoint). Credentials stay in the OpenLIT vault+ * and are sent as `Authorization: Token <apiKey>`.+ */++import getMessage from "@/constants/messages";+import type { ConnectorHealthResult } from "../../types";+import type { ResolvedSecret } from "../../datasource/http/secret";+import { BaseMemoryAdapter } from "../base-adapter";+import { memoryHttpVendorFields, memoryPageFilters } from "../config-fields";+import { memoryBaseUrl, memoryRequest } from "../http";+import type {+ MemoryCapabilities,+ MemoryFeedback,+ MemoryFeedbackInput,+ MemoryFeedbackRating,+ MemoryFilterChoice,+ MemoryFilterOptions,+ MemoryHistoryEvent,+ MemoryListFilter,+ MemoryMessage,+ MemoryRecord,+ MemorySearchQuery,+ MemorySourceDescriptor,+ MemoryTypeDescriptor,+ MemoryUpdateInput,+ MemoryWriteInput,+} from "../types";+import { emptyMemoryFilters } from "../types";++const DEFAULT_URL = "https://api.mem0.ai";++const MEM0_CAPABILITIES = {+ add: true,+ search: true,+ get: true,+ list: true,+ update: true,+ delete: true,+ feedback: true,+} as const;++const MEM0_FEEDBACK_TO_RATING: Record<string, MemoryFeedbackRating> = {+ POSITIVE: "positive",+ NEGATIVE: "negative",+ VERY_NEGATIVE: "very_negative",+};++const RATING_TO_MEM0_FEEDBACK: Record<MemoryFeedbackRating, string> = {+ positive: "POSITIVE",+ negative: "NEGATIVE",+ very_negative: "VERY_NEGATIVE",+};++function asRecord(value: unknown): Record<string, unknown> {+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}++function stringValue(value: unknown): string | undefined {+ if (typeof value !== "string") return undefined;+ const trimmed = value.trim();+ return trimmed || undefined;+}++function stringList(value: unknown): string[] {+ if (!Array.isArray(value)) return [];+ return value+ .map((item) => stringValue(item))+ .filter((item): item is string => !!item);+}++function objectValue(value: unknown): Record<string, unknown> | undefined {+ const record = asRecord(value);+ return Object.keys(record).length ? record : undefined;+}++function booleanValue(value: unknown): boolean | undefined {+ return typeof value === "boolean" ? value : undefined;+}++function normalizeFeedback(raw: unknown): MemoryFeedback | undefined {+ const row = asRecord(raw);+ const nested = asRecord(row.data);+ const token = (+ stringValue(row.feedback) ||+ stringValue(nested.feedback) ||+ ""+ )+ .trim()+ .toUpperCase()+ .replace(/[\s-]+/g, "_");+ const rating = token ? MEM0_FEEDBACK_TO_RATING[token] : undefined;+ const reason =+ stringValue(row.feedback_reason) ||+ stringValue(row.feedbackReason) ||+ stringValue(nested.feedback_reason);+ if (!rating && !reason) return undefined;+ return {+ ...(rating ? { rating } : {}),+ ...(reason ? { reason } : {}),+ };+}++function normalizeMessages(value: unknown): MemoryMessage[] {+ if (!Array.isArray(value)) return [];+ const messages: MemoryMessage[] = [];+ for (const item of value) {+ const row = asRecord(item);+ const content = stringValue(row.content) || stringValue(row.text) || "";+ if (!content) continue;+ messages.push({+ role: stringValue(row.role) || "user",+ content,+ });+ }+ return messages;+}++function normalizeHistory(raw: unknown): MemoryHistoryEvent[] {+ const body = asRecord(raw);+ const rows = Array.isArray(raw)+ ? raw+ : Array.isArray(body.results)+ ? body.results+ : Array.isArray(body.history)+ ? body.history+ : [];+ const events: MemoryHistoryEvent[] = [];+ for (const item of rows) {+ const row = asRecord(item);+ const event = stringValue(row.event) || stringValue(row.action);+ const oldMemory = stringValue(row.old_memory) || stringValue(row.oldMemory);+ const newMemory = stringValue(row.new_memory) || stringValue(row.newMemory);+ const input = normalizeMessages(row.input || row.messages);+ if (!event && !oldMemory && !newMemory && !input.length) continue;+ events.push({+ id: stringValue(row.id) || stringValue(row.history_id),+ event: event || "UPDATE",+ input: input.length ? input : undefined,+ oldMemory,+ newMemory,+ createdAt: stringValue(row.created_at) || stringValue(row.updated_at),+ actorId: stringValue(row.actor_id) || stringValue(row.user_id),+ });+ }+ return events;+}++function inputFromHistory(history: MemoryHistoryEvent[]): MemoryMessage[] {+ for (const event of history) {+ if (event.input?.length) return event.input;+ }+ return [];+}++function normalizeRecord(+ raw: unknown,+ extras: { history?: MemoryHistoryEvent[] } = {}+): MemoryRecord | null {+ const row = asRecord(raw);+ const nested = asRecord(row.data);+ const id = stringValue(row.id) || stringValue(nested.id);+ const content =+ stringValue(row.memory) ||+ stringValue(row.text) ||+ stringValue(nested.memory) ||+ stringValue(nested.text) ||+ "";+ if (!id && !content) return null;+ const metadata = objectValue(row.metadata || nested.metadata);+ const categories = stringList(row.categories ?? nested.categories);+ const history = extras.history?.length+ ? extras.history+ : normalizeHistory(row.history ?? nested.history);+ const input = normalizeMessages(+ row.input ?? row.messages ?? nested.input ?? nested.messages+ );+ const resolvedInput = input.length ? input : inputFromHistory(history);+ const structuredAttributes = objectValue(+ row.structured_attributes ?? nested.structured_attributes+ );+ return {+ id: id || content,+ content,+ userId: stringValue(row.user_id) || stringValue(nested.user_id),+ agentId: stringValue(row.agent_id) || stringValue(nested.agent_id),+ sessionId:+ stringValue(row.run_id) ||+ stringValue(row.session_id) ||+ stringValue(nested.run_id) ||+ stringValue(nested.session_id),+ appId: stringValue(row.app_id) || stringValue(nested.app_id),+ metadata,+ categories: categories.length ? categories : undefined,+ input: resolvedInput.length ? resolvedInput : undefined,+ history: history.length ? history : undefined,+ score: typeof row.score === "number" ? row.score : undefined,+ createdAt: stringValue(row.created_at) || stringValue(nested.created_at),+ updatedAt: stringValue(row.updated_at) || stringValue(nested.updated_at),+ expirationDate:+ stringValue(row.expiration_date) || stringValue(nested.expiration_date),+ structuredAttributes,+ synthesized:+ booleanValue(row.synthesized) ?? booleanValue(nested.synthesized),+ lifecycleState:+ stringValue(row.lifecycle_state) || stringValue(nested.lifecycle_state),+ feedback: normalizeFeedback(row) || normalizeFeedback(nested),+ };+}++function normalizeList(raw: unknown): MemoryRecord[] {+ if (Array.isArray(raw)) {+ return raw+ .map((row) => normalizeRecord(row))+ .filter((row): row is MemoryRecord => !!row);+ }+ const body = asRecord(raw);+ const rows = body.results ?? body.memories ?? body.data;+ if (!Array.isArray(rows)) {+ const single = normalizeRecord(raw);+ return single ? [single] : [];+ }+ return rows+ .map((row) => normalizeRecord(row))+ .filter((row): row is MemoryRecord => !!row);+}++function uniqueChoices(choices: MemoryFilterChoice[]): MemoryFilterChoice[] {+ const seen = new Set<string>();+ const next: MemoryFilterChoice[] = [];+ for (const choice of choices) {+ if (!choice.id || seen.has(choice.id)) continue;+ seen.add(choice.id);+ next.push(choice);+ }+ return next.sort((a, b) => a.label.localeCompare(b.label));+}++function entityKind(row: Record<string, unknown>): "user" | "agent" | "session" | null {+ const type = (+ stringValue(row.type) ||+ stringValue(row.entity_type) ||+ stringValue(row.owner) ||+ "user"+ ).toLowerCase();+ if (type === "run" || type === "session") return "session";+ if (type === "agent") return "agent";+ if (type === "app") return null;+ return "user";+}++function normalizeEntities(raw: unknown): MemoryFilterOptions {+ const body = asRecord(raw);+ const rows = Array.isArray(raw)+ ? raw+ : Array.isArray(body.results)+ ? body.results+ : Array.isArray(body.entities)+ ? body.entities+ : [];+ const users: MemoryFilterChoice[] = [];+ const sessions: MemoryFilterChoice[] = [];+ const agents: MemoryFilterChoice[] = [];+ for (const item of rows) {+ const row = asRecord(item);+ const id =+ stringValue(row.name) ||+ stringValue(row.user_id) ||+ stringValue(row.agent_id) ||+ stringValue(row.run_id) ||+ stringValue(row.id);+ if (!id) continue;+ const kind = entityKind(row);+ if (!kind) continue;+ const choice = { id, label: stringValue(row.email) || id };+ if (kind === "agent") agents.push(choice);+ else if (kind === "session") sessions.push(choice);+ else users.push(choice);+ }+ return {+ users: uniqueChoices(users),+ sessions: uniqueChoices(sessions),+ agents: uniqueChoices(agents),+ };+}++function isRedirectBudgetError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error);+ return /maximum number of redirects|redirect loop/i.test(message);+}++function messagesForWrite(input: MemoryWriteInput) {+ if (input.messages?.length) return input.messages;+ if (input.content?.trim()) {+ return [{ role: "user", content: input.content.trim() }];+ }+ return [];+}++/**+ * Mem0 scopes memories with user_id / agent_id / run_id (OpenLIT sessionId → run_id).+ * Multiple entity filters AND together and often match nothing (e.g. user+agent when+ * memories were written with only user_id), so OR when more than one is set.+ */+function mem0EntityFilters(scope: {+ userId?: string;+ agentId?: string;+ sessionId?: string;+}): Record<string, unknown> | undefined {+ const parts: Record<string, string>[] = [];+ if (scope.userId) parts.push({ user_id: scope.userId });+ if (scope.agentId) parts.push({ agent_id: scope.agentId });+ if (scope.sessionId) parts.push({ run_id: scope.sessionId });+ if (!parts.length) return undefined;+ if (parts.length === 1) return parts[0];+ return { OR: parts };+}++export class Mem0Adapter extends BaseMemoryAdapter {+ readonly type = "mem0";++ private get baseUrl(): string {+ return memoryBaseUrl(this.descriptor, DEFAULT_URL);+ }++ private orgScope() {+ const orgId = stringValue(this.descriptor.settings.orgId);+ const projectId = stringValue(this.descriptor.settings.projectId);+ return {+ ...(orgId ? { org_id: orgId } : {}),+ ...(projectId ? { project_id: projectId } : {}),+ };+ }++ private request<T>(+ path: string,+ opts: {+ method?: string;+ body?: unknown;+ timeoutMs?: number;+ } = {}+ ) {+ return memoryRequest<T>(this.descriptor, this.baseUrl, path, {+ ...opts,+ authHeaders: (secret: ResolvedSecret): Record<string, string> => {+ const apiKey = secret.credentials.apiKey || secret.raw;+ return apiKey ? { Authorization: `Token ${apiKey}` } : {};+ },+ });+ }++ /**+ * Mem0 routes are slash-terminated. A 301/307 `Location` that is path-relative+ * (no leading slash) nests under the current resource and exhausts the+ * redirect budget. Retry once without the trailing slash so origin-relative+ * resolution can land on the canonical URL.+ */+ private requestSlash<T>(+ path: string,+ opts: {+ method?: string;+ body?: unknown;+ timeoutMs?: number;+ } = {}+ ): Promise<T> {+ return this.request<T>(path, opts).catch((error) => {+ if (!isRedirectBudgetError(error) || !path.endsWith("/")) throw error;+ return this.request<T>(path.replace(/\/+$/, ""), opts);+ });+ }++ capabilities(): MemoryCapabilities {+ return { ...MEM0_CAPABILITIES };+ }++ async healthCheck(): Promise<ConnectorHealthResult> {+ const started = Date.now();+ try {+ await this.request("v1/entities/", {+ timeoutMs: 10_000,+ });+ return { ok: true, latencyMs: Date.now() - started };+ } catch (error) {+ return {+ ok: false,+ latencyMs: Date.now() - started,+ message: String((error as Error)?.message || error),+ };+ }+ }++ async add(input: MemoryWriteInput): Promise<MemoryRecord[]> {+ const messages = messagesForWrite(input);+ if (!messages.length) {+ throw new Error(getMessage().MEMORY_CONNECTOR_CONTENT_REQUIRED);+ }+ const body = await this.request("v1/memories/", {+ method: "POST",+ body: {+ messages,+ user_id: input.userId,+ agent_id: input.agentId,+ run_id: input.sessionId,+ metadata: input.metadata,+ ...this.orgScope(),+ },+ });+ return normalizeList(body);+ }++ async search(query: MemorySearchQuery): Promise<MemoryRecord[]> {+ const q = query.query.trim();+ if (!q) throw new Error(getMessage().MEMORY_CONNECTOR_QUERY_REQUIRED);+ const body = await this.request("v2/memories/search/", {+ method: "POST",+ body: {+ query: q,+ filters: mem0EntityFilters(query),+ top_k: query.limit || 10,+ threshold: query.threshold,+ ...this.orgScope(),+ },+ });+ return normalizeList(body);+ }++ async get(id: string): Promise<MemoryRecord | null> {+ const encoded = encodeURIComponent(id);+ const body = await this.requestSlash(`v1/memories/${encoded}/`);+ let history: MemoryHistoryEvent[] = [];+ try {+ history = normalizeHistory(+ await this.requestSlash(`v1/memories/${encoded}/history/`)+ );+ } catch {+ history = [];+ }+ return normalizeRecord(body, { history });+ }++ async list(filter: MemoryListFilter): Promise<MemoryRecord[]> {+ if (!filter.userId && !filter.agentId && !filter.sessionId) {+ throw new Error(getMessage().MEMORY_CONNECTOR_FILTER_REQUIRED);+ }+ const pageSize = filter.limit || 25;+ const body = await this.request(+ `v3/memories/?page=1&page_size=${encodeURIComponent(String(pageSize))}`,+ {+ method: "POST",+ body: {+ filters: mem0EntityFilters(filter),+ ...this.orgScope(),+ },+ }+ );+ return normalizeList(body);+ }++ async listFilters(): Promise<MemoryFilterOptions> {+ const params = new URLSearchParams();+ params.set("page_size", "100");+ const scope = this.orgScope();+ if (scope.org_id) params.set("org_id", scope.org_id);+ if (scope.project_id) params.set("project_id", scope.project_id);+ try {+ const body = await this.request(`v1/entities/?${params.toString()}`);+ return normalizeEntities(body);+ } catch {+ return emptyMemoryFilters();+ }+ }++ async update(id: string, input: MemoryUpdateInput): Promise<MemoryRecord> {+ const body = await this.requestSlash(`v1/memories/${encodeURIComponent(id)}/`, {+ method: "PUT",+ body: {+ text: input.content,+ metadata: input.metadata,+ },+ });+ return (+ normalizeRecord(body) || {+ id,+ content: input.content,+ metadata: input.metadata,+ }+ );+ }++ async delete(id: string): Promise<void> {+ await this.requestSlash(`v1/memories/${encodeURIComponent(id)}/`, {+ method: "DELETE",+ });+ }++ async feedback(id: string, input: MemoryFeedbackInput): Promise<MemoryFeedback> {+ const memoryId = id.trim();+ if (!memoryId) throw new Error(getMessage().MEMORY_DETAIL_NOT_FOUND);+ const body = await this.requestSlash("v1/feedback/", {+ method: "POST",+ body: {+ memory_id: memoryId,+ feedback: input.rating ? RATING_TO_MEM0_FEEDBACK[input.rating] : null,+ feedback_reason: input.reason?.trim() || null,+ },+ });+ return (+ normalizeFeedback(body) ||+ (input.rating || input.reason?.trim()+ ? {+ ...(input.rating ? { rating: input.rating } : {}),+ ...(input.reason?.trim() ? { reason: input.reason.trim() } : {}),+ }+ : {})+ );+ }+}++export const mem0AdapterFactory = {+ type: "mem0",+ create: (descriptor: MemorySourceDescriptor) => new Mem0Adapter(descriptor),+ describe: (): MemoryTypeDescriptor => ({+ type: "mem0",+ displayName: "Mem0",+ description: getMessage().MEMORY_CONNECTOR_MEM0_DESCRIPTION,+ capabilities: { ...MEM0_CAPABILITIES },+ configFields: [+ ...memoryHttpVendorFields({ placeholder: DEFAULT_URL }),+ {+ key: "orgId",+ label: getMessage().MEMORY_CONNECTOR_FIELD_ORG_ID,+ kind: "text",+ group: "settings",+ },+ {+ key: "projectId",+ label: getMessage().MEMORY_CONNECTOR_FIELD_PROJECT_ID,+ kind: "text",+ group: "settings",+ },+ ],+ filterFields: memoryPageFilters([+ "userId",+ { key: "sessionId", label: getMessage().MEMORY_RUN_FILTER },+ "agentId",+ ]),+ authStyle: "api-key",+ authHelp: getMessage().MEMORY_CONNECTOR_AUTH_HELP_MEM0,+ docsUrl: "https://docs.mem0.ai/api-reference",+ }),+};diff --git a/src/client/src/lib/platform/connectors/memory/port-link.ts b/src/client/src/lib/platform/connectors/memory/port-link.tsnew file mode 100644index 00000000..0540b4df--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/port-link.ts@@ -0,0 +1,92 @@+/**+ * Durable source links for memories copied between connectors.+ */++import type { MemoryPortLink, MemoryRecord } from "./types";++export function memoryContentFingerprint(+ content: string,+ userId?: string+): string {+ const key = `${content.trim().toLowerCase()}\n${String(userId || "").trim()}`;+ let hash = 0;+ for (let i = 0; i < key.length; i += 1) {+ hash = (hash * 31 + key.charCodeAt(i)) | 0;+ }+ return Math.abs(hash).toString(16);+}++function asRecord(value: unknown): Record<string, unknown> {+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}++function stringValue(value: unknown): string | undefined {+ if (typeof value !== "string") return undefined;+ const trimmed = value.trim();+ return trimmed || undefined;+}++export function parseMemoryPortLink(+ metadata?: Record<string, unknown> | null+): MemoryPortLink | undefined {+ const nested = asRecord(asRecord(asRecord(metadata).openlit).port);+ const raw = Object.keys(nested).length ? nested : asRecord(metadata).openlitPort;+ const sourceConnectorId = stringValue(asRecord(raw).sourceConnectorId);+ const sourceMemoryId = stringValue(asRecord(raw).sourceMemoryId);+ if (!sourceConnectorId || !sourceMemoryId) return undefined;+ return {+ sourceConnectorId,+ sourceConnectorType: stringValue(asRecord(raw).sourceConnectorType),+ sourceConnectorName: stringValue(asRecord(raw).sourceConnectorName),+ sourceMemoryId,+ originConnectorId: stringValue(asRecord(raw).originConnectorId),+ originMemoryId: stringValue(asRecord(raw).originMemoryId),+ copiedAt: stringValue(asRecord(raw).copiedAt) || "",+ contentFingerprint: stringValue(asRecord(raw).contentFingerprint) || "",+ destMemoryId: stringValue(asRecord(raw).destMemoryId),+ };+}++export function attachMemoryPorts<T extends MemoryRecord>(+ records: T[],+ stored: MemoryPortLink[] = []+): T[] {+ return records.map((record) => {+ const fromMetadata = parseMemoryPortLink(record.metadata);+ const fingerprint = memoryContentFingerprint(record.content, record.userId);+ const fromStore = stored.find(+ (link) =>+ link.destMemoryId === record.id ||+ (!!link.contentFingerprint && link.contentFingerprint === fingerprint)+ );+ const port = fromMetadata || fromStore;+ if (!port) return record;+ return { ...record, port };+ });+}++export function memoryPortMetadata(+ link: MemoryPortLink,+ existing?: Record<string, unknown>+): Record<string, unknown> {+ const current = { ...(existing || {}) };+ const openlit = asRecord(current.openlit);+ return {+ ...current,+ openlit: {+ ...openlit,+ port: {+ sourceConnectorId: link.sourceConnectorId,+ sourceConnectorType: link.sourceConnectorType,+ sourceConnectorName: link.sourceConnectorName,+ sourceMemoryId: link.sourceMemoryId,+ originConnectorId: link.originConnectorId,+ originMemoryId: link.originMemoryId,+ copiedAt: link.copiedAt,+ contentFingerprint: link.contentFingerprint,+ },+ },+ };+}diff --git a/src/client/src/lib/platform/connectors/memory/port.ts b/src/client/src/lib/platform/connectors/memory/port.tsnew file mode 100644index 00000000..209da89f--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/port.ts@@ -0,0 +1,163 @@+/**+ * Copy memories from one connector to another.+ *+ * Writes destination records with `metadata.openlit.port` and persists the+ * same link on the destination ConnectorInstance.+ */++import {+ MEMORY_ADD_UNSUPPORTED,+ MEMORY_CONNECTOR_CONTENT_REQUIRED,+ MEMORY_CONNECTOR_NOT_FOUND,+ MEMORY_COPY_EMPTY,+ MEMORY_COPY_SAME_CONNECTOR,+ MEMORY_COPY_TOO_MANY,+} from "@/constants/messages/en";+import { getMemoryTypeDescriptor } from "./registry";+import {+ listMemoryConnectors,+ memoryConnectorId,+ recordMemoryPortLinks,+} from "./crud";+import { queryProjectMemories, type MemoryListItem } from "./read";+import { addProjectMemories } from "./write";+import {+ memoryContentFingerprint,+ memoryPortMetadata,+ parseMemoryPortLink,+} from "./port-link";+import type { MemoryPortLink } from "./types";++export const MEMORY_COPY_MAX = 50;++export type { MemoryPortLink } from "./types";+export {+ attachMemoryPorts,+ memoryContentFingerprint,+ memoryPortMetadata,+ parseMemoryPortLink,+} from "./port-link";++export interface MemoryCopyInput {+ sourceConnectorId?: string;+ targetConnectorId?: string;+ memoryIds?: string[];+ userId?: string;+ agentId?: string;+ sessionId?: string;+ query?: string;+ targetUserId?: string;+ targetAgentId?: string;+ targetSessionId?: string;+}++export interface MemoryCopyFailure {+ id: string;+ message: string;+}++export interface MemoryCopyResult {+ source: { id: string; name: string; type: string } | null;+ target: { id: string; name: string; type: string } | null;+ copied: number;+ failed: MemoryCopyFailure[];+ memories: MemoryListItem[];+}++function trim(value?: string): string | undefined {+ const next = String(value || "").trim();+ return next || undefined;+}++export async function copyProjectMemories(+ input: MemoryCopyInput+): Promise<MemoryCopyResult> {+ const sourceId = memoryConnectorId(String(input.sourceConnectorId || ""));+ const targetId = memoryConnectorId(String(input.targetConnectorId || ""));+ if (!sourceId.startsWith("memory:") || !targetId.startsWith("memory:")) {+ throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ }+ if (sourceId === targetId) throw new Error(MEMORY_COPY_SAME_CONNECTOR);++ const connectors = await listMemoryConnectors();+ const source = connectors.find((item) => item.id === sourceId);+ const target = connectors.find((item) => item.id === targetId);+ if (!source || !target) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);++ const targetCapabilities = getMemoryTypeDescriptor(String(target.type))?.capabilities;+ if (!targetCapabilities?.add) throw new Error(MEMORY_ADD_UNSUPPORTED);++ const listed = await queryProjectMemories({+ connectorId: sourceId,+ userId: trim(input.userId),+ agentId: trim(input.agentId),+ sessionId: trim(input.sessionId),+ query: trim(input.query),+ limit: MEMORY_COPY_MAX,+ });+ const wanted = new Set(+ (input.memoryIds || []).map((id) => String(id || "").trim()).filter(Boolean)+ );+ let selected = listed.memories.filter(+ (memory) => !memory.graphOnly && memory.content?.trim()+ );+ if (wanted.size) {+ selected = selected.filter((memory) => wanted.has(memory.id));+ }+ if (!selected.length) throw new Error(MEMORY_COPY_EMPTY);+ if (selected.length > MEMORY_COPY_MAX) throw new Error(MEMORY_COPY_TOO_MANY);++ const copiedAt = new Date().toISOString();+ const created: MemoryListItem[] = [];+ const failed: MemoryCopyFailure[] = [];+ const stored: MemoryPortLink[] = [];++ for (const memory of selected) {+ const fingerprint = memoryContentFingerprint(memory.content, memory.userId);+ const prior = parseMemoryPortLink(memory.metadata);+ const link: MemoryPortLink = {+ sourceConnectorId: sourceId,+ sourceConnectorType: String(source.type || ""),+ sourceConnectorName: String(source.name || ""),+ sourceMemoryId: memory.id,+ originConnectorId: prior?.originConnectorId || prior?.sourceConnectorId,+ originMemoryId: prior?.originMemoryId || prior?.sourceMemoryId,+ copiedAt,+ contentFingerprint: fingerprint,+ };+ try {+ const result = await addProjectMemories({+ connectorId: targetId,+ content: memory.content,+ messages: memory.input,+ userId: trim(input.targetUserId) || memory.userId,+ agentId: trim(input.targetAgentId) || memory.agentId,+ sessionId: trim(input.targetSessionId) || memory.sessionId,+ metadata: memoryPortMetadata(link, memory.metadata),+ });+ const dest = result.memories[0];+ if (!dest) throw new Error(MEMORY_CONNECTOR_CONTENT_REQUIRED);+ const withPort: MemoryListItem = {+ ...dest,+ port: { ...link, destMemoryId: dest.id },+ };+ created.push(withPort);+ stored.push(withPort.port!);+ } catch (error) {+ failed.push({+ id: memory.id,+ message: error instanceof Error ? error.message : String(error),+ });+ }+ }++ if (stored.length) await recordMemoryPortLinks(targetId, stored);++ return {+ source: { id: String(source.id), name: String(source.name), type: String(source.type) },+ target: { id: String(target.id), name: String(target.name), type: String(target.type) },+ copied: created.length,+ failed,+ memories: created,+ };+}diff --git a/src/client/src/lib/platform/connectors/memory/read.ts b/src/client/src/lib/platform/connectors/memory/read.tsnew file mode 100644index 00000000..4ec3499c--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/read.ts@@ -0,0 +1,535 @@+/**+ * Project-scoped memory reads for the Memory page and Otter tools.+ */++import {+ getMemoryRuntime,+ listMemoryConnectors,+ memoryConnectorId,+ readMemoryPortLinks,+ readRememberedMemoryFilters,+ rememberMemoryFilters,+ emptyRememberedMemoryFilters,+ type RememberedMemoryFilters,+} from "./crud";+import {+ buildMemoryGraph,+ classifyMemoryKind,+ emptyMemoryStats,+ summarizeMemoryStats,+ type MemoryGraphModel,+ type MemoryKind,+ type MemoryStats,+} from "./graph";+import {+ emptyMemoryFilters,+ UnsupportedMemoryCapabilityError,+ type MemoryAdapter,+ type MemoryCapabilities,+ type MemoryFeedback,+ type MemoryFeedbackInput,+ type MemoryFeedbackRating,+ type MemoryFilterChoice,+ type MemoryFilterField,+ type MemoryFilterOptions,+ type MemoryQueryHint,+ type MemoryRecord,+ isMemoryFeedbackRating,+} from "./types";+import { getMemoryTypeDescriptor } from "./registry";+import { attachMemoryPorts } from "./port-link";+import {+ DATA_SOURCE_SECRET_DECRYPT_FAILED,+ DATA_SOURCE_SECRET_NOT_FOUND,+ DATA_SOURCE_SECRET_UNAVAILABLE,+ 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";+import getMessage from "@/constants/messages";+import { SourceResponseError } from "../datasource/http/safe-fetch";++export interface MemoryQueryInput {+ connectorId?: string;+ userId?: string;+ agentId?: string;+ sessionId?: string;+ query?: string;+ limit?: number;+}++export interface MemoryListItem extends MemoryRecord {+ kind: MemoryKind;+}++export type MemoryConnectorOption = Awaited<+ ReturnType<typeof listMemoryConnectors>+>[number] & {+ capabilities?: MemoryCapabilities | null;+ filterFields?: MemoryFilterField[];+};++export interface MemoryQueryResult {+ connectors: MemoryConnectorOption[];+ connector: MemoryConnectorOption | null;+ capabilities: MemoryCapabilities | null;+ memories: MemoryListItem[];+ stats: MemoryStats;+ graph: MemoryGraphModel;+ filters: MemoryFilterOptions;+ filterFields: MemoryFilterField[];+ hint?: MemoryQueryHint;+}++export interface MemoryDetailResult {+ connector: MemoryQueryResult["connector"];+ capabilities: MemoryCapabilities | null;+ memory: MemoryListItem | null;+ hint?: "get_unsupported";+}++export interface MemoryFeedbackResult {+ connector: MemoryQueryResult["connector"];+ capabilities: MemoryCapabilities | null;+ feedback: MemoryFeedback;+ memory: MemoryListItem | null;+}++const DEFAULT_LIMIT = 50;+const MAX_LIMIT = 100;+const FEEDBACK_REASON_MAX = 1000;++function trim(value?: string): string | undefined {+ const next = String(value || "").trim();+ return next || undefined;+}++function clampLimit(value?: number): number {+ if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_LIMIT;+ return Math.min(MAX_LIMIT, Math.max(1, Math.floor(value)));+}++function fallbackFilterFields(): MemoryFilterField[] {+ const messages = getMessage();+ return [+ { key: "userId", label: messages.MEMORY_USER_FILTER, allowCustom: true },+ { key: "sessionId", label: messages.MEMORY_SESSION_FILTER, allowCustom: true },+ { key: "agentId", label: messages.MEMORY_AGENT_FILTER, allowCustom: true },+ ];+}++function resolveFilterFields(type: string): MemoryFilterField[] {+ const described = getMemoryTypeDescriptor(type);+ if (described && described.filterFields !== undefined) {+ return described.filterFields;+ }+ return fallbackFilterFields();+}++function uniqueChoices(choices: MemoryFilterChoice[]): MemoryFilterChoice[] {+ const seen = new Set<string>();+ const next: MemoryFilterChoice[] = [];+ for (const choice of choices) {+ if (!choice.id || seen.has(choice.id)) continue;+ seen.add(choice.id);+ next.push(choice);+ }+ return next.sort((a, b) => a.label.localeCompare(b.label));+}++function mergeFilters(+ base: MemoryFilterOptions,+ extra: MemoryFilterOptions+): MemoryFilterOptions {+ return {+ users: uniqueChoices([...base.users, ...extra.users]),+ sessions: uniqueChoices([...base.sessions, ...extra.sessions]),+ agents: uniqueChoices([...base.agents, ...extra.agents]),+ };+}++function filtersFromScope(filter: {+ userId?: string;+ sessionId?: string;+ agentId?: string;+}): MemoryFilterOptions {+ return {+ users: filter.userId ? [{ id: filter.userId, label: filter.userId }] : [],+ sessions: filter.sessionId+ ? [+ {+ id: filter.sessionId,+ label: filter.sessionId,+ userId: filter.userId,+ },+ ]+ : [],+ agents: filter.agentId ? [{ id: filter.agentId, label: filter.agentId }] : [],+ };+}++function rememberedAsFilters(+ remembered: RememberedMemoryFilters+): MemoryFilterOptions {+ return {+ users: uniqueChoices(+ remembered.users.map((id) => ({ id, label: id }))+ ),+ sessions: uniqueChoices(+ remembered.sessions.map((id) => ({ id, label: id }))+ ),+ agents: uniqueChoices(+ remembered.agents.map((id) => ({ id, label: id }))+ ),+ };+}++function knownFilters(+ base: MemoryFilterOptions,+ remembered: RememberedMemoryFilters,+ filter: { userId?: string; sessionId?: string; agentId?: string },+ records: MemoryRecord[] = []+): MemoryFilterOptions {+ return mergeFilters(+ mergeFilters(+ mergeFilters(base, rememberedAsFilters(remembered)),+ filtersFromScope(filter)+ ),+ filtersFromMemories(records)+ );+}++function idsToRemember(+ filter: { userId?: string; sessionId?: string; agentId?: string },+ records: MemoryRecord[]+): RememberedMemoryFilters {+ return {+ users: [+ ...(filter.userId ? [filter.userId] : []),+ ...records.map((record) => record.userId?.trim() || ""),+ ].filter(Boolean),+ sessions: [+ ...(filter.sessionId ? [filter.sessionId] : []),+ ...records.map((record) => record.sessionId?.trim() || ""),+ ].filter(Boolean),+ agents: [+ ...(filter.agentId ? [filter.agentId] : []),+ ...records.map((record) => record.agentId?.trim() || ""),+ ].filter(Boolean),+ };+}++function filtersFromMemories(records: MemoryRecord[]): MemoryFilterOptions {+ return {+ users: uniqueChoices(+ records+ .map((record) => record.userId?.trim())+ .filter((id): id is string => !!id)+ .map((id) => ({ id, label: id }))+ ),+ sessions: uniqueChoices(+ records+ .filter((record) => record.sessionId?.trim())+ .map((record) => ({+ id: String(record.sessionId).trim(),+ label: String(record.sessionId).trim(),+ userId: record.userId?.trim(),+ }))+ ),+ agents: uniqueChoices(+ records+ .map((record) => record.agentId?.trim())+ .filter((id): id is string => !!id)+ .map((id) => ({ id, label: id }))+ ),+ };+}++function vendorStatus(error: unknown): number | undefined {+ if (error instanceof SourceResponseError) return error.status;+ const status = (error as { status?: unknown })?.status;+ return typeof status === "number" ? status : undefined;+}++function hintFromListError(error: unknown): MemoryQueryHint {+ const message = error instanceof Error ? error.message : String(error);+ if (message === MEMORY_CONNECTOR_SESSION_REQUIRED) return "session_required";+ if (message === MEMORY_CONNECTOR_FILTER_REQUIRED) return "filter_required";+ if (/one of the filters:.*is required/i.test(message)) return "filter_required";+ const status = vendorStatus(error);+ if (+ status === 401 ||+ status === 403 ||+ message === DATA_SOURCE_SECRET_DECRYPT_FAILED ||+ message === DATA_SOURCE_SECRET_NOT_FOUND ||+ message === DATA_SOURCE_SECRET_UNAVAILABLE ||+ /invalid.*api key|authentication_error|authentication failed/i.test(message)+ ) {+ return "auth_failed";+ }+ return "unavailable";+}++async function safeListFilters(adapter: MemoryAdapter): Promise<MemoryFilterOptions> {+ try {+ if (typeof adapter.listFilters !== "function") return emptyMemoryFilters();+ const filters = await adapter.listFilters();+ return mergeFilters(emptyMemoryFilters(), filters || emptyMemoryFilters());+ } catch {+ return emptyMemoryFilters();+ }+}++function emptyResult(partial: {+ connectors: MemoryQueryResult["connectors"];+ connector: MemoryQueryResult["connector"];+ capabilities: MemoryCapabilities | null;+ filters?: MemoryFilterOptions;+ filterFields?: MemoryFilterField[];+ hint?: MemoryQueryHint;+}): MemoryQueryResult {+ return {+ connectors: partial.connectors,+ connector: partial.connector,+ capabilities: partial.capabilities,+ memories: [],+ stats: emptyMemoryStats(),+ graph: { nodes: [], edges: [] },+ filters: partial.filters || emptyMemoryFilters(),+ filterFields: partial.filterFields || [],+ hint: partial.hint,+ };+}++export async function queryProjectMemories(+ input: MemoryQueryInput = {}+): Promise<MemoryQueryResult> {+ const connectors = await listMemoryConnectors();+ if (!connectors.length) {+ return emptyResult({+ connectors: [],+ connector: null,+ capabilities: null,+ });+ }++ let connector = connectors[0];+ if (input.connectorId) {+ const requested = memoryConnectorId(input.connectorId);+ const match = connectors.find((item) => item.id === requested);+ if (!match) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ connector = match;+ }++ const { adapter } = await getMemoryRuntime(String(connector.id));+ const capabilities = adapter.capabilities();+ const filterFields = resolveFilterFields(String(connector.type || ""));+ const limit = clampLimit(input.limit);+ const filter = {+ userId: trim(input.userId),+ agentId: trim(input.agentId),+ sessionId: trim(input.sessionId),+ limit,+ };+ const query = trim(input.query);+ const filters = await safeListFilters(adapter);+ const remembered = await readRememberedMemoryFilters(String(connector.id)).catch(+ () => emptyRememberedMemoryFilters()+ );++ let records: MemoryRecord[] = [];+ if (query) {+ if (!capabilities.search) {+ throw new Error(MEMORY_CONNECTOR_QUERY_REQUIRED);+ }+ try {+ records = await adapter.search({ query, ...filter, limit });+ } catch (error) {+ return emptyResult({+ connectors,+ connector,+ capabilities,+ filters: knownFilters(filters, remembered, filter),+ filterFields,+ hint: hintFromListError(error),+ });+ }+ } else {+ try {+ records = await adapter.list(filter);+ } catch (error) {+ return emptyResult({+ connectors,+ connector,+ capabilities,+ filters: knownFilters(filters, remembered, filter),+ filterFields,+ hint: hintFromListError(error),+ });+ }+ }++ await rememberMemoryFilters(+ String(connector.id),+ idsToRemember(filter, records)+ ).catch(() => undefined);++ const memories = attachMemoryPorts(+ records+ .filter((record) => !record.graphOnly)+ .map((record) => ({+ ...record,+ kind: classifyMemoryKind(record),+ })),+ await readMemoryPortLinks(String(connector.id)).catch(() => [])+ );++ const described = getMemoryTypeDescriptor(String(connector.type || ""));+ const connectorsWithCopyMeta = connectors.map((item) => {+ const type = getMemoryTypeDescriptor(String(item.type || ""));+ return {+ ...item,+ capabilities: type?.capabilities || null,+ filterFields: type?.filterFields || [],+ };+ });++ return {+ connectors: connectorsWithCopyMeta,+ connector: {+ ...connector,+ capabilities: described?.capabilities || null,+ filterFields: described?.filterFields || [],+ },+ capabilities,+ memories,+ stats: summarizeMemoryStats(memories),+ graph: buildMemoryGraph(records),+ filters: knownFilters(filters, remembered, filter, records),+ filterFields,+ };+}++export async function resolveProjectMemoryAdapter(connectorId?: string) {+ const connectors = await listMemoryConnectors();+ if (!connectors.length) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);++ let connector = connectors[0];+ if (connectorId) {+ const requested = memoryConnectorId(connectorId);+ const match = connectors.find((item) => item.id === requested);+ if (!match) throw new Error(MEMORY_CONNECTOR_NOT_FOUND);+ connector = match;+ }++ const { adapter } = await getMemoryRuntime(String(connector.id));+ return {+ connector,+ adapter,+ capabilities: adapter.capabilities(),+ };+}++export function asMemoryListItem(record: MemoryRecord): MemoryListItem {+ return {+ ...record,+ kind: classifyMemoryKind(record),+ };+}++export async function getProjectMemory(input: {+ id: string;+ connectorId?: string;+}): Promise<MemoryDetailResult> {+ const id = trim(input.id);+ if (!id) throw new Error(MEMORY_DETAIL_NOT_FOUND);++ const { connector, adapter, capabilities } = await resolveProjectMemoryAdapter(+ input.connectorId+ );+ if (!capabilities.get) {+ return { connector, capabilities, memory: null, hint: "get_unsupported" };+ }++ let record: MemoryRecord | null;+ try {+ record = await adapter.get(id);+ } catch (error) {+ if (error instanceof UnsupportedMemoryCapabilityError) {+ return { connector, capabilities, memory: null, hint: "get_unsupported" };+ }+ throw error;+ }+ if (!record) throw new Error(MEMORY_DETAIL_NOT_FOUND);++ const [withPort] = attachMemoryPorts(+ [record],+ await readMemoryPortLinks(String(connector.id)).catch(() => [])+ );++ return {+ connector,+ capabilities,+ memory: asMemoryListItem(withPort),+ };+}++export async function submitProjectMemoryFeedback(input: {+ id: string;+ connectorId?: string;+ rating: MemoryFeedbackRating | null;+ reason?: string | null;+}): Promise<MemoryFeedbackResult> {+ const id = trim(input.id);+ if (!id) throw new Error(MEMORY_DETAIL_NOT_FOUND);+ if (input.rating !== null && !isMemoryFeedbackRating(input.rating)) {+ throw new Error(MEMORY_FEEDBACK_INVALID);+ }+ const reason = input.reason == null ? undefined : String(input.reason).trim();+ if (reason && reason.length > FEEDBACK_REASON_MAX) {+ throw new Error(MEMORY_FEEDBACK_REASON_TOO_LONG);+ }++ const { connector, adapter, capabilities } = await resolveProjectMemoryAdapter(+ input.connectorId+ );+ if (!capabilities.feedback) {+ throw new Error(MEMORY_DETAIL_FEEDBACK_UNSUPPORTED);+ }++ const payload: MemoryFeedbackInput = {+ rating: input.rating,+ reason: reason || null,+ };+ let feedback: MemoryFeedback;+ try {+ feedback = await adapter.feedback(id, payload);+ } catch (error) {+ if (error instanceof UnsupportedMemoryCapabilityError) {+ throw new Error(MEMORY_DETAIL_FEEDBACK_UNSUPPORTED);+ }+ throw error;+ }++ let memory: MemoryListItem | null = null;+ if (capabilities.get) {+ try {+ const record = await adapter.get(id);+ if (record) {+ memory = asMemoryListItem({+ ...record,+ feedback: record.feedback || feedback,+ });+ }+ } catch {+ memory = null;+ }+ }++ return { connector, capabilities, feedback, memory };+}diff --git a/src/client/src/lib/platform/connectors/memory/registry.ts b/src/client/src/lib/platform/connectors/memory/registry.tsnew file mode 100644index 00000000..03aaf108--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/registry.ts@@ -0,0 +1,77 @@+/**+ * Memory connector adapter registry (CE).+ *+ * Holds adapter factories keyed by connector type. `bootstrap.ts` registers+ * Claude, Mem0, and Zep. Extra private factories can still be contributed+ * through the neutral `getExternalMemoryAdapters()` hook without an+ * `@/ee/**` import.+ */++import { getExternalMemoryAdapters } from "./enterprise";+import type {+ MemoryAdapter,+ MemoryAdapterFactory,+ MemorySourceDescriptor,+ MemoryTypeDescriptor,+} from "./types";++const factories = new Map<string, MemoryAdapterFactory>();+let externalLoaded = false;++export function registerMemoryAdapterFactory(factory: MemoryAdapterFactory): void {+ factories.set(factory.type, factory);+}++function ensureExternalLoaded(): void {+ if (externalLoaded) return;+ externalLoaded = true;+ for (const factory of getExternalMemoryAdapters()) {+ if (!factories.has(factory.type)) {+ factories.set(factory.type, factory);+ }+ }+}++export function hasMemoryAdapterFactory(type: string): boolean {+ ensureExternalLoaded();+ return factories.has(type);+}++export function getMemoryAdapterFactory(+ type: string+): MemoryAdapterFactory | undefined {+ ensureExternalLoaded();+ return factories.get(type);+}++export function getMemoryTypeDescriptor(+ type: string+): MemoryTypeDescriptor | undefined {+ ensureExternalLoaded();+ return factories.get(type)?.describe();+}++export function listMemoryTypeDescriptors(+ _opts: { includeInternal?: boolean } = {}+): MemoryTypeDescriptor[] {+ ensureExternalLoaded();+ const out: MemoryTypeDescriptor[] = [];+ for (const factory of Array.from(factories.values())) {+ const descriptor = factory.describe();+ if (descriptor.internal) continue;+ out.push(descriptor);+ }+ return out;+}++export function createMemoryAdapter(+ descriptor: MemorySourceDescriptor+): MemoryAdapter | undefined {+ const factory = getMemoryAdapterFactory(descriptor.type);+ return factory?.create(descriptor);+}++export function __resetMemoryRegistryForTests(): void {+ factories.clear();+ externalLoaded = false;+}diff --git a/src/client/src/lib/platform/connectors/memory/types.ts b/src/client/src/lib/platform/connectors/memory/types.tsnew file mode 100644index 00000000..e76d2b28--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/types.ts@@ -0,0 +1,232 @@+/**+ * Memory connector contract.+ *+ * Memory adapters are the category-specific runtime behind `category: "memory"`+ * connector instances. Vendors implement only the operations their+ * `capabilities()` advertise; the rest throw `UnsupportedMemoryCapabilityError`+ * so product surfaces can gate honestly instead of guessing.+ */++import type { ConnectorHealthResult, ConnectorRuntime } from "../types";+import type { AuthStyle, FieldDef } from "../datasource/types";++export interface MemoryCapabilities {+ add: boolean;+ search: boolean;+ get: boolean;+ list: boolean;+ update: boolean;+ delete: boolean;+ feedback: boolean;+}++export const MEMORY_FEEDBACK_RATINGS = [+ "positive",+ "negative",+ "very_negative",+] as const;++export const MEMORY_CONTENT_MAX = 20_000;+export const MEMORY_METADATA_JSON_MAX = 4_000;++export type MemoryFeedbackRating = (typeof MEMORY_FEEDBACK_RATINGS)[number];++export interface MemoryFeedback {+ rating?: MemoryFeedbackRating;+ reason?: string;+}++export interface MemoryFeedbackInput {+ rating: MemoryFeedbackRating | null;+ reason?: string | null;+}++export function isMemoryFeedbackRating(+ value: unknown+): value is MemoryFeedbackRating {+ return MEMORY_FEEDBACK_RATINGS.includes(value as MemoryFeedbackRating);+}++export interface MemoryMessage {+ role: string;+ content: string;+}++export interface MemoryHistoryEvent {+ id?: string;+ event: string;+ input?: MemoryMessage[];+ oldMemory?: string;+ newMemory?: string;+ createdAt?: string;+ actorId?: string;+}++export interface MemoryRecord {+ id: string;+ content: string;+ userId?: string;+ agentId?: string;+ sessionId?: string;+ appId?: string;+ metadata?: Record<string, unknown>;+ categories?: string[];+ input?: MemoryMessage[];+ history?: MemoryHistoryEvent[];+ score?: number;+ createdAt?: string;+ updatedAt?: string;+ expirationDate?: string;+ structuredAttributes?: Record<string, unknown>;+ synthesized?: boolean;+ lifecycleState?: string;+ feedback?: MemoryFeedback;+ graphOnly?: boolean;+ relation?: {+ source: MemoryGraphEndpoint;+ target: MemoryGraphEndpoint;+ name?: string;+ };+ port?: MemoryPortLink;+}++export interface MemoryPortLink {+ sourceConnectorId: string;+ sourceConnectorType?: string;+ sourceConnectorName?: string;+ sourceMemoryId: string;+ originConnectorId?: string;+ originMemoryId?: string;+ copiedAt: string;+ contentFingerprint: string;+ destMemoryId?: string;+}++export interface MemoryGraphEndpoint {+ id: string;+ label: string;+ types?: string[];+}++export interface MemoryWriteInput {+ content?: string;+ messages?: MemoryMessage[];+ userId?: string;+ agentId?: string;+ sessionId?: string;+ metadata?: Record<string, unknown>;+}++export interface MemoryUpdateInput {+ content: string;+ metadata?: Record<string, unknown>;+}++export interface MemorySearchQuery {+ query: string;+ userId?: string;+ agentId?: string;+ sessionId?: string;+ limit?: number;+ threshold?: number;+}++export interface MemoryListFilter {+ userId?: string;+ agentId?: string;+ sessionId?: string;+ limit?: number;+}++export interface MemoryFilterChoice {+ id: string;+ label: string;+ userId?: string;+}++export type MemoryFilterKey = "userId" | "sessionId" | "agentId";++/** Memory page filter declared by a vendor `describe()`. */+export interface MemoryFilterField {+ key: MemoryFilterKey;+ label: string;+ required?: boolean;+ /** Required when creating a memory, even if listing allows it to be empty. */+ writeRequired?: boolean;+ allowCustom?: boolean;+}++export interface MemoryFilterOptions {+ users: MemoryFilterChoice[];+ sessions: MemoryFilterChoice[];+ agents: MemoryFilterChoice[];+}++export type MemoryQueryHint =+ | "session_required"+ | "filter_required"+ | "auth_failed"+ | "unavailable";++export function emptyMemoryFilters(): MemoryFilterOptions {+ return { users: [], sessions: [], agents: [] };+}++export interface MemorySourceDescriptor {+ type: string;+ id: string;+ settings: Record<string, unknown>;+ secretRef?: string | null;+ projectId?: string | null;+ name: string;+ environment?: string;+}++export interface MemoryTypeDescriptor {+ type: string;+ displayName: string;+ description?: string;+ internal?: boolean;+ icon?: string;+ capabilities: MemoryCapabilities;+ configFields: FieldDef[];+ /** Memory page filters for this vendor. Empty means no user/session/agent bar. */+ filterFields?: MemoryFilterField[];+ authStyle: AuthStyle;+ authHelp?: string;+ docsUrl?: string;+}++export interface MemoryAdapter extends ConnectorRuntime {+ readonly type: string;+ capabilities(): MemoryCapabilities;+ healthCheck(): Promise<ConnectorHealthResult>;+ add(input: MemoryWriteInput): Promise<MemoryRecord[]>;+ search(query: MemorySearchQuery): Promise<MemoryRecord[]>;+ get(id: string): Promise<MemoryRecord | null>;+ list(filter: MemoryListFilter): Promise<MemoryRecord[]>;+ listFilters(): Promise<MemoryFilterOptions>;+ update(id: string, input: MemoryUpdateInput): Promise<MemoryRecord>;+ delete(id: string): Promise<void>;+ feedback(id: string, input: MemoryFeedbackInput): Promise<MemoryFeedback>;+}++export interface MemoryAdapterFactory {+ type: string;+ create(descriptor: MemorySourceDescriptor): MemoryAdapter;+ describe(): MemoryTypeDescriptor;+}++export class UnsupportedMemoryCapabilityError extends Error {+ readonly capability: string;+ readonly sourceType: string;+ constructor(sourceType: string, capability: string, message?: string) {+ super(+ message ||+ `Capability "${capability}" is not supported by memory connector "${sourceType}".`+ );+ this.name = "UnsupportedMemoryCapabilityError";+ this.capability = capability;+ this.sourceType = sourceType;+ }+}diff --git a/src/client/src/lib/platform/connectors/memory/write.ts b/src/client/src/lib/platform/connectors/memory/write.tsnew file mode 100644index 00000000..e663e6fa--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/write.ts@@ -0,0 +1,225 @@+/**+ * Project-scoped memory writes for the Memory page, API routes, and Otter tools.+ */++import {+ asMemoryListItem,+ resolveProjectMemoryAdapter,+ type MemoryListItem,+ type MemoryQueryResult,+} from "./read";+import { rememberMemoryFilters } from "./crud";+import {+ UnsupportedMemoryCapabilityError,+ type MemoryCapabilities,+ type MemoryMessage,+ type MemoryRecord,+ type MemoryUpdateInput,+ type MemoryWriteInput,+ MEMORY_CONTENT_MAX,+ MEMORY_METADATA_JSON_MAX,+} from "./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";++export interface MemoryWriteResult {+ connector: MemoryQueryResult["connector"];+ capabilities: MemoryCapabilities | null;+ memories: MemoryListItem[];+}++export interface MemoryUpdateResult {+ connector: MemoryQueryResult["connector"];+ capabilities: MemoryCapabilities | null;+ memory: MemoryListItem;+}++export interface MemoryDeleteResult {+ connector: MemoryQueryResult["connector"];+ capabilities: MemoryCapabilities | null;+ ok: true;+}++function trim(value?: string): string | undefined {+ const next = String(value || "").trim();+ return next || undefined;+}++function requireContent(content?: string): string {+ const next = trim(content);+ if (!next) throw new Error(MEMORY_CONNECTOR_CONTENT_REQUIRED);+ if (next.length > MEMORY_CONTENT_MAX) throw new Error(MEMORY_CONTENT_TOO_LONG);+ return next;+}++export function parseMemoryMessages(value: unknown): MemoryMessage[] | undefined {+ if (value == null) return undefined;+ if (!Array.isArray(value)) throw new Error(MEMORY_CONNECTOR_CONTENT_REQUIRED);+ const messages: MemoryMessage[] = [];+ for (const item of value) {+ if (!item || typeof item !== "object" || Array.isArray(item)) {+ throw new Error(MEMORY_CONNECTOR_CONTENT_REQUIRED);+ }+ const row = item as Record<string, unknown>;+ const role = String(row.role || "").trim();+ const content = String(row.content || "").trim();+ if (!role && !content) continue;+ if (!role || !content) throw new Error(MEMORY_CONNECTOR_CONTENT_REQUIRED);+ if (role.length > 64 || content.length > MEMORY_CONTENT_MAX) {+ throw new Error(MEMORY_CONTENT_TOO_LONG);+ }+ messages.push({ role, content });+ }+ return messages.length ? messages : undefined;+}++export function parseMemoryMetadata(+ value: unknown+): Record<string, unknown> | undefined {+ if (value == null) return undefined;+ if (typeof value !== "object" || Array.isArray(value)) {+ throw new Error(MEMORY_INVALID_METADATA);+ }+ const encoded = JSON.stringify(value);+ if (encoded.length > MEMORY_METADATA_JSON_MAX) {+ throw new Error(MEMORY_INVALID_METADATA);+ }+ return value as Record<string, unknown>;+}++function writeInput(input: {+ content?: string;+ messages?: MemoryMessage[];+ userId?: string;+ agentId?: string;+ sessionId?: string;+ metadata?: Record<string, unknown>;+}): MemoryWriteInput {+ const content = trim(input.content);+ if (content && content.length > MEMORY_CONTENT_MAX) {+ throw new Error(MEMORY_CONTENT_TOO_LONG);+ }+ const messages = input.messages?.length ? input.messages : undefined;+ if (!content && !messages?.length) {+ throw new Error(MEMORY_CONNECTOR_CONTENT_REQUIRED);+ }+ return {+ content,+ messages,+ userId: trim(input.userId),+ agentId: trim(input.agentId),+ sessionId: trim(input.sessionId),+ metadata: input.metadata,+ };+}++export async function addProjectMemories(input: {+ connectorId?: string;+ content?: string;+ messages?: MemoryMessage[];+ userId?: string;+ agentId?: string;+ sessionId?: string;+ metadata?: Record<string, unknown>;+}): Promise<MemoryWriteResult> {+ const payload = writeInput(input);+ const { connector, adapter, capabilities } = await resolveProjectMemoryAdapter(+ input.connectorId+ );+ if (!capabilities.add) throw new Error(MEMORY_ADD_UNSUPPORTED);++ let records: MemoryRecord[];+ try {+ records = await adapter.add(payload);+ } catch (error) {+ if (error instanceof UnsupportedMemoryCapabilityError) {+ throw new Error(MEMORY_ADD_UNSUPPORTED);+ }+ throw error;+ }++ await rememberMemoryFilters(String(connector.id), {+ users: [+ payload.userId,+ ...records.map((record) => record.userId?.trim() || ""),+ ].filter((id): id is string => !!id),+ sessions: [+ payload.sessionId,+ ...records.map((record) => record.sessionId?.trim() || ""),+ ].filter((id): id is string => !!id),+ agents: [+ payload.agentId,+ ...records.map((record) => record.agentId?.trim() || ""),+ ].filter((id): id is string => !!id),+ }).catch(() => undefined);++ return {+ connector,+ capabilities,+ memories: records.map(asMemoryListItem),+ };+}++export async function updateProjectMemory(input: {+ id: string;+ connectorId?: string;+ content: string;+ metadata?: Record<string, unknown>;+}): Promise<MemoryUpdateResult> {+ const id = trim(input.id);+ if (!id) throw new Error(MEMORY_DETAIL_NOT_FOUND);+ const payload: MemoryUpdateInput = {+ content: requireContent(input.content),+ metadata: input.metadata,+ };+ const { connector, adapter, capabilities } = await resolveProjectMemoryAdapter(+ input.connectorId+ );+ if (!capabilities.update) throw new Error(MEMORY_EDIT_UNSUPPORTED);++ let record: MemoryRecord;+ try {+ record = await adapter.update(id, payload);+ } catch (error) {+ if (error instanceof UnsupportedMemoryCapabilityError) {+ throw new Error(MEMORY_EDIT_UNSUPPORTED);+ }+ throw error;+ }++ return {+ connector,+ capabilities,+ memory: asMemoryListItem(record),+ };+}++export async function deleteProjectMemory(input: {+ id: string;+ connectorId?: string;+}): Promise<MemoryDeleteResult> {+ const id = trim(input.id);+ if (!id) throw new Error(MEMORY_DETAIL_NOT_FOUND);+ const { connector, adapter, capabilities } = await resolveProjectMemoryAdapter(+ input.connectorId+ );+ if (!capabilities.delete) throw new Error(MEMORY_DELETE_UNSUPPORTED);++ try {+ await adapter.delete(id);+ } catch (error) {+ if (error instanceof UnsupportedMemoryCapabilityError) {+ throw new Error(MEMORY_DELETE_UNSUPPORTED);+ }+ throw error;+ }++ return { connector, capabilities, ok: true };+}diff --git a/src/client/src/lib/platform/connectors/memory/zep/adapter.ts b/src/client/src/lib/platform/connectors/memory/zep/adapter.tsnew file mode 100644index 00000000..97edf33e--- /dev/null+++ b/src/client/src/lib/platform/connectors/memory/zep/adapter.ts@@ -0,0 +1,721 @@+/**+ * Zep memory connector.+ *+ * Talks to the Zep Cloud REST API (hosted `https://api.getzep.com` or a+ * self-hosted compatible endpoint). User graph facts, session memory, search,+ * and per-fact get are supported. Delete targets graph edges/nodes, not the+ * whole session.+ */++import getMessage from "@/constants/messages";+import type { ConnectorHealthResult } from "../../types";+import type { ResolvedSecret } from "../../datasource/http/secret";+import { BaseMemoryAdapter } from "../base-adapter";+import { memoryHttpVendorFields, memoryPageFilters } from "../config-fields";+import { memoryBaseUrl, memoryRequest } from "../http";+import type {+ MemoryCapabilities,+ MemoryFilterChoice,+ MemoryFilterOptions,+ MemoryHistoryEvent,+ MemoryListFilter,+ MemoryMessage,+ MemoryRecord,+ MemorySearchQuery,+ MemorySourceDescriptor,+ MemoryTypeDescriptor,+ MemoryWriteInput,+} from "../types";+import { emptyMemoryFilters } from "../types";++const DEFAULT_URL = "https://api.getzep.com";+const EDGE_PAGE_SIZE = 50;+const MAX_EDGE_PAGES = 5;+const MAX_EPISODES = 8;++const ZEP_CAPABILITIES: MemoryCapabilities = {+ add: true,+ search: true,+ get: true,+ list: true,+ update: false,+ delete: true,+ feedback: false,+};++function asRecord(value: unknown): Record<string, unknown> {+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}++function stringValue(value: unknown): string | undefined {+ if (typeof value === "number" && Number.isFinite(value)) return String(value);+ if (typeof value !== "string") return undefined;+ const trimmed = value.trim();+ return trimmed || undefined;+}++function stringList(value: unknown): string[] {+ if (!Array.isArray(value)) {+ const one = stringValue(value);+ return one ? [one] : [];+ }+ return value+ .map((item) => stringValue(item))+ .filter((item): item is string => !!item);+}++function objectValue(value: unknown): Record<string, unknown> | undefined {+ const record = asRecord(value);+ return Object.keys(record).length ? record : undefined;+}++function requireScope(filter: { userId?: string; sessionId?: string }): void {+ if (!filter.userId?.trim() && !filter.sessionId?.trim()) {+ throw new Error(getMessage().MEMORY_CONNECTOR_FILTER_REQUIRED);+ }+}++function uniqueChoices(choices: MemoryFilterChoice[]): MemoryFilterChoice[] {+ const seen = new Set<string>();+ const next: MemoryFilterChoice[] = [];+ for (const choice of choices) {+ if (!choice.id || seen.has(choice.id)) continue;+ seen.add(choice.id);+ next.push(choice);+ }+ return next.sort((a, b) => a.label.localeCompare(b.label));+}++function rowsFrom(raw: unknown, keys: string[]): unknown[] {+ if (Array.isArray(raw)) return raw;+ const body = asRecord(raw);+ for (const key of keys) {+ const value = body[key];+ if (Array.isArray(value)) return value;+ }+ return [];+}++function normalizeMessages(value: unknown): MemoryMessage[] {+ if (!Array.isArray(value)) return [];+ const messages: MemoryMessage[] = [];+ for (const item of value) {+ const row = asRecord(item);+ const content = stringValue(row.content) || stringValue(row.text) || "";+ if (!content) continue;+ messages.push({+ role: stringValue(row.role) || "user",+ content,+ });+ }+ return messages;+}++function normalizeRecord(+ raw: unknown,+ ctx: { userId?: string; sessionId?: string; input?: MemoryMessage[] } = {}+): MemoryRecord | null {+ const row = asRecord(raw);+ const nested = asRecord(row.data);+ const id =+ stringValue(row.uuid) ||+ stringValue(row.uuid_) ||+ stringValue(row.fact_uuid) ||+ stringValue(row.id) ||+ stringValue(nested.uuid) ||+ stringValue(nested.id);+ const fact = stringValue(row.fact) || stringValue(nested.fact);+ const content =+ fact ||+ stringValue(row.summary) ||+ stringValue(row.content) ||+ stringValue(row.text) ||+ stringValue(nested.summary) ||+ stringValue(nested.content) ||+ "";+ if (!id && !content) return null;+ const relationName = fact ? stringValue(row.name) : undefined;+ const labels = [+ ...stringList(row.labels ?? nested.labels),+ ...(relationName ? [relationName] : []),+ ];+ const episodes = stringList(row.episodes ?? nested.episodes);+ const metadata = {+ ...asRecord(row.metadata),+ ...asRecord(nested.metadata),+ ...(stringValue(row.source_node_name)+ ? { source: row.source_node_name }+ : {}),+ ...(stringValue(row.target_node_name)+ ? { target: row.target_node_name }+ : {}),+ ...(stringValue(row.valid_at) ? { valid_at: row.valid_at } : {}),+ ...(stringValue(row.scope) ? { scope: row.scope } : {}),+ ...(!fact && stringValue(row.name) ? { name: row.name } : {}),+ ...(fact ? { memory_type: "temporal" } : {}),+ ...(!fact && (stringValue(row.summary) || labels.includes("user"))+ ? { memory_type: "profile" }+ : {}),+ ...(episodes.length ? { episodes } : {}),+ };+ const attributes = objectValue(row.attributes ?? nested.attributes);+ const input = ctx.input?.length+ ? ctx.input+ : normalizeMessages(row.messages ?? nested.messages);+ const history = historyFromEdge(row, nested, content);+ const sourceId =+ stringValue(row.source_node_uuid) ||+ stringValue(nested.source_node_uuid) ||+ stringValue(row.source_node_name) ||+ stringValue(nested.source_node_name);+ const targetId =+ stringValue(row.target_node_uuid) ||+ stringValue(nested.target_node_uuid) ||+ stringValue(row.target_node_name) ||+ stringValue(nested.target_node_name);+ const sourceTypes = stringList(+ row.source_node_labels ?? nested.source_node_labels+ );+ const targetTypes = stringList(+ row.target_node_labels ?? nested.target_node_labels+ );+ return {+ id: id || content,+ content,+ userId: stringValue(row.user_id) || stringValue(nested.user_id) || ctx.userId,+ sessionId:+ stringValue(row.session_id) ||+ stringValue(nested.session_id) ||+ stringValue(row.thread_id) ||+ ctx.sessionId,+ metadata: Object.keys(metadata).length ? metadata : undefined,+ categories: labels.length ? labels : undefined,+ input: input.length ? input : undefined,+ history: history.length ? history : undefined,+ structuredAttributes: attributes,+ relation:+ sourceId && targetId+ ? {+ source: {+ id: sourceId,+ label:+ stringValue(row.source_node_name) ||+ stringValue(nested.source_node_name) ||+ sourceId,+ types: sourceTypes.length ? sourceTypes : undefined,+ },+ target: {+ id: targetId,+ label:+ stringValue(row.target_node_name) ||+ stringValue(nested.target_node_name) ||+ targetId,+ types: targetTypes.length ? targetTypes : undefined,+ },+ name: relationName,+ }+ : undefined,+ score:+ typeof row.score === "number"+ ? row.score+ : typeof row.relevance === "number"+ ? row.relevance+ : undefined,+ createdAt:+ stringValue(row.created_at) ||+ stringValue(nested.created_at) ||+ stringValue(row.valid_at),+ updatedAt: stringValue(row.updated_at) || stringValue(nested.updated_at),+ expirationDate:+ stringValue(row.expired_at) ||+ stringValue(row.invalid_at) ||+ stringValue(nested.expired_at),+ };+}++function dedupeRecords(records: MemoryRecord[]): MemoryRecord[] {+ const seen = new Set<string>();+ const next: MemoryRecord[] = [];+ for (const record of records) {+ if (seen.has(record.id)) continue;+ seen.add(record.id);+ next.push(record);+ }+ return next;+}++function normalizeGraph(+ raw: unknown,+ ctx: { userId?: string; sessionId?: string; input?: MemoryMessage[] } = {}+): MemoryRecord[] {+ const body = asRecord(raw);+ const groups = [+ body.edges,+ body.facts,+ body.relevant_facts,+ body.nodes,+ body.results,+ body.episodes,+ ];+ const records: MemoryRecord[] = [];+ for (const group of groups) {+ if (!Array.isArray(group)) continue;+ for (const row of group) {+ const record = normalizeRecord(row, ctx);+ if (record) records.push(record);+ }+ }+ if (records.length) return dedupeRecords(records);+ if (Array.isArray(raw)) {+ return dedupeRecords(+ raw+ .map((row) => normalizeRecord(row, ctx))+ .filter((row): row is MemoryRecord => !!row)+ );+ }+ const single = normalizeRecord(raw, ctx);+ return single ? [single] : [];+}++function normalizeSessionMemory(+ raw: unknown,+ sessionId: string,+ userId?: string+): MemoryRecord[] {+ const body = asRecord(raw);+ const messages = normalizeMessages(body.messages);+ const facts = normalizeGraph(raw, { sessionId, userId, input: messages });+ if (facts.length) return facts;+ const context = stringValue(body.context);+ if (context) {+ return [+ {+ id: sessionId,+ content: context,+ sessionId,+ userId,+ metadata: { memory_type: "summary" },+ input: messages.length ? messages : undefined,+ },+ ];+ }+ return messages.map((message, index) => ({+ id: `${sessionId}:${index}`,+ content: message.content,+ sessionId,+ userId,+ metadata: { role: message.role, memory_type: "temporal" },+ }));+}++function historyFromEdge(+ row: Record<string, unknown>,+ nested: Record<string, unknown>,+ content: string+): MemoryHistoryEvent[] {+ const created = stringValue(row.created_at) || stringValue(nested.created_at);+ const valid = stringValue(row.valid_at) || stringValue(nested.valid_at);+ const invalid = stringValue(row.invalid_at) || stringValue(nested.invalid_at);+ const expired = stringValue(row.expired_at) || stringValue(nested.expired_at);+ const events: MemoryHistoryEvent[] = [];+ if (created) {+ events.push({ event: "ADD", newMemory: content, createdAt: created });+ }+ if (valid && valid !== created) {+ events.push({ event: "UPDATE", newMemory: content, createdAt: valid });+ }+ if (invalid) {+ events.push({ event: "DELETE", oldMemory: content, createdAt: invalid });+ } else if (expired) {+ events.push({ event: "DELETE", oldMemory: content, createdAt: expired });+ }+ return events;+}++function normalizeUsers(raw: unknown): MemoryFilterChoice[] {+ return uniqueChoices(+ rowsFrom(raw, ["users", "results"]).map((item) => {+ const row = asRecord(item);+ const id = stringValue(row.user_id) || stringValue(row.uuid);+ const name = [stringValue(row.first_name), stringValue(row.last_name)]+ .filter(Boolean)+ .join(" ");+ return {+ id: id || "",+ label: stringValue(row.email) || name || id || "",+ };+ })+ );+}++function normalizeSessions(raw: unknown): MemoryFilterChoice[] {+ return uniqueChoices(+ rowsFrom(raw, ["sessions", "threads", "results"]).map((item) => {+ const row = asRecord(item);+ const id =+ stringValue(row.thread_id) ||+ stringValue(row.session_id) ||+ stringValue(row.uuid);+ return {+ id: id || "",+ label: id || "",+ userId: stringValue(row.user_id),+ };+ })+ );+}++export class ZepAdapter extends BaseMemoryAdapter {+ readonly type = "zep";++ private get baseUrl(): string {+ return memoryBaseUrl(this.descriptor, DEFAULT_URL);+ }++ private request<T>(+ path: string,+ opts: {+ method?: string;+ body?: unknown;+ timeoutMs?: number;+ } = {}+ ) {+ return memoryRequest<T>(this.descriptor, this.baseUrl, path, {+ ...opts,+ authHeaders: (secret: ResolvedSecret): Record<string, string> => {+ const apiKey = secret.credentials.apiKey || secret.raw;+ return apiKey ? { Authorization: `Api-Key ${apiKey}` } : {};+ },+ });+ }++ private async requestFirst<T>(+ paths: string[],+ opts: {+ method?: string;+ body?: unknown;+ timeoutMs?: number;+ } = {}+ ): Promise<T> {+ let last: unknown;+ for (const path of paths) {+ try {+ return await this.request<T>(path, opts);+ } catch (error) {+ last = error;+ }+ }+ throw last instanceof Error ? last : new Error(String(last));+ }++ private async firstRecord(+ attempts: Array<() => Promise<unknown>>+ ): Promise<MemoryRecord | null> {+ for (const attempt of attempts) {+ try {+ const records = normalizeGraph(await attempt());+ if (records[0]) return records[0];+ } catch {+ continue;+ }+ }+ return null;+ }++ capabilities(): MemoryCapabilities {+ return { ...ZEP_CAPABILITIES };+ }++ async healthCheck(): Promise<ConnectorHealthResult> {+ const started = Date.now();+ try {+ await this.requestFirst(+ ["api/v2/users-ordered?pageSize=1&pageNumber=1", "api/v2/users"],+ { timeoutMs: 10_000 }+ );+ return { ok: true, latencyMs: Date.now() - started };+ } catch (error) {+ return {+ ok: false,+ latencyMs: Date.now() - started,+ message: String((error as Error)?.message || error),+ };+ }+ }++ async add(input: MemoryWriteInput): Promise<MemoryRecord[]> {+ const sessionId = input.sessionId?.trim();+ if (!sessionId) throw new Error(getMessage().MEMORY_CONNECTOR_SESSION_REQUIRED);+ const messages = input.messages?.length+ ? input.messages+ : input.content?.trim()+ ? [{ role: "user", content: input.content.trim() }]+ : [];+ if (!messages.length) {+ throw new Error(getMessage().MEMORY_CONNECTOR_CONTENT_REQUIRED);+ }+ const encoded = encodeURIComponent(sessionId);+ const body = await this.requestFirst(+ [`api/v2/threads/${encoded}/messages`, `api/v2/sessions/${encoded}/memory`],+ {+ method: "POST",+ body: {+ messages,+ return_context: true,+ ...(input.userId ? { user_id: input.userId } : {}),+ ...(input.metadata ? { metadata: input.metadata } : {}),+ },+ }+ );+ const records = normalizeSessionMemory(body, sessionId, input.userId);+ return records.length+ ? records+ : [+ {+ id: sessionId,+ content: messages.map((item) => item.content).join("\n"),+ sessionId,+ userId: input.userId,+ input: messages,+ },+ ];+ }++ async search(query: MemorySearchQuery): Promise<MemoryRecord[]> {+ const q = query.query.trim();+ if (!q) throw new Error(getMessage().MEMORY_CONNECTOR_QUERY_REQUIRED);+ requireScope(query);+ const sessionId = query.sessionId?.trim();+ const userId = query.userId?.trim();+ if (sessionId) {+ try {+ const body = await this.request(+ `api/v2/sessions/${encodeURIComponent(sessionId)}/search`,+ {+ method: "POST",+ body: { text: q, limit: query.limit || 10 },+ }+ );+ return normalizeGraph(body, { sessionId, userId }).slice(+ 0,+ query.limit || 10+ );+ } catch (error) {+ if (!userId) throw error;+ }+ }+ const body = await this.request("api/v2/graph/search", {+ method: "POST",+ body: {+ user_id: userId,+ query: q,+ limit: query.limit || 10,+ },+ });+ return normalizeGraph(body, { userId, sessionId }).slice(0, query.limit || 10);+ }++ async get(id: string): Promise<MemoryRecord | null> {+ const trimmed = id.trim();+ if (!trimmed) return null;+ const encoded = encodeURIComponent(trimmed);+ const graph = await this.firstRecord([+ () => this.request(`api/v2/graph/edge/${encoded}`),+ () => this.request(`api/v2/graph/node/${encoded}`),+ ]);+ if (graph) return this.enrichRecord(graph);+ try {+ const body = await this.requestFirst([+ `api/v2/threads/${encoded}/context`,+ `api/v2/sessions/${encoded}/memory`,+ ]);+ return normalizeSessionMemory(body, trimmed)[0] || null;+ } catch {+ return null;+ }+ }++ async list(filter: MemoryListFilter): Promise<MemoryRecord[]> {+ requireScope(filter);+ const sessionId = filter.sessionId?.trim();+ let userId = filter.userId?.trim();+ const limit = filter.limit || 25;+ if (!userId && sessionId) {+ userId = await this.userIdForThread(sessionId);+ }+ if (userId) {+ return (await this.listUserGraph(userId, limit)).slice(0, limit);+ }+ if (!sessionId) return [];+ const encoded = encodeURIComponent(sessionId);+ const body = await this.requestFirst(+ [`api/v2/threads/${encoded}/context`, `api/v2/sessions/${encoded}/memory`]+ );+ return normalizeSessionMemory(body, sessionId).slice(0, limit);+ }++ async listFilters(): Promise<MemoryFilterOptions> {+ const filters = emptyMemoryFilters();+ try {+ filters.users = normalizeUsers(+ await this.requestFirst([+ "api/v2/users-ordered?pageSize=100&pageNumber=1",+ "api/v2/users",+ ])+ );+ } catch {+ filters.users = [];+ }+ try {+ filters.sessions = normalizeSessions(+ await this.requestFirst([+ "api/v2/threads?page_size=100&page_number=1",+ "api/v2/sessions",+ ])+ );+ } catch {+ filters.sessions = [];+ }+ return filters;+ }++ async delete(id: string): Promise<void> {+ const trimmed = id.trim();+ if (!trimmed) return;+ try {+ await this.request(`api/v2/graph/edge/${encodeURIComponent(trimmed)}`, {+ method: "DELETE",+ });+ return;+ } catch {+ await this.request(`api/v2/graph/node/${encodeURIComponent(trimmed)}`, {+ method: "DELETE",+ });+ }+ }++ private async listUserGraph(+ userId: string,+ limit: number+ ): Promise<MemoryRecord[]> {+ const collected: MemoryRecord[] = [];+ let uuidCursor: string | undefined;+ const pageSize = Math.min(EDGE_PAGE_SIZE, Math.max(limit, 1));+ for (let page = 0; page < MAX_EDGE_PAGES && collected.length < limit; page++) {+ try {+ const edges = await this.request(+ `api/v2/graph/edge/user/${encodeURIComponent(userId)}`,+ {+ method: "POST",+ body: {+ limit: Math.min(pageSize, limit - collected.length),+ ...(uuidCursor ? { uuid_cursor: uuidCursor } : {}),+ },+ }+ );+ const records = normalizeGraph(edges, { userId });+ if (!records.length) break;+ collected.push(...records);+ if (records.length < pageSize) break;+ uuidCursor = records[records.length - 1]?.id;+ if (!uuidCursor) break;+ } catch {+ break;+ }+ }+ if (collected.length) {+ const facts = dedupeRecords(collected).slice(0, limit);+ const factIds = new Set(facts.map((record) => record.id));+ try {+ const nodes = await this.request(+ `api/v2/graph/node/user/${encodeURIComponent(userId)}`,+ {+ method: "POST",+ body: { limit: 100 },+ }+ );+ const extras = normalizeGraph(nodes, { userId })+ .filter((record) => !factIds.has(record.id))+ .map((record) => ({ ...record, graphOnly: true }));+ return [...facts, ...extras];+ } catch {+ return facts;+ }+ }+ const nodes = await this.request(+ `api/v2/graph/node/user/${encodeURIComponent(userId)}`,+ {+ method: "POST",+ body: { limit },+ }+ );+ return normalizeGraph(nodes, { userId });+ }++ private async userIdForThread(sessionId: string): Promise<string | undefined> {+ const encoded = encodeURIComponent(sessionId);+ try {+ const body = asRecord(+ await this.requestFirst([+ `api/v2/threads/${encoded}/messages?limit=1`,+ `api/v2/sessions/${encoded}`,+ ])+ );+ return (+ stringValue(body.user_id) ||+ stringValue(asRecord(body.session).user_id)+ );+ } catch {+ return undefined;+ }+ }++ private async enrichRecord(record: MemoryRecord): Promise<MemoryRecord> {+ if (record.input?.length) return record;+ const episodes = stringList(record.metadata?.episodes);+ if (!episodes.length) return record;+ const input = await this.episodesAsMessages(episodes);+ return input.length ? { ...record, input } : record;+ }++ private async episodesAsMessages(ids: string[]): Promise<MemoryMessage[]> {+ const messages: MemoryMessage[] = [];+ for (const id of ids.slice(0, MAX_EPISODES)) {+ try {+ const row = asRecord(+ await this.request(`api/v2/graph/episodes/${encodeURIComponent(id)}`)+ );+ const content = stringValue(row.content);+ if (!content) continue;+ messages.push({+ role: stringValue(row.role) || stringValue(row.role_type) || "user",+ content,+ });+ } catch {+ continue;+ }+ }+ return messages;+ }+}++export const zepAdapterFactory = {+ type: "zep",+ create: (descriptor: MemorySourceDescriptor) => new ZepAdapter(descriptor),+ describe: (): MemoryTypeDescriptor => ({+ type: "zep",+ displayName: "Zep",+ description: getMessage().MEMORY_CONNECTOR_ZEP_DESCRIPTION,+ capabilities: { ...ZEP_CAPABILITIES },+ configFields: memoryHttpVendorFields({ placeholder: DEFAULT_URL }),+ filterFields: memoryPageFilters([+ { key: "userId", required: true },+ { key: "sessionId", writeRequired: true },+ ]),+ authStyle: "api-key",+ authHelp: getMessage().MEMORY_CONNECTOR_AUTH_HELP_ZEP,+ docsUrl: "https://help.getzep.com/sdk-reference",+ }),+};diff --git a/src/client/src/lib/platform/connectors/visible-types.ts b/src/client/src/lib/platform/connectors/visible-types.tsindex 9206c087..b5a055f9 100644--- a/src/client/src/lib/platform/connectors/visible-types.ts+++ b/src/client/src/lib/platform/connectors/visible-types.ts@@ -1,5 +1,14 @@/** Connector types currently exposed in the CE UI. */-export const VISIBLE_CONNECTOR_TYPES = ["clickhouse", "tempo", "loki", "prometheus", "jaeger"] as const;+export const VISIBLE_CONNECTOR_TYPES = [+ "clickhouse",+ "tempo",+ "loki",+ "prometheus",+ "jaeger",+ "claude",+ "mem0",+ "zep",+] as const;export function isVisibleConnectorType(type: unknown): boolean {return VISIBLE_CONNECTOR_TYPES.includes(String(type) as (typeof VISIBLE_CONNECTOR_TYPES)[number]);diff --git a/src/client/src/utils/breadcrumbs.ts b/src/client/src/utils/breadcrumbs.tsindex cdda498f..6f4502c9 100644--- a/src/client/src/utils/breadcrumbs.ts+++ b/src/client/src/utils/breadcrumbs.ts@@ -240,6 +240,13 @@ export const ROUTE_CONFIGS: RouteConfig[] = [getBreadcrumbs: () => [],},+ // Memory+ {+ regex: /^\/memory$/,+ getTitle: () => getMessage().FEATURE_MEMORY,+ getBreadcrumbs: () => [],+ },+// Rule Engine{regex: /^\/rule-engine$/,diff --git a/src/client/src/utils/date.ts b/src/client/src/utils/date.tsindex c0a84d05..5559badd 100644--- a/src/client/src/utils/date.ts+++ b/src/client/src/utils/date.ts@@ -28,6 +28,81 @@ export function formatBrowserDateTime(return date ? date.toLocaleString() : fallback;}+const DATE_PART_KEYS = new Set([+ "year",+ "month",+ "day",+ "hour",+ "hours",+ "minute",+ "minutes",+ "second",+ "seconds",+ "millisecond",+ "milliseconds",+ "ms",+ "quarter",+ "isweekend",+ "weekend",+ "dayofweek",+ "weekday",+ "dayofyear",+ "weekofyear",+ "week",+ "timezone",+ "tz",+ "utc",+ "timestamp",+ "datetime",+ "date",+ "ampm",+ "meridiem",+ "offset",+]);++function normalizeDatePartKey(key: string): string {+ return key.toLowerCase().replace(/[\s_-]/g, "");+}++function datePartNumber(+ parts: Record<string, unknown>,+ ...keys: string[]+): number | undefined {+ for (const key of keys) {+ const value = parts[key];+ if (typeof value === "number" && Number.isFinite(value)) return value;+ if (typeof value === "string" && value.trim() && Number.isFinite(Number(value))) {+ return Number(value);+ }+ }+ return undefined;+}++function isPlainDatePartsObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++export function formatDatePartsValue(value: unknown): string | null {+ if (!isPlainDatePartsObject(value)) return null;+ const parts: Record<string, unknown> = {};+ for (const [key, entry] of Object.entries(value)) {+ if (entry === null || entry === undefined || entry === "") continue;+ parts[normalizeDatePartKey(key)] = entry;+ }+ if (!("year" in parts) || !("month" in parts) || !("day" in parts)) return null;+ if (!Object.keys(parts).every((key) => DATE_PART_KEYS.has(key))) return null;+ const year = datePartNumber(parts, "year");+ const month = datePartNumber(parts, "month");+ const day = datePartNumber(parts, "day");+ if (!year || !month || !day) return null;+ const hour = datePartNumber(parts, "hour", "hours") ?? 0;+ const minute = datePartNumber(parts, "minute", "minutes") ?? 0;+ const second = datePartNumber(parts, "second", "seconds") ?? 0;+ const date = new Date(year, month - 1, day, hour, minute, second);+ if (Number.isNaN(date.getTime())) return null;+ return date.toLocaleString();+}+export function formatDate(dateString: string, options?: { time?: boolean }) {const date = parseDateString(dateString);if (!date) return "-";