🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(ui-customization): add self-hosted instance switcher (#15611)
Steffen Schmitz462d07c6c050
diff --git a/web/src/__tests__/server/unit/instanceLinks.servertest.ts b/web/src/__tests__/server/unit/instanceLinks.servertest.tsnew file mode 100644index 0000000000..b446346234--- /dev/null+++ b/web/src/__tests__/server/unit/instanceLinks.servertest.ts@@ -0,0 +1,96 @@+import { describe, it, expect, vi, afterEach } from "vitest";++import {+ parseInstanceLinks,+ findCurrentInstance,+} from "@/src/ee/features/ui-customization/instanceLinks";++describe("parseInstanceLinks", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("parses a valid JSON array of {name, url} objects", () => {+ const raw = JSON.stringify([+ { name: "Staging", url: "https://langfuse-staging.example.com" },+ { name: "Prod", url: "https://langfuse.example.com" },+ ]);+ expect(parseInstanceLinks(raw)).toEqual([+ { name: "Staging", url: "https://langfuse-staging.example.com" },+ { name: "Prod", url: "https://langfuse.example.com" },+ ]);+ });++ it("returns null when unset or blank", () => {+ expect(parseInstanceLinks(undefined)).toBeNull();+ expect(parseInstanceLinks("")).toBeNull();+ expect(parseInstanceLinks(" ")).toBeNull();+ });++ it("returns null and warns on invalid JSON", () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ expect(parseInstanceLinks("not json")).toBeNull();+ expect(warn).toHaveBeenCalledOnce();+ });++ it("returns null and warns when the JSON is not an array of {name, url}", () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ expect(parseInstanceLinks('{"name":"A","url":"https://a.com"}')).toBeNull();+ expect(parseInstanceLinks('[{"name":"A"}]')).toBeNull();+ expect(+ parseInstanceLinks('[{"name":"","url":"https://a.com"}]'),+ ).toBeNull();+ expect(parseInstanceLinks('[{"name":"A","url":"not-a-url"}]')).toBeNull();+ expect(parseInstanceLinks("[]")).toBeNull();+ expect(warn).toHaveBeenCalledTimes(5);+ });++ it("rejects non-http(s) URL schemes, which window.open would run in-app", () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ for (const url of [+ "javascript:alert(1)",+ "data:text/html,<script>alert(1)</script>",+ "file:///etc/passwd",+ "mailto:[email protected]",+ "ftp://langfuse.example.com",+ ]) {+ expect(+ parseInstanceLinks(JSON.stringify([{ name: "A", url }])),+ ).toBeNull();+ }+ expect(warn).toHaveBeenCalledTimes(5);+ });++ it("rejects duplicate names, which are ambiguous in the menu", () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const raw = JSON.stringify([+ { name: "Staging", url: "https://staging-a.example.com" },+ { name: "Staging", url: "https://staging-b.example.com" },+ ]);+ expect(parseInstanceLinks(raw)).toBeNull();+ expect(warn).toHaveBeenCalledOnce();+ expect(warn.mock.calls[0]?.[0]).toContain("names must be unique");+ });+});++describe("findCurrentInstance", () => {+ const links = [+ { name: "Staging", url: "https://langfuse-staging.example.com" },+ { name: "Dev", url: "https://langfuse.example.com:8443" },+ ];++ it("matches by host including the port", () => {+ expect(findCurrentInstance(links, "langfuse-staging.example.com")).toEqual(+ links[0],+ );+ expect(findCurrentInstance(links, "langfuse.example.com:8443")).toEqual(+ links[1],+ );+ });++ it("returns undefined when nothing matches or the host is unknown", () => {+ expect(findCurrentInstance(links, "other.example.com")).toBeUndefined();+ expect(findCurrentInstance(links, "langfuse.example.com")).toBeUndefined();+ expect(findCurrentInstance(links, undefined)).toBeUndefined();+ });+});diff --git a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsxindex 082b44eb27..4d04ba1c77 100644--- a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx+++ b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx@@ -38,6 +38,7 @@ import { ControlledFeaturePreviewModal } from "@/src/features/feature-previews/cimport { InAppAgentWindowHost } from "@/src/features/in-app-agent/components/InAppAgentWindowHost";import { useV4UpgradeUiEnabled } from "@/src/features/v4-migration/useV4UpgradeUiEnabled";import { useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";+import { findCurrentInstance } from "@/src/ee/features/ui-customization/instanceLinks";import { api } from "@/src/utils/api";import { usePlan } from "@/src/features/entitlements/hooks";import { env } from "@/src/env.mjs";@@ -122,6 +123,7 @@ export function AuthenticatedLayout({const [featurePreviewOpen, setFeaturePreviewOpen] = useState(false);const router = useRouter();useProjectCookie(router);+ const uiCustomization = useUiCustomization();// Safe assertion: AuthenticatedLayout is only rendered after auth checks pass// in AppLayout, which guarantees session.user exists at this point@@ -147,6 +149,23 @@ export function AuthenticatedLayout({}),);+ // Self-hosted instance switcher (EE): configured via+ // LANGFUSE_UI_INSTANCE_LINKS, delivered through the uiCustomization query.+ const instanceLinks = uiCustomization?.instanceLinks ?? null;+ const currentInstance = instanceLinks+ ? findCurrentInstance(+ instanceLinks,+ typeof window !== "undefined" ? window.location.host : undefined,+ )+ : undefined;+ const instanceMenuItems = (instanceLinks ?? []).map((link) => ({+ type: "action" as const,+ name: link.name,+ onClick: () => {+ window.open(link.url, "_blank", "noopener,noreferrer");+ },+ }));+const hasFeaturePreviews = isLangfuseCloud || user.v4BetaEnabled === true;// User navigation items for sidebar dropdown@@ -193,6 +212,23 @@ export function AuthenticatedLayout({},]: []),+ ...(instanceMenuItems.length > 0+ ? [+ {+ type: "submenu" as const,+ name: "Instances",+ subItems: instanceMenuItems,+ content: currentInstance ? (+ <>+ Instances+ <div className="ml-2 inline-flex rounded bg-black/5 p-1 text-xs dark:bg-white/10">+ Current: {currentInstance.name}+ </div>+ </>+ ) : undefined,+ },+ ]+ : []),{ type: "action" as const, name: "Sign out", onClick: onSignOut },];diff --git a/web/src/ee/features/ui-customization/instanceLinks.ts b/web/src/ee/features/ui-customization/instanceLinks.tsnew file mode 100644index 0000000000..ce24046401--- /dev/null+++ b/web/src/ee/features/ui-customization/instanceLinks.ts@@ -0,0 +1,81 @@+import { z } from "zod";++/**+ * Schema for a single entry of the instance switcher shown in the sidebar+ * user menu. Configured via LANGFUSE_UI_INSTANCE_LINKS.+ */+export const InstanceLink = z.object({+ name: z.string().min(1),+ // Restricted to http(s): the URL is handed to window.open, where a+ // javascript:/data:/file: entry would run in the app's context rather+ // than open another Langfuse deployment.+ url: z.url({ protocol: /^https?$/ }),+});++export type InstanceLink = z.infer<typeof InstanceLink>;++// Names must be unique: they are the only thing distinguishing entries in+// the menu, and the sidebar keys its items by name.+const InstanceLinks = z+ .array(InstanceLink)+ .min(1)+ .refine((links) => new Set(links.map((l) => l.name)).size === links.length, {+ message: "Instance link names must be unique",+ });++/**+ * Parse LANGFUSE_UI_INSTANCE_LINKS into the instance links rendered as an+ * instance switcher in the sidebar user menu.+ *+ * Expects a JSON array of { name, url } objects with unique names and+ * http(s) URLs, e.g.+ * [{"name":"Staging","url":"https://langfuse-staging.example.com"}]+ *+ * Invalid configuration disables the switcher (returns null) instead of+ * failing the deployment.+ */+export function parseInstanceLinks(raw?: string): InstanceLink[] | null {+ if (!raw || !raw.trim()) return null;++ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ console.warn(+ "LANGFUSE_UI_INSTANCE_LINKS is not valid JSON. Expected a JSON array of {name, url} objects. The instance switcher is disabled.",+ );+ return null;+ }++ const result = InstanceLinks.safeParse(parsed);+ if (!result.success) {+ const issues = result.error.issues+ .map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`)+ .join("; ");+ console.warn(+ `LANGFUSE_UI_INSTANCE_LINKS is invalid, so the instance switcher is disabled. Expected a non-empty JSON array of {name, url} objects with unique names and http(s) URLs. ${issues}`,+ );+ return null;+ }++ return result.data;+}++/**+ * Find the configured instance link matching the host (hostname + port) the+ * user is currently on, if any.+ */+export function findCurrentInstance(+ links: InstanceLink[],+ currentHost: string | undefined,+): InstanceLink | undefined {+ if (!currentHost) return undefined;++ return links.find((link) => {+ try {+ return new URL(link.url).host === currentHost;+ } catch {+ return false;+ }+ });+}diff --git a/web/src/ee/features/ui-customization/uiCustomizationRouter.ts b/web/src/ee/features/ui-customization/uiCustomizationRouter.tsindex 9dd382d2c5..87ee81d049 100644--- a/web/src/ee/features/ui-customization/uiCustomizationRouter.ts+++ b/web/src/ee/features/ui-customization/uiCustomizationRouter.ts@@ -5,6 +5,10 @@ import {authenticatedProcedure,} from "@/src/server/api/trpc";import { getVisibleProductModules } from "@/src/ee/features/ui-customization/productModuleSchema";+import { parseInstanceLinks } from "@/src/ee/features/ui-customization/instanceLinks";++// Parsed once per process so invalid configuration warns once, not per query.+const instanceLinks = parseInstanceLinks(env.LANGFUSE_UI_INSTANCE_LINKS);export const uiCustomizationRouter = createTRPCRouter({get: authenticatedProcedure.query(({ ctx }) => {@@ -25,6 +29,7 @@ export const uiCustomizationRouter = createTRPCRouter({defaultBaseUrlOpenAI: env.LANGFUSE_UI_DEFAULT_BASE_URL_OPENAI,defaultBaseUrlAnthropic: env.LANGFUSE_UI_DEFAULT_BASE_URL_ANTHROPIC,defaultBaseUrlAzure: env.LANGFUSE_UI_DEFAULT_BASE_URL_AZURE,+ instanceLinks,visibleModules: getVisibleProductModules(env.LANGFUSE_UI_VISIBLE_PRODUCT_MODULES,env.LANGFUSE_UI_HIDDEN_PRODUCT_MODULES,diff --git a/web/src/env.mjs b/web/src/env.mjsindex 86dc29c995..38c6b50456 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -335,6 +335,10 @@ export const env = createEnv({LANGFUSE_UI_DEFAULT_BASE_URL_OPENAI: z.url().optional(),LANGFUSE_UI_DEFAULT_BASE_URL_ANTHROPIC: z.url().optional(),LANGFUSE_UI_DEFAULT_BASE_URL_AZURE: z.url().optional(),+ // JSON array of {name, url} objects; validated lazily in+ // web/src/ee/features/ui-customization/instanceLinks.ts so a bad value+ // disables the instance switcher instead of failing the deployment.+ LANGFUSE_UI_INSTANCE_LINKS: z.string().optional(),// EE LicenseLANGFUSE_EE_LICENSE_KEY: z.string().optional(),@@ -920,6 +924,7 @@ export const env = createEnv({process.env.LANGFUSE_UI_DEFAULT_BASE_URL_ANTHROPIC,LANGFUSE_UI_DEFAULT_BASE_URL_AZURE:process.env.LANGFUSE_UI_DEFAULT_BASE_URL_AZURE,+ LANGFUSE_UI_INSTANCE_LINKS: process.env.LANGFUSE_UI_INSTANCE_LINKS,LANGFUSE_UI_VISIBLE_PRODUCT_MODULES:process.env.LANGFUSE_UI_VISIBLE_PRODUCT_MODULES,LANGFUSE_UI_HIDDEN_PRODUCT_MODULES: