Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(web): newsletter step in self-hosted signup onboarding (#18804)

Abdallah Othman860ccfaece54
diff --git a/docker-compose.build.yml b/docker-compose.build.yml
index e52865a496..70df5e864a 100644
--- a/docker-compose.build.yml
+++ b/docker-compose.build.yml
@@ -37,6 +37,7 @@ services:
LANGFUSE_INIT_USER_PASSWORD: ${LANGFUSE_INIT_USER_PASSWORD:-}
LANGFUSE_MARKDOWN_RENDER_CHARACTER_LIMIT: ${LANGFUSE_MARKDOWN_RENDER_CHARACTER_LIMIT:-}
LANGFUSE_TRUSTED_PROXY_COUNT: ${LANGFUSE_TRUSTED_PROXY_COUNT:-}
+ LANGFUSE_DISABLE_SIGNUP_ONBOARDING: ${LANGFUSE_DISABLE_SIGNUP_ONBOARDING:-}
CLICKHOUSE_MIGRATION_URL: ${CLICKHOUSE_MIGRATION_URL:-clickhouse://clickhouse:9000}
CLICKHOUSE_URL: ${CLICKHOUSE_URL:-http://clickhouse:8123}
CLICKHOUSE_USER: ${CLICKHOUSE_USER:-clickhouse}
diff --git a/docker-compose.yml b/docker-compose.yml
index 9b1ac38e73..38012cd38b 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -136,6 +136,7 @@ services:
LANGFUSE_INIT_USER_PASSWORD: ${LANGFUSE_INIT_USER_PASSWORD:-}
LANGFUSE_MARKDOWN_RENDER_CHARACTER_LIMIT: ${LANGFUSE_MARKDOWN_RENDER_CHARACTER_LIMIT:-}
LANGFUSE_TRUSTED_PROXY_COUNT: ${LANGFUSE_TRUSTED_PROXY_COUNT:-}
+ LANGFUSE_DISABLE_SIGNUP_ONBOARDING: ${LANGFUSE_DISABLE_SIGNUP_ONBOARDING:-}
# Hostnames allowed to reach the MCP endpoint, beyond NEXTAUTH_URL's own
# host. Required when the worker uses LANGFUSE_MCP_BASE_URL.
LANGFUSE_MCP_ALLOWED_HOSTS: ${LANGFUSE_MCP_ALLOWED_HOSTS:-}
diff --git a/web/next.config.mjs b/web/next.config.mjs
index abb4d2e55d..93abd892d1 100644
--- a/web/next.config.mjs
+++ b/web/next.config.mjs
@@ -31,6 +31,12 @@ const localStorageConnectSrc =
env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined
? "http://localhost:* "
: "";
+// The self-hosted newsletter step after sign-up checks and subscribes on the
+// bare langfuse.com host, which `https://*.langfuse.com` does not match.
+const newsletterSignupConnectSrc =
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined
+ ? "https://langfuse.com "
+ : "";
// When build output is served from a dedicated asset hostname, that origin has
// to be allowed everywhere Next.js can emit an asset URL. A host under
// langfuse.com would already be covered by the wildcards below, but the policy
@@ -54,7 +60,7 @@ const cspHeader = `
base-uri 'self';
form-action 'self' https://login.microsoftonline.com https://login.microsoft.com https://*.microsoftonline.com;
frame-ancestors 'none';
- connect-src 'self' ${localStorageConnectSrc}${mediaUploadConnectSrc}${assetPrefixSrc}https://*.langfuse.com https://*.langfuse.dev https://*.ingest.us.sentry.io https://*.sentry.io https://chat.uk.plain.com https://*.amazonaws.com https://*.blob.core.windows.net https://storage.googleapis.com https://prod-uk-services-attachm-attachmentsuploadbucket2-1l2e4906o2asm.s3.eu-west-2.amazonaws.com https://login.microsoftonline.com https://login.microsoft.com https://*.microsoftonline.com https://graph.microsoft.com;
+ connect-src 'self' ${localStorageConnectSrc}${newsletterSignupConnectSrc}${mediaUploadConnectSrc}${assetPrefixSrc}https://*.langfuse.com https://*.langfuse.dev https://*.ingest.us.sentry.io https://*.sentry.io https://chat.uk.plain.com https://*.amazonaws.com https://*.blob.core.windows.net https://storage.googleapis.com https://prod-uk-services-attachm-attachmentsuploadbucket2-1l2e4906o2asm.s3.eu-west-2.amazonaws.com https://login.microsoftonline.com https://login.microsoft.com https://*.microsoftonline.com https://graph.microsoft.com;
media-src 'self' https: http://localhost:*;
${env.LANGFUSE_CSP_ENFORCE_HTTPS === "true" ? "upgrade-insecure-requests; block-all-mixed-content;" : ""}
${env.SENTRY_CSP_REPORT_URI ? `report-uri ${env.SENTRY_CSP_REPORT_URI}; report-to csp-endpoint;` : ""}
diff --git a/web/src/__tests__/redirect.clienttest.ts b/web/src/__tests__/redirect.clienttest.ts
index 86df2e6ae1..40a8e3158f 100644
--- a/web/src/__tests__/redirect.clienttest.ts
+++ b/web/src/__tests__/redirect.clienttest.ts
@@ -421,6 +421,11 @@ describe("stripBasePath", () => {
expect(stripBasePath("/apps/apps/dashboard")).toBe("/apps/dashboard");
});
+ it("never returns a protocol-relative path", () => {
+ expect(stripBasePath("/apps//evil.example/x")).toBe("/evil.example/x");
+ expect(stripBasePath("/apps/\\evil.example/x")).toBe("/evil.example/x");
+ });
+
it("strips ASCII control characters from the path", () => {
// Newline (header-injection vector)
expect(stripBasePath("/apps\n/dashboard")).toBe("/dashboard");
diff --git a/web/src/__tests__/server/onboarding-router.servertest.ts b/web/src/__tests__/server/onboarding-router.servertest.ts
index 4e82a4ac05..c0f7e1d750 100644
--- a/web/src/__tests__/server/onboarding-router.servertest.ts
+++ b/web/src/__tests__/server/onboarding-router.servertest.ts
@@ -486,7 +486,7 @@ describe("onboarding router", () => {
surveyCreated: true,
});
});
- describe("build intent answers", () => {
+ describe("survey answers", () => {
const createCallerForNewUser = async () => {
const userId = randomUUID();
const email = `build-intent-${userId}@example.com`;
@@ -523,6 +523,77 @@ describe("onboarding router", () => {
});
});
+ describe("newsletter result", () => {
+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+
+ afterEach(() => {
+ Object.assign(env, {
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: originalCloudRegion,
+ });
+ });
+
+ const completeAsOrganizationMember = async ({
+ role,
+ cloudRegion,
+ clientLists,
+ }: {
+ role: Role;
+ cloudRegion?: string;
+ clientLists: string[];
+ }) => {
+ Object.assign(env, { NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: cloudRegion });
+ const { caller, userId } = await createCallerForNewUser();
+ const organization = await prisma.organization.create({
+ data: {
+ name: `Newsletter Org ${userId}`,
+ organizationMemberships: { create: { userId, role } },
+ },
+ });
+ createdOrgIds.push(organization.id);
+
+ await caller.onboarding.complete({
+ newsletter: { outcome: "subscribed", lists: clientLists },
+ } as Parameters<typeof caller.onboarding.complete>[0]);
+
+ const survey = await prisma.survey.findFirstOrThrow({
+ where: { userId },
+ });
+ return survey.response;
+ };
+
+ it.each([
+ {
+ role: Role.VIEWER,
+ clientLists: ["product", "oss"],
+ storedLists: ["product"],
+ },
+ {
+ role: Role.OWNER,
+ clientLists: ["product"],
+ storedLists: ["product", "oss"],
+ },
+ ])(
+ "stores the lists offered to a $role on self-hosted, not the client's",
+ async ({ role, clientLists, storedLists }) => {
+ await expect(
+ completeAsOrganizationMember({ role, clientLists }),
+ ).resolves.toEqual({
+ newsletter: { lists: storedLists, outcome: "subscribed" },
+ });
+ },
+ );
+
+ it("stores no newsletter result in Cloud", async () => {
+ await expect(
+ completeAsOrganizationMember({
+ role: Role.OWNER,
+ cloudRegion: "US",
+ clientLists: ["product", "oss"],
+ }),
+ ).resolves.toEqual({});
+ });
+ });
+
it.each([
[
"duplicate picks",
@@ -558,6 +629,10 @@ describe("onboarding router", () => {
"positions that don't match the picks",
{ buildIntents: ["rag", "other"], buildIntentPositions: [2] },
],
+ [
+ "a newsletter result with an unknown outcome",
+ { newsletter: { outcome: "bounced" } },
+ ],
])("rejects %s", async (_case, input) => {
const { caller, userId } = await createCallerForNewUser();
diff --git a/web/src/__tests__/server/unit/csp.servertest.ts b/web/src/__tests__/server/unit/csp.servertest.ts
index 22bdc73185..f1cca6ad4f 100644
--- a/web/src/__tests__/server/unit/csp.servertest.ts
+++ b/web/src/__tests__/server/unit/csp.servertest.ts
@@ -25,6 +25,12 @@ const getCsp = (cloudRegion?: string) =>
},
);
+const getConnectSrc = (cloudRegion?: string) =>
+ getCsp(cloudRegion)
+ .match(/connect-src ([^;]*);/)?.[1]
+ .trim()
+ .split(/\s+/);
+
describe("Content Security Policy", () => {
it("allows the local MinIO endpoint in self-hosted Docker builds", () => {
expect(getCsp()).toContain("connect-src 'self' http://localhost:*");
@@ -33,4 +39,12 @@ describe("Content Security Policy", () => {
it("does not allow local connections in Cloud", () => {
expect(getCsp("US")).not.toContain("connect-src 'self' http://localhost:*");
});
+
+ it("allows the newsletter signup on the bare langfuse.com host in self-hosted builds", () => {
+ expect(getConnectSrc()).toContain("https://langfuse.com");
+ });
+
+ it("does not allow the bare langfuse.com host in Cloud", () => {
+ expect(getConnectSrc("US")).not.toContain("https://langfuse.com");
+ });
});
diff --git a/web/src/__tests__/server/unit/getServerAuthSession-invalid-callback-url.servertest.ts b/web/src/__tests__/server/unit/getServerAuthSession-invalid-callback-url.servertest.ts
index eba17f3d7f..6a7a5b7a76 100644
--- a/web/src/__tests__/server/unit/getServerAuthSession-invalid-callback-url.servertest.ts
+++ b/web/src/__tests__/server/unit/getServerAuthSession-invalid-callback-url.servertest.ts
@@ -4,6 +4,7 @@ import type * as NextAuth from "next-auth";
import { createMocks } from "node-mocks-http";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { env } from "@/src/env.mjs";
import { getCookieName } from "@/src/server/utils/cookies";
const { mockAuthSpan, mockGetServerSession, mockInstrumentAsync } = vi.hoisted(
@@ -48,6 +49,8 @@ import {
const callbackUrlCookieName = getCookieName("next-auth.callback-url");
const originalNextAuthSecret = process.env.NEXTAUTH_SECRET;
+const originalDisableSignupOnboarding = env.LANGFUSE_DISABLE_SIGNUP_ONBOARDING;
+const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
const assertSanitizedRequest = (request: {
cookies?: Partial<Record<string, string>>;
@@ -66,6 +69,10 @@ describe("getServerAuthSession invalid callback URL handling", () => {
});
afterEach(() => {
+ Object.assign(env, {
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: originalCloudRegion,
+ LANGFUSE_DISABLE_SIGNUP_ONBOARDING: originalDisableSignupOnboarding,
+ });
if (originalNextAuthSecret === undefined) {
delete process.env.NEXTAUTH_SECRET;
} else {
@@ -132,6 +139,33 @@ describe("getServerAuthSession invalid callback URL handling", () => {
).toBe("http://localhost:3000");
});
+ it.each([
+ {
+ region: "EU",
+ disableSignupOnboarding: undefined,
+ newUser: "/onboarding",
+ },
+ { region: "EU", disableSignupOnboarding: "true", newUser: "/onboarding" },
+ {
+ region: undefined,
+ disableSignupOnboarding: undefined,
+ newUser: "/onboarding",
+ },
+ { region: undefined, disableSignupOnboarding: "true", newUser: undefined },
+ ])(
+ "sets pages.newUser to $newUser in region $region when LANGFUSE_DISABLE_SIGNUP_ONBOARDING is $disableSignupOnboarding",
+ async ({ region, disableSignupOnboarding, newUser }) => {
+ Object.assign(env, {
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: region,
+ LANGFUSE_DISABLE_SIGNUP_ONBOARDING: disableSignupOnboarding,
+ });
+
+ const authOptions = await getAuthOptions();
+
+ expect(authOptions.pages?.newUser).toBe(newUser);
+ },
+ );
+
it("does not attach the user email to the sign-in span", async () => {
const authOptions = await getAuthOptions();
const signIn = authOptions.callbacks?.signIn;
diff --git a/web/src/__tests__/server/unit/onboardingService.servertest.ts b/web/src/__tests__/server/unit/onboardingService.servertest.ts
index 61df7470d7..2426d5636f 100644
--- a/web/src/__tests__/server/unit/onboardingService.servertest.ts
+++ b/web/src/__tests__/server/unit/onboardingService.servertest.ts
@@ -7,23 +7,38 @@ vi.mock("@/src/features/audit-logs/server", () => ({
}));
import { type Prisma, Role, SurveyName } from "@langfuse/shared/src/db";
+import { env } from "@/src/env.mjs";
import {
- completeCloudSignupOnboarding,
- getCloudSignupOnboardingStatus,
+ completeSignupOnboarding,
+ getSignupOnboardingStatus,
provisionStarterOrganizationForNewUser,
resolveOnboardingRedirectTarget,
type RealOrganizationMembership,
} from "@/src/features/onboarding/server";
type CompletionPrisma = Parameters<
- typeof completeCloudSignupOnboarding
+ typeof completeSignupOnboarding
>[0]["prisma"];
type RedirectPrisma = Parameters<
typeof resolveOnboardingRedirectTarget
>[0]["prisma"];
-type StatusPrisma = Parameters<
- typeof getCloudSignupOnboardingStatus
->[0]["prisma"];
+type StatusPrisma = Parameters<typeof getSignupOnboardingStatus>[0]["prisma"];
+
+const originalEnv = {
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
+ LANGFUSE_DISABLE_SIGNUP_ONBOARDING: env.LANGFUSE_DISABLE_SIGNUP_ONBOARDING,
+};
+
+beforeEach(() => {
+ Object.assign(env, {
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: "US",
+ LANGFUSE_DISABLE_SIGNUP_ONBOARDING: undefined,
+ });
+});
+
+afterEach(() => {
+ Object.assign(env, originalEnv);
+});
const makeMembership = ({
orgId,
@@ -129,12 +144,12 @@ describe("resolveOnboardingRedirectTarget", () => {
});
});
-describe("getCloudSignupOnboardingStatus", () => {
- const getStatus = (prisma: StatusPrisma) =>
- getCloudSignupOnboardingStatus({
+describe("getSignupOnboardingStatus", () => {
+ const getStatus = (prisma: StatusPrisma, canCreateOrganizations = true) =>
+ getSignupOnboardingStatus({
prisma,
userId: "user-1",
- canCreateOrganizations: true,
+ canCreateOrganizations,
});
it("uses the onboarding survey as the completion marker", async () => {
@@ -186,9 +201,78 @@ describe("getCloudSignupOnboardingStatus", () => {
canConfigureAiFeatures: true,
});
});
+
+ it.each([
+ {
+ audience: "an installer",
+ role: undefined,
+ canCreateOrganizations: true,
+ lists: ["product", "oss"],
+ },
+ {
+ audience: "a user without a membership who can't create organizations",
+ role: undefined,
+ canCreateOrganizations: false,
+ lists: ["product"],
+ },
+ {
+ audience: "an organization admin",
+ role: Role.ADMIN,
+ canCreateOrganizations: true,
+ lists: ["product", "oss"],
+ },
+ {
+ audience: "an invited viewer",
+ role: Role.VIEWER,
+ canCreateOrganizations: true,
+ lists: ["product"],
+ },
+ ])(
+ "offers $audience the $lists newsletters on self-hosted",
+ async ({ role, canCreateOrganizations, lists }) => {
+ Object.assign(env, { NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: undefined });
+ const { tx } = makeCompletionPrisma({
+ memberships: role
+ ? [makeMembership({ orgId: "org-1", role, projects: [] })]
+ : [],
+ });
+
+ await expect(
+ getStatus(tx as unknown as StatusPrisma, canCreateOrganizations),
+ ).resolves.toMatchObject({ completed: false, newsletterLists: lists });
+ },
+ );
+
+ it("reports a disabled step as completed on self-hosted without reading the survey", async () => {
+ Object.assign(env, {
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: undefined,
+ LANGFUSE_DISABLE_SIGNUP_ONBOARDING: "true",
+ });
+ const { tx } = makeCompletionPrisma({
+ memberships: [
+ makeMembership({ orgId: "org-1", projects: [{ id: "project-1" }] }),
+ ],
+ });
+
+ await expect(getStatus(tx as unknown as StatusPrisma)).resolves.toEqual({
+ completed: true,
+ redirectTo: "/project/project-1",
+ });
+ expect(tx.survey.findFirst).not.toHaveBeenCalled();
+ });
+
+ it("ignores the off switch on Cloud", async () => {
+ Object.assign(env, { LANGFUSE_DISABLE_SIGNUP_ONBOARDING: "true" });
+ const { tx } = makeCompletionPrisma();
+
+ await expect(getStatus(tx as unknown as StatusPrisma)).resolves.toEqual({
+ completed: false,
+ canConfigureAiFeatures: false,
+ });
+ });
});
-describe("completeCloudSignupOnboarding", () => {
+describe("completeSignupOnboarding", () => {
it("locks the user row and writes one trimmed onboarding survey once", async () => {
const { prisma, tx } = makeCompletionPrisma({
memberships: [
@@ -205,7 +289,7 @@ describe("completeCloudSignupOnboarding", () => {
});
await expect(
- completeCloudSignupOnboarding({
+ completeSignupOnboarding({
prisma,
userId: "user-1",
userEmail: "[email protected]",
@@ -249,7 +333,7 @@ describe("completeCloudSignupOnboarding", () => {
tx.survey.findFirst.mockResolvedValue({ id: "survey-1" });
- const repeatResult = await completeCloudSignupOnboarding({
+ const repeatResult = await completeSignupOnboarding({
prisma,
userId: "user-1",
userEmail: "[email protected]",
@@ -271,7 +355,7 @@ describe("completeCloudSignupOnboarding", () => {
],
});
- await completeCloudSignupOnboarding({
+ await completeSignupOnboarding({
prisma,
userId: "user-1",
userEmail: "[email protected]",
@@ -296,6 +380,44 @@ describe("completeCloudSignupOnboarding", () => {
);
});
+ it("writes nothing when the step is disabled on self-hosted", async () => {
+ Object.assign(env, {
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: undefined,
+ LANGFUSE_DISABLE_SIGNUP_ONBOARDING: "true",
+ });
+ const prisma = {
+ $transaction: vi.fn(),
+ organizationMembership: { findMany: vi.fn().mockResolvedValue([]) },
+ };
+
+ await expect(
+ completeSignupOnboarding({
+ prisma: prisma as unknown as CompletionPrisma,
+ userId: "user-1",
+ canCreateOrganizations: true,
+ newsletter: { outcome: "declined" },
+ }),
+ ).resolves.toEqual({ redirectTo: "/setup", surveyCreated: false });
+ expect(prisma.$transaction).not.toHaveBeenCalled();
+ });
+
+ it("still stores the survey on Cloud when the off switch is set", async () => {
+ Object.assign(env, { LANGFUSE_DISABLE_SIGNUP_ONBOARDING: "true" });
+ const { prisma, tx } = makeCompletionPrisma({
+ memberships: [
+ makeMembership({ orgId: "org-1", projects: [{ id: "project-1" }] }),
+ ],
+ });
+
+ await completeSignupOnboarding({
+ prisma,
+ userId: "user-1",
+ canCreateOrganizations: true,
+ });
+
+ expect(tx.survey.create).toHaveBeenCalled();
+ });
+
it("stores an empty response when the survey is skipped", async () => {
const { prisma, tx } = makeCompletionPrisma({
memberships: [
@@ -303,7 +425,7 @@ describe("completeCloudSignupOnboarding", () => {
],
});
- await completeCloudSignupOnboarding({
+ await completeSignupOnboarding({
prisma,
userId: "user-1",
canCreateOrganizations: true,
@@ -326,7 +448,7 @@ describe("completeCloudSignupOnboarding", () => {
],
});
- await completeCloudSignupOnboarding({
+ await completeSignupOnboarding({
prisma,
userId: "user-1",
userEmail: "[email protected]",
diff --git a/web/src/components/design-system/Button/Button.stories.tsx b/web/src/components/design-system/Button/Button.stories.tsx
index cec10edfa5..a034ad698e 100644
--- a/web/src/components/design-system/Button/Button.stories.tsx
+++ b/web/src/components/design-system/Button/Button.stories.tsx
@@ -101,6 +101,29 @@ export const Loading = meta.story({
},
});
+export const KeepsItsWidthWhileLoading = meta.story({
+ name: "(Test) Keeps Its Width While Loading",
+ parameters: { controls: { disable: true } },
+ render: () => (
+ <div className="flex gap-2">
+ <Button text="Save changes" />
+ <Button text="Save changes" loading />
+ </div>
+ ),
+ play: async ({ canvasElement }) => {
+ const [idle, loading] = within(canvasElement).getAllByRole("button", {
+ name: "Save changes",
+ });
+
+ await expect(loading).toBeDisabled();
+ await expect(loading).toHaveAttribute("aria-busy", "true");
+ await expect(within(loading).getByText("Save changes")).not.toBeVisible();
+ await expect(loading.getBoundingClientRect().width).toBe(
+ idle.getBoundingClientRect().width,
+ );
+ },
+});
+
const onClick = fn();
export const TestClick = meta.story({
diff --git a/web/src/components/design-system/Button/Button.tsx b/web/src/components/design-system/Button/Button.tsx
index 30382d2911..1e8e19aca6 100644
--- a/web/src/components/design-system/Button/Button.tsx
+++ b/web/src/components/design-system/Button/Button.tsx
@@ -128,7 +128,7 @@ export function Button(props: ButtonProps) {
return (
<button
- className={className}
+ className={cn(className, "relative")}
ref={props.ref}
type={props.type ?? "button"}
form={props.form}
@@ -137,15 +137,21 @@ export function Button(props: ButtonProps) {
aria-busy={props.loading}
aria-label={props.text}
>
- {props.loading ? (
- <span className="flex h-1/2 items-center justify-center">
- <Spinner size="full" />
+ <span
+ className={cn(
+ "inline-flex items-center gap-1.5",
+ props.loading && "invisible",
+ )}
+ >
+ {Icon ? <Icon className={iconClassName} aria-hidden /> : null}
+ {props.text}
+ </span>
+ {props.loading && (
+ <span className="absolute inset-0 flex items-center justify-center">
+ <span className="flex h-1/2 items-center justify-center">
+ <Spinner size="full" />
+ </span>
</span>
- ) : (
- <>
- {Icon ? <Icon className={iconClassName} aria-hidden /> : null}
- {props.text}
- </>
)}
</button>
);
diff --git a/web/src/components/design-system/LinkBadge/LinkBadge.stories.tsx b/web/src/components/design-system/LinkBadge/LinkBadge.stories.tsx
index a7c5354085..a2a754c588 100644
--- a/web/src/components/design-system/LinkBadge/LinkBadge.stories.tsx
+++ b/web/src/components/design-system/LinkBadge/LinkBadge.stories.tsx
@@ -43,3 +43,31 @@ export const RendersALink = meta.story({
await expect(link?.textContent).toContain("prompt:");
},
});
+
+export const WrapsALongValue = meta.story({
+ name: "(Test) Wraps A Long Value",
+ args: {
+ href: "https://langfuse.com/self-hosting/oss-newsletter",
+ label: undefined,
+ text: "https://langfuse.com/self-hosting/oss-newsletter",
+ shouldWrap: true,
+ },
+ render: (args) => (
+ <div className="w-40">
+ <LinkBadge {...args} />
+ </div>
+ ),
+ play: async ({ canvas, args }) => {
+ const value = canvas.getByText(args.text);
+ // The badge clips overflow, so measure the text itself: it must stay inside the box, on several lines.
+ const text = document.createRange();
+ text.selectNodeContents(value);
+ await expect(text.getClientRects().length).toBeGreaterThan(1);
+ await expect(text.getBoundingClientRect().right).toBeLessThanOrEqual(
+ value.getBoundingClientRect().right + 1,
+ );
+ await expect(
+ value.closest("a")?.getBoundingClientRect().width,
+ ).toBeLessThanOrEqual(160);
+ },
+});
diff --git a/web/src/components/design-system/LinkBadge/LinkBadge.tsx b/web/src/components/design-system/LinkBadge/LinkBadge.tsx
index d829c5f61e..46b0c0e283 100644
--- a/web/src/components/design-system/LinkBadge/LinkBadge.tsx
+++ b/web/src/components/design-system/LinkBadge/LinkBadge.tsx
@@ -12,6 +12,8 @@ type LinkBadgeProps = {
title?: string;
/** Opens in a new tab. */
newTab?: boolean;
+ /** Wraps a long value onto more lines instead of truncating it. */
+ shouldWrap?: boolean;
/** Keeps the value out of session recordings (ids, user names). */
noCapture?: boolean;
} & { [key: `data-${string}`]: string };
@@ -24,6 +26,7 @@ export function LinkBadge({
title,
newTab,
noCapture,
+ shouldWrap,
...dataProps
}: LinkBadgeProps) {
return (
@@ -44,6 +47,7 @@ export function LinkBadge({
title={title}
trailingIcon={ArrowUpRight}
trailingIconTone="link"
+ shouldWrap={shouldWrap}
{...dataProps}
/>
</Link>
diff --git a/web/src/env.mjs b/web/src/env.mjs
index be336a9d01..562ce08fa8 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -286,6 +286,7 @@ export const env = createEnv({
AUTH_IGNORE_ACCOUNT_FIELDS: z.string().optional(),
AUTH_DISABLE_USERNAME_PASSWORD: z.enum(["true", "false"]).optional(),
AUTH_DISABLE_SIGNUP: z.enum(["true", "false"]).optional(),
+ LANGFUSE_DISABLE_SIGNUP_ONBOARDING: z.enum(["true", "false"]).optional(),
AUTH_EMAIL_VERIFICATION_REQUIRED: z
.enum(["true", "false"])
.default("false"),
@@ -1027,6 +1028,8 @@ export const env = createEnv({
process.env.AUTH_DOMAINS_WITH_SSO_ENFORCEMENT,
AUTH_DISABLE_USERNAME_PASSWORD: process.env.AUTH_DISABLE_USERNAME_PASSWORD,
AUTH_DISABLE_SIGNUP: process.env.AUTH_DISABLE_SIGNUP,
+ LANGFUSE_DISABLE_SIGNUP_ONBOARDING:
+ process.env.LANGFUSE_DISABLE_SIGNUP_ONBOARDING,
AUTH_EMAIL_VERIFICATION_REQUIRED:
process.env.AUTH_EMAIL_VERIFICATION_REQUIRED,
AUTH_SESSION_MAX_AGE: process.env.AUTH_SESSION_MAX_AGE,
diff --git a/web/src/features/auth-credentials/components/ResetPasswordPage.clienttest.tsx b/web/src/features/auth-credentials/components/ResetPasswordPage.clienttest.tsx
index ee6000fbcc..5d182348d4 100644
--- a/web/src/features/auth-credentials/components/ResetPasswordPage.clienttest.tsx
+++ b/web/src/features/auth-credentials/components/ResetPasswordPage.clienttest.tsx
@@ -265,6 +265,152 @@ describe("ResetPasswordPage re-authentication", () => {
});
});
+describe("ResetPasswordPage redirect after saving the password", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ routerState.isReady = true;
+ routerState.query = {};
+ useLangfuseCloudRegionMock.mockReturnValue({
+ isLangfuseCloud: false,
+ region: undefined,
+ });
+ useSessionMock.mockReturnValue({ status: "unauthenticated", data: null });
+ mutateAsyncMock.mockResolvedValue({ success: true });
+ signInMock.mockResolvedValue({ ok: true });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ const waitForRedirect = async () => {
+ await flushPasswordSubmit();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+ };
+
+ const setFirstPassword = async () => {
+ render(
+ <ResetPasswordPage
+ passwordResetAvailable
+ initialEmail="[email protected]"
+ intent="setup"
+ />,
+ );
+ submitPasswordForm({
+ code: "654321",
+ passwordLabel: "Password",
+ confirmPasswordLabel: "Confirm Password",
+ submitLabel: "Set password",
+ });
+ await waitForRedirect();
+ };
+
+ it("sends a first self-hosted password setup through onboarding", async () => {
+ await setFirstPassword();
+
+ expect(routerPushMock).toHaveBeenCalledWith("/onboarding");
+ });
+
+ it("carries a self-hosted deep link through onboarding", async () => {
+ routerState.query = { targetPath: "/project/p1/traces?view=v1" };
+
+ await setFirstPassword();
+
+ expect(routerPushMock).toHaveBeenCalledWith(
+ "/onboarding?targetPath=%2Fproject%2Fp1%2Ftraces%3Fview%3Dv1",
+ );
+ });
+
+ it("still drops a Cloud deep link that isn't a demo link", async () => {
+ routerState.query = { targetPath: "/project/p1/traces" };
+ useLangfuseCloudRegionMock.mockReturnValue({
+ isLangfuseCloud: true,
+ region: "EU",
+ });
+
+ await setFirstPassword();
+
+ expect(routerPushMock).toHaveBeenCalledWith("/onboarding");
+ });
+
+ it("keeps an ordinary self-hosted reset going to /", async () => {
+ routerState.query = { targetPath: "/project/p1/traces" };
+ useSessionMock.mockReturnValue({
+ status: "authenticated",
+ data: { user: { email: "[email protected]", hasPassword: true } },
+ });
+
+ render(
+ <ResetPasswordPage
+ passwordResetAvailable
+ initialEmail="[email protected]"
+ intent="reset"
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Send email" }));
+ submitPasswordForm({
+ code: "123456",
+ passwordLabel: "New Password",
+ confirmPasswordLabel: "Confirm New Password",
+ submitLabel: "Update Password",
+ });
+ await waitForRedirect();
+
+ expect(routerPushMock).toHaveBeenCalledWith("/");
+ });
+
+ /** An SSO user adding a password from Account settings: reset page, no password yet. */
+ const addPasswordAsExistingUser = async () => {
+ useSessionMock.mockReturnValue({
+ status: "authenticated",
+ data: { user: { email: "[email protected]", hasPassword: false } },
+ });
+ render(
+ <ResetPasswordPage
+ passwordResetAvailable
+ initialEmail="[email protected]"
+ intent="reset"
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Send email" }));
+ submitPasswordForm({
+ code: "123456",
+ passwordLabel: "Password",
+ confirmPasswordLabel: "Confirm Password",
+ submitLabel: "Set password",
+ });
+ await waitForRedirect();
+ };
+
+ it("sends an existing self-hosted user who adds a password straight to /", async () => {
+ await addPasswordAsExistingUser();
+
+ expect(routerPushMock).toHaveBeenCalledWith("/");
+ });
+
+ it("sends an existing self-hosted user who adds a password straight to their deep link", async () => {
+ routerState.query = { targetPath: "/project/p1/traces?view=v1" };
+
+ await addPasswordAsExistingUser();
+
+ expect(routerPushMock).toHaveBeenCalledWith("/project/p1/traces?view=v1");
+ });
+
+ it("keeps Cloud routing an existing user who adds a password through onboarding", async () => {
+ useLangfuseCloudRegionMock.mockReturnValue({
+ isLangfuseCloud: true,
+ region: "EU",
+ });
+
+ await addPasswordAsExistingUser();
+
+ expect(routerPushMock).toHaveBeenCalledWith("/onboarding");
+ });
+});
+
describe("reset-password page ?email= prefill", () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx b/web/src/features/auth-credentials/components/ResetPasswordPage.tsx
index bb48ab89fe..63bf2212d5 100644
--- a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx
+++ b/web/src/features/auth-credentials/components/ResetPasswordPage.tsx
@@ -27,7 +27,7 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { passwordSchema } from "@/src/features/auth";
import { useLangfuseCloudRegion } from "@/src/features/organizations";
import { PASSWORD_SETUP_EMAIL_STORAGE_KEY } from "@/src/features/auth-credentials/lib/credentialsUtils";
-import { getDemoTargetPath } from "@/src/features/onboarding/lib/demoCallbackRedirect";
+import { getOnboardingTargetPath } from "@/src/features/onboarding/lib/demoCallbackRedirect";
import { env } from "@/src/env.mjs";
import { TURNSTILE_ACTIONS } from "@/src/features/auth/constants";
import {
@@ -75,7 +75,10 @@ export function ResetPasswordPage({
intent === "setup" || session.data?.user?.hasPassword === false;
const setupTargetPath =
isSetMode && router.isReady
- ? getDemoTargetPath(router.query.targetPath)
+ ? getOnboardingTargetPath({
+ targetPath: router.query.targetPath,
+ isLangfuseCloud,
+ })
: undefined;
const setupPasswordPath = setupTargetPath
? `/auth/setup-password?targetPath=${encodeURIComponent(setupTargetPath)}`
@@ -135,7 +138,11 @@ export function ResetPasswordPage({
}
let target = setupTargetPath ?? "/";
- if (isSetMode && isLangfuseCloud && region !== "DEV") {
+ // Self-hosted: only a new sign-up, which lands on the setup-password page; /onboarding forwards on when the step is off.
+ const goesThroughOnboarding = isLangfuseCloud
+ ? isSetMode && region !== "DEV"
+ : intent === "setup";
+ if (goesThroughOnboarding) {
target = setupTargetPath
? `/onboarding?targetPath=${encodeURIComponent(setupTargetPath)}`
: "/onboarding";
diff --git a/web/src/features/auth/SignUpPage.clienttest.tsx b/web/src/features/auth/SignUpPage.clienttest.tsx
index 6568e8038f..f55117b40f 100644
--- a/web/src/features/auth/SignUpPage.clienttest.tsx
+++ b/web/src/features/auth/SignUpPage.clienttest.tsx
@@ -1,12 +1,17 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
-const { signInMock, fetchMock, routerPushMock, envState } = vi.hoisted(() => ({
- signInMock: vi.fn(),
- fetchMock: vi.fn(),
- routerPushMock: vi.fn(),
- envState: { siteKey: undefined as string | undefined },
-}));
+const { signInMock, fetchMock, routerPushMock, routerState, envState } =
+ vi.hoisted(() => ({
+ signInMock: vi.fn(),
+ fetchMock: vi.fn(),
+ routerPushMock: vi.fn(),
+ routerState: { query: {} as Record<string, string> },
+ envState: {
+ siteKey: undefined as string | undefined,
+ region: undefined as string | undefined,
+ },
+ }));
vi.mock("next-auth/react", () => ({
signIn: (...args: unknown[]) => signInMock(...args),
@@ -16,7 +21,7 @@ vi.mock("next-auth/react", () => ({
vi.mock("next/router", () => ({
useRouter: () => ({
push: routerPushMock,
- query: {},
+ query: routerState.query,
asPath: "/auth/sign-up",
isReady: true,
}),
@@ -31,6 +36,9 @@ vi.mock("@/src/env.mjs", () => ({
get NEXT_PUBLIC_TURNSTILE_SITE_KEY() {
return envState.siteKey;
},
+ get NEXT_PUBLIC_LANGFUSE_CLOUD_REGION() {
+ return envState.region;
+ },
NEXT_PUBLIC_BASE_PATH: "",
},
}));
@@ -100,7 +108,9 @@ describe("VerifiedSignupFlow captcha", () => {
});
vi.stubGlobal("fetch", fetchMock);
routerPushMock.mockReset();
+ routerState.query = {};
envState.siteKey = undefined;
+ envState.region = undefined;
});
it("sends the setup code without a captcha token when Turnstile is off", async () => {
@@ -169,3 +179,52 @@ describe("VerifiedSignupFlow captcha", () => {
expect(fetchMock).toHaveBeenCalledOnce();
});
});
+
+describe("VerifiedSignupFlow target path", () => {
+ beforeEach(() => {
+ signInMock.mockReset();
+ signInMock.mockResolvedValue({ ok: true, error: null });
+ fetchMock.mockReset();
+ fetchMock.mockResolvedValue({ ok: true, json: async () => ({}) });
+ vi.stubGlobal("fetch", fetchMock);
+ routerPushMock.mockReset();
+ envState.siteKey = undefined;
+ });
+
+ it.each([
+ {
+ region: undefined,
+ targetPath: "/project/p1/traces?view=v1",
+ setupPasswordPath:
+ "/auth/setup-password?targetPath=%2Fproject%2Fp1%2Ftraces%3Fview%3Dv1",
+ },
+ {
+ region: "EU",
+ targetPath: "/demo/datasets",
+ setupPasswordPath: "/auth/setup-password?targetPath=%2Fdemo%2Fdatasets",
+ },
+ {
+ region: "EU",
+ targetPath: "/project/p1/traces",
+ setupPasswordPath: "/auth/setup-password",
+ },
+ ])(
+ "sends $targetPath on to $setupPasswordPath (Cloud region $region)",
+ async ({ region, targetPath, setupPasswordPath }) => {
+ envState.region = region;
+ routerState.query = { targetPath };
+ renderVerifiedSignup();
+ await fillSignupForm();
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+
+ await waitFor(() => {
+ expect(routerPushMock).toHaveBeenCalledWith(setupPasswordPath);
+ });
+ expect(signInMock).toHaveBeenCalledWith("email", {
+ email: "[email protected]",
+ callbackUrl: setupPasswordPath,
+ redirect: false,
+ });
+ },
+ );
+});
diff --git a/web/src/features/auth/SignUpPage.tsx b/web/src/features/auth/SignUpPage.tsx
index 8f28d7765a..1157c41311 100644
--- a/web/src/features/auth/SignUpPage.tsx
+++ b/web/src/features/auth/SignUpPage.tsx
@@ -35,7 +35,10 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import useLocalStorage from "@/src/components/useLocalStorage";
import { noUrlCheck, StringNoHTMLNonEmpty } from "@langfuse/shared";
import { PASSWORD_SETUP_EMAIL_STORAGE_KEY } from "@/src/features/auth-credentials";
-import { getDemoTargetPath } from "@/src/features/onboarding/lib/demoCallbackRedirect";
+import {
+ getOnboardingTargetPath,
+ getSignupCallbackUrl,
+} from "@/src/features/onboarding/lib/demoCallbackRedirect";
import {
TurnstileWidget,
type TurnstileWidgetHandle,
@@ -252,20 +255,10 @@ function StandardSignupFlow({
values: z.infer<typeof signupSchema>,
loginTurnstileToken: string | undefined,
) {
- let callbackUrl =
- targetPath ??
- (isLangfuseCloud
- ? `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding`
- : `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/`);
- const demoTargetPath = getDemoTargetPath(targetPath);
- if (isLangfuseCloud && demoTargetPath) {
- callbackUrl = `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding?targetPath=${encodeURIComponent(demoTargetPath)}`;
- }
-
await signIn<"credentials">("credentials", {
email: values.email,
password: values.password,
- callbackUrl,
+ callbackUrl: getSignupCallbackUrl({ targetPath, isLangfuseCloud }),
turnstileToken: loginTurnstileToken,
});
}
@@ -435,6 +428,7 @@ function StandardSignupFlow({
function VerifiedSignupFlow({
authProviders,
}: Pick<PageProps, "authProviders" | "emailVerificationRequired">) {
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
const router = useRouter();
const capture = usePostHogClientCapture();
const emailParam = router.query.email as string | undefined;
@@ -442,9 +436,12 @@ function VerifiedSignupFlow({
const targetPath = queryTargetPath
? getSafeRedirectPath(queryTargetPath)
: undefined;
- const demoTargetPath = getDemoTargetPath(targetPath);
- const setupPasswordPath = demoTargetPath
- ? `/auth/setup-password?targetPath=${encodeURIComponent(demoTargetPath)}`
+ const setupTargetPath = getOnboardingTargetPath({
+ targetPath,
+ isLangfuseCloud,
+ });
+ const setupPasswordPath = setupTargetPath
+ ? `/auth/setup-password?targetPath=${encodeURIComponent(setupTargetPath)}`
: "/auth/setup-password";
const [formError, setFormError] = useState<string | null>(null);
diff --git a/web/src/features/onboarding/components/ConnectedOnboardingSurvey.clienttest.tsx b/web/src/features/onboarding/components/ConnectedOnboardingSurvey.clienttest.tsx
new file mode 100644
index 0000000000..2cc8c51f08
--- /dev/null
+++ b/web/src/features/onboarding/components/ConnectedOnboardingSurvey.clienttest.tsx
@@ -0,0 +1,351 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const {
+ completeMock,
+ harness,
+ locationAssignMock,
+ reportErrorMock,
+ routerReplaceMock,
+ setDataMock,
+ showErrorToastMock,
+ statusState,
+ subscribeMock,
+} = vi.hoisted(() => ({
+ completeMock: vi.fn(),
+ harness: {
+ isLangfuseCloud: false,
+ query: {} as Record<string, string>,
+ canCreateOrganizations: true,
+ organizations: [] as { id: string }[],
+ },
+ locationAssignMock: vi.fn(),
+ reportErrorMock: vi.fn(),
+ routerReplaceMock: vi.fn(),
+ setDataMock: vi.fn(),
+ showErrorToastMock: vi.fn(),
+ statusState: {
+ query: {} as {
+ data?: unknown;
+ isLoading: boolean;
+ isError: boolean;
+ error?: unknown;
+ },
+ },
+ subscribeMock: vi.fn(),
+}));
+
+vi.mock("next/router", () => ({
+ useRouter: () => ({
+ isReady: true,
+ query: harness.query,
+ replace: routerReplaceMock,
+ }),
+}));
+
+vi.mock("next-auth/react", () => ({
+ useSession: () => ({
+ data: {
+ user: {
+ email: "[email protected]",
+ canCreateOrganizations: harness.canCreateOrganizations,
+ organizations: harness.organizations,
+ },
+ },
+ update: vi.fn(async () => undefined),
+ }),
+}));
+
+vi.mock("@/src/features/organizations", () => ({
+ useLangfuseCloudRegion: () => ({ isLangfuseCloud: harness.isLangfuseCloud }),
+}));
+
+vi.mock("@/src/features/posthog-analytics", () => ({
+ usePostHogClientCapture: () => vi.fn(),
+}));
+
+vi.mock("@/src/features/notifications", () => ({
+ showErrorToast: (...args: unknown[]) => showErrorToastMock(...args),
+}));
+
+vi.mock("@/src/utils/reportError", () => ({
+ reportError: (...args: unknown[]) => reportErrorMock(...args),
+}));
+
+vi.mock("@/src/utils/trpcErrorClassification", () => ({
+ classifyTrpcToastError: () => ({}),
+}));
+
+vi.mock("@/src/utils/api", () => ({
+ api: {
+ useUtils: () => ({ onboarding: { status: { setData: setDataMock } } }),
+ onboarding: {
+ status: { useQuery: () => statusState.query },
+ complete: { useMutation: () => ({ mutateAsync: completeMock }) },
+ },
+ },
+}));
+
+vi.mock("../hooks/useNewsletterSignup", () => ({
+ useNewsletterSignup: () => ({
+ reachability: "reachable",
+ subscribe: subscribeMock,
+ }),
+}));
+
+import { ConnectedOnboardingSurvey } from "./ConnectedOnboardingSurvey";
+
+const INSTALLER_LISTS = ["product", "oss"];
+const INCOMPLETE_STATUS = {
+ data: {
+ completed: false,
+ canConfigureAiFeatures: false,
+ newsletterLists: INSTALLER_LISTS,
+ },
+ isLoading: false,
+ isError: false,
+};
+const FAILED_STATUS = {
+ data: undefined,
+ isLoading: false,
+ isError: true,
+ error: new Error("status failed"),
+};
+const originalLocation = window.location;
+
+beforeEach(() => {
+ // The design-system Switch measures its thumb; jsdom has no ResizeObserver.
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ value: { ...originalLocation, assign: locationAssignMock },
+ });
+ completeMock.mockReset();
+ locationAssignMock.mockReset();
+ reportErrorMock.mockReset();
+ routerReplaceMock.mockReset();
+ setDataMock.mockReset();
+ showErrorToastMock.mockReset();
+ subscribeMock.mockReset();
+ statusState.query = INCOMPLETE_STATUS;
+ Object.assign(harness, {
+ isLangfuseCloud: false,
+ query: {},
+ canCreateOrganizations: true,
+ organizations: [],
+ });
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ value: originalLocation,
+ });
+});
+
+const clickButton = (name: string) =>
+ fireEvent.click(screen.getByRole("button", { name }));
+
+describe("ConnectedOnboardingSurvey on self-hosted", () => {
+ it("shows a neutral card while the onboarding status loads", () => {
+ statusState.query = { data: undefined, isLoading: true, isError: false };
+
+ render(<ConnectedOnboardingSurvey />);
+
+ expect(
+ screen.getByRole("heading", { name: "Getting your workspace ready" }),
+ ).toBeVisible();
+ expect(screen.queryByText(/langfuse\.com/)).not.toBeInTheDocument();
+ expect(screen.queryByText(/Finishing setup/)).not.toBeInTheDocument();
+ });
+
+ it("shows the neutral card while redirecting a completed status", async () => {
+ statusState.query = {
+ data: { completed: true, redirectTo: "/setup" },
+ isLoading: false,
+ isError: false,
+ };
+
+ render(<ConnectedOnboardingSurvey />);
+
+ expect(
+ screen.getByRole("heading", { name: "Getting your workspace ready" }),
+ ).toBeVisible();
+ expect(screen.queryByText(/Finishing setup/)).not.toBeInTheDocument();
+ await waitFor(() =>
+ expect(routerReplaceMock).toHaveBeenCalledWith("/setup"),
+ );
+ });
+
+ it("skips without subscribing and stores declined", async () => {
+ completeMock.mockResolvedValue({
+ redirectTo: "/setup",
+ surveyCreated: true,
+ });
+
+ render(<ConnectedOnboardingSurvey />);
+ clickButton("Skip");
+
+ await waitFor(() =>
+ expect(routerReplaceMock).toHaveBeenCalledWith("/setup"),
+ );
+ expect(subscribeMock).not.toHaveBeenCalled();
+ expect(completeMock.mock.calls).toEqual([
+ [{ newsletter: { outcome: "declined" } }],
+ ]);
+ });
+
+ it("subscribes the address to the step's lists and stores subscribed", async () => {
+ subscribeMock.mockResolvedValue("subscribed");
+ completeMock.mockResolvedValue({
+ redirectTo: "/setup",
+ surveyCreated: true,
+ });
+
+ render(<ConnectedOnboardingSurvey />);
+ clickButton("Subscribe");
+
+ await waitFor(() =>
+ expect(routerReplaceMock).toHaveBeenCalledWith("/setup"),
+ );
+ expect(subscribeMock).toHaveBeenCalledWith({
+ email: "[email protected]",
+ lists: INSTALLER_LISTS,
+ });
+ expect(completeMock.mock.calls).toEqual([
+ [{ newsletter: { outcome: "subscribed" } }],
+ ]);
+ });
+
+ it.each([
+ { query: { targetPath: "/demo" }, canCreate: false, destination: "/demo" },
+ { query: {}, canCreate: true, destination: "/setup" },
+ { query: {}, canCreate: false, destination: "/" },
+ ])(
+ "goes to $destination without a toast when saving the outcome fails (query $query, can create orgs $canCreate)",
+ async ({ query, canCreate, destination }) => {
+ Object.assign(harness, { query, canCreateOrganizations: canCreate });
+ completeMock.mockRejectedValue(new Error("network"));
+
+ render(<ConnectedOnboardingSurvey />);
+ clickButton("Skip");
+
+ await waitFor(() =>
+ expect(routerReplaceMock).toHaveBeenCalledWith(destination),
+ );
+ expect(showErrorToastMock).not.toHaveBeenCalled();
+ expect(reportErrorMock).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it("goes to the destination without the error card when the status fails", async () => {
+ statusState.query = FAILED_STATUS;
+
+ render(<ConnectedOnboardingSurvey />);
+
+ await waitFor(() =>
+ expect(routerReplaceMock).toHaveBeenCalledWith("/setup"),
+ );
+ expect(
+ screen.queryByText("Failed to load onboarding"),
+ ).not.toBeInTheDocument();
+ expect(showErrorToastMock).not.toHaveBeenCalled();
+ expect(reportErrorMock).toHaveBeenCalledWith(
+ FAILED_STATUS.error,
+ expect.objectContaining({ area: "onboarding" }),
+ );
+ });
+
+ it("sends an invited member to / when the status fails", async () => {
+ harness.organizations = [{ id: "org-invited" }];
+ statusState.query = FAILED_STATUS;
+
+ render(<ConnectedOnboardingSurvey />);
+
+ await waitFor(() => expect(routerReplaceMock).toHaveBeenCalledWith("/"));
+ expect(routerReplaceMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("loads the page when the client-side redirect fails", async () => {
+ completeMock.mockResolvedValue({
+ redirectTo: "/setup",
+ surveyCreated: true,
+ });
+ routerReplaceMock.mockRejectedValue(new Error("route change failed"));
+
+ render(<ConnectedOnboardingSurvey />);
+ clickButton("Skip");
+
+ await waitFor(() =>
+ expect(locationAssignMock).toHaveBeenCalledWith(
+ `${originalLocation.origin}/setup`,
+ ),
+ );
+ expect(showErrorToastMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("ConnectedOnboardingSurvey on Cloud", () => {
+ beforeEach(() => {
+ harness.isLangfuseCloud = true;
+ });
+
+ it("keeps the error card when the status fails", () => {
+ statusState.query = FAILED_STATUS;
+
+ render(<ConnectedOnboardingSurvey />);
+
+ expect(screen.getByText("Failed to load onboarding")).toBeVisible();
+ expect(routerReplaceMock).not.toHaveBeenCalled();
+ });
+
+ it("keeps the toast and stays on the survey when saving fails", async () => {
+ statusState.query = {
+ data: { completed: false, canConfigureAiFeatures: false },
+ isLoading: false,
+ isError: false,
+ };
+ completeMock.mockRejectedValue(new Error("network"));
+
+ render(<ConnectedOnboardingSurvey />);
+ clickButton("Next");
+
+ await waitFor(() =>
+ expect(showErrorToastMock).toHaveBeenCalledWith(
+ "Failed to finish onboarding",
+ "network",
+ expect.anything(),
+ ),
+ );
+ expect(routerReplaceMock).not.toHaveBeenCalled();
+ expect(reportErrorMock).not.toHaveBeenCalled();
+ });
+
+ it("keeps the toast when the redirect of a completed status fails", async () => {
+ statusState.query = {
+ data: { completed: true, redirectTo: "/project/p1/traces" },
+ isLoading: false,
+ isError: false,
+ };
+ routerReplaceMock.mockRejectedValue(new Error("route change failed"));
+
+ render(<ConnectedOnboardingSurvey />);
+
+ await waitFor(() =>
+ expect(showErrorToastMock).toHaveBeenCalledWith(
+ "Failed to continue onboarding",
+ "route change failed",
+ expect.anything(),
+ ),
+ );
+ expect(locationAssignMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/features/onboarding/components/ConnectedOnboardingSurvey.tsx b/web/src/features/onboarding/components/ConnectedOnboardingSurvey.tsx
index a77503051f..82eae3eef8 100644
--- a/web/src/features/onboarding/components/ConnectedOnboardingSurvey.tsx
+++ b/web/src/features/onboarding/components/ConnectedOnboardingSurvey.tsx
@@ -1,82 +1,122 @@
import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/router";
import { useSession } from "next-auth/react";
+import { env } from "@/src/env.mjs";
import { showErrorToast } from "@/src/features/notifications";
+import { useLangfuseCloudRegion } from "@/src/features/organizations";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { useWatchedPromiseCallback } from "@/src/hooks/useWatchedPromiseCallback";
-import { api } from "@/src/utils/api";
+import { api, type RouterInputs, type RouterOutputs } from "@/src/utils/api";
+import { reportError } from "@/src/utils/reportError";
import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
-import { getDemoCallbackRedirectPath } from "../lib/demoCallbackRedirect";
+import {
+ getDeepLinkCallbackRedirectPath,
+ getDemoCallbackRedirectPath,
+} from "../lib/demoCallbackRedirect";
import {
getSurveySubmittedEvent,
shuffleBuildIntentOptions,
} from "../lib/buildIntent";
+import { getFallbackRedirectPath } from "../lib/fallbackRedirect";
+import {
+ type NewsletterList,
+ type NewsletterOutcome,
+} from "../lib/newsletterSignup";
import type { SurveyFormData } from "../lib/surveyTypes";
+import { useNewsletterSignup } from "../hooks/useNewsletterSignup";
+import { NewsletterOptIn, type NewsletterOptInValues } from "./NewsletterOptIn";
import { OnboardingSurvey } from "./OnboardingSurvey";
export function ConnectedOnboardingSurvey() {
const router = useRouter();
- const { update: updateSession } = useSession();
+ const { data: session, update: updateSession } = useSession();
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
const capture = usePostHogClientCapture();
const utils = api.useUtils();
- const onboardingStatus = api.onboarding.status.useQuery();
- const completeOnboardingMutation = api.onboarding.complete.useMutation();
+ // Self-hosted reports a failed step and moves on (below), so its default error toasts stay off.
+ const onboardingStatus = api.onboarding.status.useQuery(undefined, {
+ meta: { silentAllErrors: !isLangfuseCloud },
+ });
+ const completeOnboardingMutation = api.onboarding.complete.useMutation(
+ isLangfuseCloud ? undefined : { onError: () => undefined },
+ );
+ /** Cloud forwards demo links only; self-hosted forwards any same-origin deep link. */
+ const getQueryRedirectPath = isLangfuseCloud
+ ? getDemoCallbackRedirectPath
+ : getDeepLinkCallbackRedirectPath;
const queryRedirectPath = router.isReady
- ? (getDemoCallbackRedirectPath(router.query.targetPath) ??
- getDemoCallbackRedirectPath(router.query.callbackUrl))
+ ? (getQueryRedirectPath(router.query.targetPath) ??
+ getQueryRedirectPath(router.query.callbackUrl))
: undefined;
const [hasStartedOnboardingCompletion, setHasStartedOnboardingCompletion] =
useState(false);
const [onboardingOpenedAt] = useState(() => Date.now());
const [buildIntentOptions] = useState(shuffleBuildIntentOptions);
+ const newsletterLists =
+ onboardingStatus.data?.completed === false
+ ? onboardingStatus.data.newsletterLists
+ : undefined;
+ /** Where self-hosted goes when the step fails: the deep link, else the shared fallback. The demo org doesn't count, as on the server. */
+ const fallbackDestination =
+ queryRedirectPath ??
+ getFallbackRedirectPath({
+ hasOrganizations:
+ session?.user?.organizations.some(
+ (organization) => organization.id !== env.NEXT_PUBLIC_DEMO_ORG_ID,
+ ) ?? false,
+ canCreateOrganizations: session?.user?.canCreateOrganizations ?? false,
+ });
- const [finishOnboarding, isFinishingOnboarding] = useWatchedPromiseCallback(
- async (data: SurveyFormData) => {
+ /** On self-hosted, a failed client-side redirect falls back to loading the same path. */
+ const replaceRoute = useCallback(
+ async (path: string) => {
+ try {
+ await router.replace(path);
+ } catch (error) {
+ if (isLangfuseCloud) throw error;
+ reportError(error, {
+ area: "onboarding",
+ warnMessage: "Onboarding redirect failed; loading the page instead",
+ });
+ // The client-side router just failed, so a full page load is the fallback.
+ const destination = new URL(
+ `${env.NEXT_PUBLIC_BASE_PATH ?? ""}${path}`,
+ window.location.origin,
+ );
+ window.location.assign(destination.href);
+ }
+ },
+ [isLangfuseCloud, router],
+ );
+
+ const [completeOnboarding, isFinishingOnboarding] = useWatchedPromiseCallback(
+ async (
+ input: OnboardingCompletionInput,
+ onCompleted?: (result: OnboardingCompletionResult) => void,
+ ) => {
setHasStartedOnboardingCompletion(true);
+ let redirectTo: string | undefined;
try {
- const referralSource = data.referralSource?.trim();
- const canConfigureAiFeatures =
- onboardingStatus.data?.completed === false &&
- onboardingStatus.data.canConfigureAiFeatures;
- const buildIntents = data.buildIntents;
- const buildIntentOther = data.buildIntentOther?.trim();
- const onboardingResult = await completeOnboardingMutation.mutateAsync({
- ...(referralSource ? { referralSource } : {}),
- ...(canConfigureAiFeatures
- ? { aiFeaturesEnabled: data.aiFeaturesEnabled }
- : {}),
- ...(buildIntents.length > 0
- ? {
- buildIntents,
- buildIntentPositions: buildIntents.map((id) =>
- buildIntentOptions.findIndex((option) => option.id === id),
- ),
- }
- : {}),
- ...(buildIntentOther ? { buildIntentOther } : {}),
- });
- const surveySubmittedEvent = getSurveySubmittedEvent({
- surveyCreated: onboardingResult.surveyCreated,
- buildIntents,
- hasReferralSource: Boolean(referralSource),
- surveyDurationMs: Date.now() - onboardingOpenedAt,
- });
- if (surveySubmittedEvent) {
- capture(
- "onboarding:signup_survey_submitted",
- surveySubmittedEvent.properties,
- surveySubmittedEvent.options,
- );
- }
- const redirectTo = queryRedirectPath ?? onboardingResult.redirectTo;
+ const onboardingResult =
+ await completeOnboardingMutation.mutateAsync(input);
+ onCompleted?.(onboardingResult);
+ redirectTo = queryRedirectPath ?? onboardingResult.redirectTo;
utils.onboarding.status.setData(undefined, {
completed: true,
redirectTo,
});
await updateSession();
- await router.replace(redirectTo);
+ await replaceRoute(redirectTo);
} catch (error) {
+ if (!isLangfuseCloud) {
+ reportError(error, {
+ area: "onboarding",
+ warnMessage: "Saving the onboarding step failed; continuing",
+ });
+ await replaceRoute(redirectTo ?? fallbackDestination);
+ return;
+ }
setHasStartedOnboardingCompletion(false);
showErrorToast(
"Failed to finish onboarding",
@@ -86,13 +126,11 @@ export function ConnectedOnboardingSurvey() {
}
},
[
- capture,
- onboardingOpenedAt,
- buildIntentOptions,
completeOnboardingMutation,
- onboardingStatus.data,
+ fallbackDestination,
+ isLangfuseCloud,
queryRedirectPath,
- router,
+ replaceRoute,
updateSession,
utils,
],
@@ -104,8 +142,9 @@ export function ConnectedOnboardingSurvey() {
setHasStartedOnboardingCompletion(true);
try {
- await router.replace(redirectTo);
+ await replaceRoute(redirectTo);
} catch (error) {
+ // Only Cloud gets here; self-hosted falls back to loading the page.
setHasStartedOnboardingCompletion(false);
showErrorToast(
"Failed to continue onboarding",
@@ -118,7 +157,7 @@ export function ConnectedOnboardingSurvey() {
);
}
},
- [router],
+ [replaceRoute],
);
useEffect(() => {
@@ -139,23 +178,128 @@ export function ConnectedOnboardingSurvey() {
router.isReady,
]);
+ useEffect(() => {
+ if (
+ isLangfuseCloud ||
+ !router.isReady ||
+ !onboardingStatus.isError ||
+ hasStartedOnboardingCompletion
+ ) {
+ return;
+ }
+
+ reportError(onboardingStatus.error, {
+ area: "onboarding",
+ warnMessage: "Loading the onboarding status failed; continuing",
+ });
+ setHasStartedOnboardingCompletion(true);
+ replaceRoute(fallbackDestination).catch(() => undefined);
+ }, [
+ fallbackDestination,
+ hasStartedOnboardingCompletion,
+ isLangfuseCloud,
+ onboardingStatus.error,
+ onboardingStatus.isError,
+ replaceRoute,
+ router.isReady,
+ ]);
+
const onSubmit = useCallback(
async (data: SurveyFormData) => {
- await finishOnboarding(data);
+ const referralSource = data.referralSource?.trim();
+ const canConfigureAiFeatures =
+ onboardingStatus.data?.completed === false &&
+ onboardingStatus.data.canConfigureAiFeatures;
+ const buildIntents = data.buildIntents;
+ const buildIntentOther = data.buildIntentOther?.trim();
+ const captureSurveySubmitted = ({
+ surveyCreated,
+ }: OnboardingCompletionResult) => {
+ const surveySubmittedEvent = getSurveySubmittedEvent({
+ surveyCreated,
+ buildIntents,
+ hasReferralSource: Boolean(referralSource),
+ surveyDurationMs: Date.now() - onboardingOpenedAt,
+ });
+ if (surveySubmittedEvent) {
+ capture(
+ "onboarding:signup_survey_submitted",
+ surveySubmittedEvent.properties,
+ surveySubmittedEvent.options,
+ );
+ }
+ };
+
+ await completeOnboarding(
+ {
+ ...(referralSource ? { referralSource } : {}),
+ ...(canConfigureAiFeatures
+ ? { aiFeaturesEnabled: data.aiFeaturesEnabled }
+ : {}),
+ ...(buildIntents.length > 0
+ ? {
+ buildIntents,
+ buildIntentPositions: buildIntents.map((id) =>
+ buildIntentOptions.findIndex((option) => option.id === id),
+ ),
+ }
+ : {}),
+ ...(buildIntentOther ? { buildIntentOther } : {}),
+ },
+ captureSurveySubmitted,
+ );
},
- [finishOnboarding],
+ [
+ buildIntentOptions,
+ capture,
+ completeOnboarding,
+ onboardingOpenedAt,
+ onboardingStatus.data,
+ ],
);
+ const completeNewsletterStep = (outcome: NewsletterOutcome) =>
+ completeOnboarding({ newsletter: { outcome } });
+
+ const isLoadingOnboarding = !router.isReady || onboardingStatus.isLoading;
const isCompletingOnboarding =
hasStartedOnboardingCompletion ||
isFinishingOnboarding ||
isRedirectingCompletedOnboarding ||
- !router.isReady ||
- onboardingStatus.isLoading ||
+ isLoadingOnboarding ||
onboardingStatus.data?.completed === true;
+ // A completed status the user didn't just finish here (step off, or done before) is only a redirect.
+ const isBouncingCompletedOnboarding =
+ onboardingStatus.data?.completed === true && !isFinishingOnboarding;
+
+ if (
+ !isLangfuseCloud &&
+ (isLoadingOnboarding ||
+ isBouncingCompletedOnboarding ||
+ onboardingStatus.isError)
+ ) {
+ return <NewsletterOptIn state="loading" />;
+ }
+
+ // Stays mounted while completing, so Subscribe or Skip shows its progress; status flips only on success.
+ if (newsletterLists) {
+ return (
+ <NewsletterOptInStep
+ lists={newsletterLists}
+ defaultEmail={session?.user?.email ?? ""}
+ isCompleting={hasStartedOnboardingCompletion}
+ onComplete={completeNewsletterStep}
+ />
+ );
+ }
+
if (isCompletingOnboarding) {
- return <OnboardingSurvey state="completing" />;
+ return isLangfuseCloud ? (
+ <OnboardingSurvey state="completing" />
+ ) : (
+ <NewsletterOptIn state="completing" />
+ );
}
if (onboardingStatus.isError) {
@@ -175,3 +319,73 @@ export function ConnectedOnboardingSurvey() {
/>
);
}
+
+function NewsletterOptInStep({
+ lists,
+ defaultEmail,
+ isCompleting,
+ onComplete,
+}: {
+ lists: NewsletterList[];
+ defaultEmail: string;
+ isCompleting: boolean;
+ onComplete: (outcome: NewsletterOutcome) => Promise<void>;
+}) {
+ const { reachability, subscribe } = useNewsletterSignup();
+ const [hasSignupFailed, setHasSignupFailed] = useState(false);
+
+ const subscribeWithAddress = async ({ email }: NewsletterOptInValues) => {
+ const outcome = await subscribe({ email, lists });
+ if (outcome === "failed") {
+ setHasSignupFailed(true);
+ return;
+ }
+
+ await onComplete(outcome);
+ };
+
+ const skipSignup = () => onComplete("declined");
+
+ const continueWithoutSignup = () =>
+ onComplete(hasSignupFailed ? "failed" : "unreachable");
+
+ if (hasSignupFailed) {
+ return (
+ <NewsletterOptIn
+ state="failed"
+ lists={lists}
+ isContinuing={isCompleting}
+ onContinue={continueWithoutSignup}
+ />
+ );
+ }
+
+ switch (reachability) {
+ case "checking":
+ return <NewsletterOptIn state="loading" />;
+ case "unreachable":
+ return (
+ <NewsletterOptIn
+ state="unreachable"
+ lists={lists}
+ isContinuing={isCompleting}
+ onContinue={continueWithoutSignup}
+ />
+ );
+ case "reachable":
+ return (
+ <NewsletterOptIn
+ state="form"
+ lists={lists}
+ defaultEmail={defaultEmail}
+ onSubscribe={subscribeWithAddress}
+ onSkip={skipSignup}
+ />
+ );
+ }
+}
+
+type OnboardingCompletionInput = NonNullable<
+ RouterInputs["onboarding"]["complete"]
+>;
+type OnboardingCompletionResult = RouterOutputs["onboarding"]["complete"];
diff --git a/web/src/features/onboarding/components/NewsletterOptIn.stories.tsx b/web/src/features/onboarding/components/NewsletterOptIn.stories.tsx
new file mode 100644
index 0000000000..b61c97df6f
--- /dev/null
+++ b/web/src/features/onboarding/components/NewsletterOptIn.stories.tsx
@@ -0,0 +1,390 @@
+import {
+ expect,
+ fireEvent,
+ fn,
+ userEvent,
+ waitFor,
+ within,
+} from "storybook/test";
+import preview from "../../../../.storybook/preview";
+import { NewsletterOptIn } from "./NewsletterOptIn";
+
+const meta = preview.meta({
+ component: NewsletterOptIn,
+ parameters: { layout: "fullscreen" },
+});
+
+const INSTALLER_DESCRIPTION =
+ "Monthly product updates, plus a heads-up when a new major version or a required upgrade affects your instance.";
+const INVITED_DESCRIPTION =
+ "One email a month with the newest Langfuse features and improvements.";
+
+const formArgs = (lists: ("product" | "oss")[], defaultEmail: string) => ({
+ state: "form" as const,
+ lists,
+ defaultEmail,
+ onSubscribe: fn(async () => undefined),
+ onSkip: fn(async () => undefined),
+});
+
+export const InstallerForm = meta.story({
+ args: formArgs(["product", "oss"], "[email protected]"),
+});
+
+export const InvitedForm = meta.story({
+ args: formArgs(["product"], "[email protected]"),
+});
+
+export const LoadingAndConnectionCheck = meta.story({
+ args: {
+ state: "loading",
+ },
+});
+
+export const InstallerUnreachable = meta.story({
+ args: {
+ state: "unreachable",
+ lists: ["product", "oss"],
+ isContinuing: false,
+ onContinue: fn(),
+ },
+});
+
+export const InvitedUnreachable = meta.story({
+ args: {
+ state: "unreachable",
+ lists: ["product"],
+ isContinuing: false,
+ onContinue: fn(),
+ },
+});
+
+export const InstallerFailed = meta.story({
+ args: {
+ state: "failed",
+ lists: ["product", "oss"],
+ isContinuing: false,
+ onContinue: fn(),
+ },
+});
+
+export const InvitedFailed = meta.story({
+ args: {
+ state: "failed",
+ lists: ["product"],
+ isContinuing: false,
+ onContinue: fn(),
+ },
+});
+
+export const FailedWhileContinuing = meta.story({
+ args: {
+ state: "failed",
+ lists: ["product", "oss"],
+ isContinuing: true,
+ onContinue: fn(),
+ },
+});
+
+export const Completing = meta.story({
+ args: {
+ state: "completing",
+ },
+});
+
+export const ShowsTheInstallerCopy = meta.story({
+ name: "(Test) Shows The Installer Copy",
+ args: formArgs(["product", "oss"], "[email protected]"),
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(canvas.getByText(INSTALLER_DESCRIPTION)).toBeInTheDocument();
+ await expect(canvas.getByRole("textbox", { name: "Email" })).toHaveValue(
+ );
+ const skip = canvas.getByRole("button", { name: "Skip" });
+ const subscribe = canvas.getByRole("button", { name: "Subscribe" });
+ await expect(subscribe.nextElementSibling).toBe(skip);
+ await expect(canvas.queryByRole("switch")).not.toBeInTheDocument();
+ },
+});
+
+export const ShowsTheInvitedCopy = meta.story({
+ name: "(Test) Shows The Invited Copy",
+ args: formArgs(["product"], "[email protected]"),
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(canvas.getByText(INVITED_DESCRIPTION)).toBeInTheDocument();
+ await expect(
+ canvas.queryByText(INSTALLER_DESCRIPTION),
+ ).not.toBeInTheDocument();
+ },
+});
+
+const skipArgs = formArgs(["product", "oss"], "[email protected]");
+
+export const SkipsWithoutSubscribing = meta.story({
+ name: "(Test) Skips Without Subscribing",
+ args: skipArgs,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await userEvent.click(canvas.getByRole("button", { name: "Skip" }));
+
+ await expect(skipArgs.onSkip).toHaveBeenCalledTimes(1);
+ await expect(skipArgs.onSubscribe).not.toHaveBeenCalled();
+ },
+});
+
+const subscribeArgs = formArgs(["product", "oss"], "[email protected]");
+
+export const SubscribesWithThePrefilledAddress = meta.story({
+ name: "(Test) Subscribes With The Prefilled Address",
+ args: subscribeArgs,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await userEvent.click(canvas.getByRole("button", { name: "Subscribe" }));
+
+ await expect(subscribeArgs.onSubscribe).toHaveBeenCalledWith(
+ { email: "[email protected]" },
+ expect.anything(),
+ );
+ await expect(subscribeArgs.onSkip).not.toHaveBeenCalled();
+ },
+});
+
+const editedArgs = formArgs(["product"], "[email protected]");
+
+export const SubscribesAnEditedAddressOnEnter = meta.story({
+ name: "(Test) Subscribes An Edited Address On Enter",
+ args: editedArgs,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const email = canvas.getByRole("textbox", { name: "Email" });
+
+ await userEvent.clear(email);
+ await userEvent.type(email, " [email protected] {Enter}");
+
+ await expect(editedArgs.onSubscribe).toHaveBeenCalledWith(
+ { email: "[email protected]" },
+ expect.anything(),
+ );
+ },
+});
+
+const invalidArgs = formArgs(["product", "oss"], "[email protected]");
+
+export const RejectsAnEmptyOrInvalidAddress = meta.story({
+ name: "(Test) Rejects An Empty Or Invalid Address",
+ args: invalidArgs,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const email = canvas.getByRole("textbox", { name: "Email" });
+ const subscribe = canvas.getByRole("button", { name: "Subscribe" });
+
+ await userEvent.clear(email);
+ await userEvent.click(subscribe);
+ await expect(
+ await canvas.findByText("Enter a valid email address"),
+ ).toBeInTheDocument();
+
+ await userEvent.type(email, "not-an-email");
+ await userEvent.click(subscribe);
+ await expect(
+ canvas.getByText("Enter a valid email address"),
+ ).toBeInTheDocument();
+ await expect(invalidArgs.onSubscribe).not.toHaveBeenCalled();
+ },
+});
+
+const skipInvalidArgs = formArgs(["product", "oss"], "[email protected]");
+
+export const SkipsWithAnInvalidAddress = meta.story({
+ name: "(Test) Skips With An Invalid Address",
+ args: skipInvalidArgs,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const email = canvas.getByRole("textbox", { name: "Email" });
+
+ await userEvent.clear(email);
+ await userEvent.type(email, "not-an-email");
+ await userEvent.click(canvas.getByRole("button", { name: "Skip" }));
+
+ await expect(skipInvalidArgs.onSkip).toHaveBeenCalledTimes(1);
+ await expect(
+ canvas.queryByText("Enter a valid email address"),
+ ).not.toBeInTheDocument();
+ },
+});
+
+const pendingSubscribeArgs = {
+ ...formArgs(["product", "oss"], "[email protected]"),
+ onSubscribe: fn(() => new Promise<void>(() => undefined)),
+};
+
+export const DisablesSkipWhileSubscribing = meta.story({
+ name: "(Test) Disables Skip While Subscribing",
+ args: pendingSubscribeArgs,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const subscribe = canvas.getByRole("button", { name: "Subscribe" });
+ const skip = canvas.getByRole("button", { name: "Skip" });
+ const widthBefore = subscribe.getBoundingClientRect().width;
+ const skipLeftBefore = skip.getBoundingClientRect().left;
+
+ await userEvent.click(subscribe);
+
+ await waitFor(() => expect(subscribe).toHaveAttribute("aria-busy", "true"));
+ await expect(skip).toBeDisabled();
+ await expect(subscribe.getBoundingClientRect().width).toBe(widthBefore);
+ await expect(skip.getBoundingClientRect().left).toBe(skipLeftBefore);
+ },
+});
+
+export const InvitedFallbackLinks = meta.story({
+ name: "(Test) Invited Fallback Links",
+ args: {
+ state: "unreachable",
+ lists: ["product"],
+ isContinuing: false,
+ onContinue: fn(),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(canvas.getByText(INVITED_DESCRIPTION)).toBeInTheDocument();
+ await expect(
+ canvas.getAllByRole("link").map((link) => link.getAttribute("href")),
+ ).toEqual(["https://langfuse.com/changelog"]);
+ },
+});
+
+export const InstallerFallbackKeepsTheHeader = meta.story({
+ name: "(Test) Installer Fallback Keeps The Header",
+ args: {
+ state: "unreachable",
+ lists: ["product", "oss"],
+ isContinuing: false,
+ onContinue: fn(),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const links = canvas.getAllByRole("link");
+ const inCardOrder = [
+ canvas.getByRole("heading", { name: "Stay up to date" }),
+ canvas.getByText(INSTALLER_DESCRIPTION),
+ canvas.getByText(
+ "This browser can't reach langfuse.com. To subscribe, open a link below on a device with internet access:",
+ ),
+ ...links,
+ canvas.getByRole("button", { name: "Continue" }),
+ ];
+
+ const documentOrder = Array.from(
+ canvasElement.querySelectorAll<HTMLElement>("*"),
+ ).filter((element) => inCardOrder.includes(element));
+ await expect(documentOrder).toEqual(inCardOrder);
+ await expect(links.map((link) => link.getAttribute("href"))).toEqual([
+ "https://langfuse.com/self-hosting/oss-newsletter",
+ "https://langfuse.com/changelog",
+ ]);
+ await expect(canvas.getByText("Self-hosting notices:")).toBeInTheDocument();
+ await expect(canvas.getByText("Product updates:")).toBeInTheDocument();
+ for (const link of links) {
+ await expect(link).toHaveAttribute("target", "_blank");
+ await expect(link).toHaveAttribute("rel", "noopener noreferrer");
+ }
+ },
+});
+
+export const FocusesTheFailureReason = meta.story({
+ name: "(Test) Focuses The Failure Reason",
+ args: {
+ state: "failed",
+ lists: ["product"],
+ isContinuing: false,
+ onContinue: fn(),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ await expect(
+ canvas.getByText(
+ "We couldn't subscribe you. You can sign up here instead:",
+ ),
+ ).toHaveFocus();
+ },
+});
+
+const INSTALLER_EXPLAINER_INTRO =
+ "By subscribing, you'll be added to the Langfuse mailing lists for product updates and self-hosting notices.";
+const INVITED_EXPLAINER_INTRO =
+ "By subscribing, you'll be added to the Langfuse product updates list. Expect one email a month about new features.";
+
+/** A bare click, as a tap delivers it: no hover and no keyboard focus that could open the card instead. */
+const openExplainer = async (canvasElement: HTMLElement) => {
+ fireEvent.click(
+ within(canvasElement).getByRole("button", {
+ name: "How your address is used",
+ }),
+ );
+ return within(canvasElement.ownerDocument.body).findByRole(
+ "dialog",
+ { name: "How your address is used" },
+ { timeout: 300 },
+ );
+};
+
+export const OpensTheInstallerExplainerOnClick = meta.story({
+ name: "(Test) Opens The Installer Explainer On Click",
+ args: formArgs(["product", "oss"], "[email protected]"),
+ play: async ({ canvasElement }) => {
+ const explainer = await openExplainer(canvasElement);
+
+ await expect(explainer).toHaveTextContent(INSTALLER_EXPLAINER_INTRO);
+ await expect(explainer).toHaveTextContent(
+ "You can unsubscribe at any time with the link in every email.",
+ );
+ await expect(explainer).toHaveTextContent(
+ "https://langfuse.com/api/productUpdateSignup",
+ );
+ await expect(explainer).toHaveTextContent(
+ "LANGFUSE_DISABLE_SIGNUP_ONBOARDING=true",
+ );
+ },
+});
+
+export const OpensTheInvitedExplainerOnClick = meta.story({
+ name: "(Test) Opens The Invited Explainer On Click",
+ args: formArgs(["product"], "[email protected]"),
+ play: async ({ canvasElement }) => {
+ const explainer = await openExplainer(canvasElement);
+
+ await expect(explainer).toHaveTextContent(INVITED_EXPLAINER_INTRO);
+ await expect(explainer).not.toHaveTextContent(INSTALLER_EXPLAINER_INTRO);
+ },
+});
+
+export const ClosesTheExplainerOnEscape = meta.story({
+ name: "(Test) Closes The Explainer On Escape",
+ args: formArgs(["product", "oss"], "[email protected]"),
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ const trigger = canvas.getByRole("button", {
+ name: "How your address is used",
+ });
+
+ await userEvent.tab();
+ await expect(trigger).toHaveFocus();
+ await body.findByRole("dialog", { name: "How your address is used" });
+
+ await userEvent.keyboard("{Escape}");
+ await waitFor(() =>
+ expect(body.queryByRole("dialog")).not.toBeInTheDocument(),
+ );
+ await expect(trigger).toHaveFocus();
+ },
+});
diff --git a/web/src/features/onboarding/components/NewsletterOptIn.tsx b/web/src/features/onboarding/components/NewsletterOptIn.tsx
new file mode 100644
index 0000000000..b1b5b388f7
--- /dev/null
+++ b/web/src/features/onboarding/components/NewsletterOptIn.tsx
@@ -0,0 +1,315 @@
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Info } from "lucide-react";
+import { type ReactNode, useState } from "react";
+import { z } from "zod";
+import { Button } from "@/src/components/design-system/Button/Button";
+import { ControlledHoverCard } from "@/src/components/design-system/ControlledHoverCard/ControlledHoverCard";
+import { createForm } from "@/src/components/design-system/factories/createForm";
+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";
+import { Input } from "@/src/components/design-system/Input/Input";
+import { LangfuseIcon } from "@/src/components/design-system/LangfuseIcon/LangfuseIcon";
+import { LinkBadge } from "@/src/components/design-system/LinkBadge/LinkBadge";
+import { Spinner } from "@/src/components/design-system/Spinner/Spinner";
+import { useWatchedPromiseCallback } from "@/src/hooks/useWatchedPromiseCallback";
+import {
+ getNewsletterFallbackLinks,
+ NEWSLETTER_SIGNUP_URL,
+ type NewsletterList,
+} from "../lib/newsletterSignup";
+
+const newsletterOptInSchema = z.object({
+ email: z
+ .string()
+ .trim()
+ .pipe(z.email({ error: "Enter a valid email address" })),
+});
+
+const NewsletterOptInForm = createForm<NewsletterOptInValues>();
+
+const EXPLAINER_LABEL = "How your address is used";
+
+const DESCRIPTIONS = {
+ installer:
+ "Monthly product updates, plus a heads-up when a new major version or a required upgrade affects your instance.",
+ invited:
+ "One email a month with the newest Langfuse features and improvements.",
+} as const;
+
+const EXPLAINER_INTROS = {
+ installer:
+ "By subscribing, you'll be added to the Langfuse mailing lists for product updates and self-hosting notices. Expect a monthly email about new features, plus a heads-up when a new major version or a required upgrade affects your instance.",
+ invited:
+ "By subscribing, you'll be added to the Langfuse product updates list. Expect one email a month about new features.",
+} as const;
+
+const FALLBACK_REASONS = {
+ unreachable:
+ "This browser can't reach langfuse.com. To subscribe, open a link below on a device with internet access:",
+ failed: "We couldn't subscribe you. You can sign up here instead:",
+} as const;
+
+const FALLBACK_LINK_LABELS: Record<NewsletterList, string> = {
+ oss: "Self-hosting notices:",
+ product: "Product updates:",
+};
+
+type NewsletterOptInProps =
+ | { state: "loading" }
+ | { state: "completing" }
+ | {
+ state: "form";
+ lists: NewsletterList[];
+ defaultEmail: string;
+ onSubscribe: (values: NewsletterOptInValues) => Promise<void>;
+ onSkip: () => Promise<void>;
+ }
+ | {
+ state: "unreachable" | "failed";
+ lists: NewsletterList[];
+ isContinuing: boolean;
+ onContinue: () => void;
+ };
+
+export function NewsletterOptIn(props: NewsletterOptInProps) {
+ switch (props.state) {
+ case "loading":
+ return (
+ <StatusCard
+ title="Getting your workspace ready"
+ description="One moment..."
+ />
+ );
+ case "completing":
+ return (
+ <StatusCard
+ title="Finishing setup"
+ description="Taking you to your workspace..."
+ />
+ );
+ case "form":
+ return (
+ <OnboardingCard>
+ <NewsletterHeader audience={getAudience(props.lists)} />
+ <NewsletterForm
+ defaultEmail={props.defaultEmail}
+ onSubscribe={props.onSubscribe}
+ onSkip={props.onSkip}
+ />
+ </OnboardingCard>
+ );
+ case "unreachable":
+ case "failed":
+ return (
+ <OnboardingCard>
+ <NewsletterHeader audience={getAudience(props.lists)} />
+ <NewsletterFallback
+ reason={FALLBACK_REASONS[props.state]}
+ lists={props.lists}
+ isContinuing={props.isContinuing}
+ onContinue={props.onContinue}
+ />
+ </OnboardingCard>
+ );
+ }
+}
+
+function OnboardingCard({ children }: { children: ReactNode }) {
+ return (
+ <div className="flex flex-1 flex-col py-6 sm:min-h-full sm:justify-start sm:px-6 sm:py-12 lg:px-8">
+ <div className="flex items-center justify-center gap-2 sm:mx-auto sm:w-full sm:max-w-md">
+ <LangfuseIcon size={32} />
+ </div>
+
+ <div className="bg-card mt-6 flex flex-col gap-6 rounded-lg px-6 py-6 shadow-sm sm:mx-auto sm:mt-16 sm:w-full sm:max-w-[480px] sm:px-12 sm:py-10">
+ {children}
+ </div>
+ </div>
+ );
+}
+
+function StatusCard({
+ title,
+ description,
+}: {
+ title: string;
+ description: string;
+}) {
+ return (
+ <OnboardingCard>
+ <div className="flex flex-col items-center py-4 text-center">
+ <Spinner size="xl" variant="muted" />
+ <h1 className="mt-6 text-xl font-bold">{title}</h1>
+ <p className="text-muted-foreground mt-2 text-sm">{description}</p>
+ </div>
+ </OnboardingCard>
+ );
+}
+
+/** The ⓘ opens on hover and keyboard focus, and on click or tap for touch screens. */
+function NewsletterHeader({ audience }: { audience: Audience }) {
+ const [isExplainerOpen, setIsExplainerOpen] = useState(false);
+ const openExplainer = () => setIsExplainerOpen(true);
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-1">
+ <h1 className="text-xl font-bold">Stay up to date</h1>
+ <ControlledHoverCard
+ open={isExplainerOpen}
+ onOpenChange={setIsExplainerOpen}
+ content={<NewsletterExplainer audience={audience} />}
+ aria-label={EXPLAINER_LABEL}
+ >
+ {({ getTriggerProps }) => (
+ <IconButton
+ {...getTriggerProps({ onClick: openExplainer })}
+ icon={Info}
+ label={EXPLAINER_LABEL}
+ size="sm"
+ variant="ghost"
+ />
+ )}
+ </ControlledHoverCard>
+ </div>
+ <p className="text-muted-foreground text-sm">{DESCRIPTIONS[audience]}</p>
+ </div>
+ );
+}
+
+function NewsletterExplainer({ audience }: { audience: Audience }) {
+ return (
+ <div className="text-muted-foreground flex w-96 max-w-[calc(100vw-1rem)] flex-col gap-2 p-3 text-sm">
+ <p>{EXPLAINER_INTROS[audience]}</p>
+ <p>You can unsubscribe at any time with the link in every email.</p>
+ <p>
+ Shown once to new users. Your browser, not this instance, checks it can
+ reach langfuse.com and sends your address to{" "}
+ <span className="font-mono break-words">{NEWSLETTER_SIGNUP_URL}</span>{" "}
+ when you subscribe. If it can&apos;t reach it, you&apos;ll see sign-up
+ links instead.
+ </p>
+ <p>
+ Langfuse admins can disable this question entirely by setting{" "}
+ <span className="font-mono break-words">
+ LANGFUSE_DISABLE_SIGNUP_ONBOARDING=true
+ </span>
+ .
+ </p>
+ </div>
+ );
+}
+
+/** Skip leaves without checking the address; Subscribe (or Enter in the field) validates it first. */
+function NewsletterForm({
+ defaultEmail,
+ onSubscribe,
+ onSkip,
+}: {
+ defaultEmail: string;
+ onSubscribe: (values: NewsletterOptInValues) => Promise<void>;
+ onSkip: () => Promise<void>;
+}) {
+ const form = NewsletterOptInForm.useForm({
+ resolver: zodResolver(newsletterOptInSchema),
+ defaultValues: { email: defaultEmail },
+ });
+ const [skip, isSkipping] = useWatchedPromiseCallback(onSkip, [onSkip]);
+ const isSubscribing = form.formState.isSubmitting;
+
+ return (
+ <NewsletterOptInForm
+ form={form}
+ onSubmit={onSubscribe}
+ actions={[
+ {
+ id: "subscribe",
+ type: "submit",
+ text: "Subscribe",
+ loading: isSubscribing,
+ disabled: isSkipping,
+ },
+ {
+ id: "skip",
+ type: "button",
+ text: "Skip",
+ variant: "ghost",
+ loading: isSkipping,
+ disabled: isSubscribing,
+ onClick: skip,
+ },
+ ]}
+ >
+ <NewsletterOptInForm.Field name="email" label="Email">
+ {(field) => (
+ <Input
+ id={field.id}
+ inputMode="email"
+ autoComplete="email"
+ name={field.name}
+ value={field.value}
+ onBlur={field.onBlur}
+ onChange={field.onChange}
+ ref={field.ref}
+ aria-describedby={field.inputDescribedById}
+ aria-invalid={Boolean(field.error)}
+ error={Boolean(field.error)}
+ />
+ )}
+ </NewsletterOptInForm.Field>
+ </NewsletterOptInForm>
+ );
+}
+
+/** Replaces a form that may have had focus, so the reason takes focus for keyboard and screen-reader users. */
+function NewsletterFallback({
+ reason,
+ lists,
+ isContinuing,
+ onContinue,
+}: {
+ reason: string;
+ lists: NewsletterList[];
+ isContinuing: boolean;
+ onContinue: () => void;
+}) {
+ return (
+ <div className="flex flex-col gap-8">
+ <div className="flex flex-col gap-3">
+ <p
+ ref={focusOnMount}
+ tabIndex={-1}
+ className="text-muted-foreground text-sm outline-hidden"
+ >
+ {reason}
+ </p>
+ <ul className="flex flex-col gap-2">
+ {getNewsletterFallbackLinks(lists).map(({ list, url }) => (
+ <li key={list} className="flex flex-col gap-0.5">
+ <span className="text-muted-foreground text-xs">
+ {FALLBACK_LINK_LABELS[list]}
+ </span>
+ <LinkBadge href={url} text={url} newTab shouldWrap />
+ </li>
+ ))}
+ </ul>
+ </div>
+ <div>
+ <Button
+ type="button"
+ text="Continue"
+ loading={isContinuing}
+ onClick={onContinue}
+ />
+ </div>
+ </div>
+ );
+}
+
+type Audience = "installer" | "invited";
+
+const getAudience = (lists: NewsletterList[]): Audience =>
+ lists.includes("oss") ? "installer" : "invited";
+
+const focusOnMount = (element: HTMLElement | null) => element?.focus();
+
+export type NewsletterOptInValues = z.infer<typeof newsletterOptInSchema>;
diff --git a/web/src/features/onboarding/hooks/useNewsletterSignup.ts b/web/src/features/onboarding/hooks/useNewsletterSignup.ts
new file mode 100644
index 0000000000..feb1a0d8c4
--- /dev/null
+++ b/web/src/features/onboarding/hooks/useNewsletterSignup.ts
@@ -0,0 +1,29 @@
+import { useQuery } from "@tanstack/react-query";
+import {
+ checkLangfuseReachable,
+ subscribeToNewsletter,
+} from "../lib/newsletterSignup";
+
+/** Checks once per page load whether the browser reaches langfuse.com and exposes the signup call. */
+export function useNewsletterSignup() {
+ // The query function never rejects, so no global error toast can fire.
+ const reachabilityCheck = useQuery({
+ queryKey: ["onboarding", "newsletterReachability"],
+ queryFn: checkLangfuseReachable,
+ retry: false,
+ staleTime: Infinity,
+ refetchOnWindowFocus: false,
+ });
+
+ return {
+ reachability: getReachability(reachabilityCheck.data),
+ subscribe: subscribeToNewsletter,
+ };
+}
+
+const getReachability = (
+ isReachable: boolean | undefined,
+): "checking" | "reachable" | "unreachable" => {
+ if (isReachable === undefined) return "checking";
+ return isReachable ? "reachable" : "unreachable";
+};
diff --git a/web/src/features/onboarding/lib/demoCallbackRedirect.clienttest.ts b/web/src/features/onboarding/lib/demoCallbackRedirect.clienttest.ts
new file mode 100644
index 0000000000..f6bf0a60ad
--- /dev/null
+++ b/web/src/features/onboarding/lib/demoCallbackRedirect.clienttest.ts
@@ -0,0 +1,95 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const { envState } = vi.hoisted(() => ({
+ envState: { NEXT_PUBLIC_BASE_PATH: undefined as string | undefined },
+}));
+
+vi.mock("@/src/env.mjs", () => ({ env: envState }));
+
+import {
+ getDeepLinkCallbackRedirectPath,
+ getSignupCallbackUrl,
+} from "@/src/features/onboarding/lib/demoCallbackRedirect";
+
+const DEEP_LINK = "/project/p1/traces/t1?observation=o1#trace-o1";
+
+afterEach(() => {
+ envState.NEXT_PUBLIC_BASE_PATH = undefined;
+});
+
+describe("getDeepLinkCallbackRedirectPath", () => {
+ it("keeps a relative deep link with its query", () => {
+ expect(getDeepLinkCallbackRedirectPath(DEEP_LINK)).toBe(DEEP_LINK);
+ });
+
+ it("keeps the same-origin absolute URL NextAuth passes to newUser", () => {
+ expect(
+ getDeepLinkCallbackRedirectPath(`${window.location.origin}${DEEP_LINK}`),
+ ).toBe(DEEP_LINK);
+ });
+
+ it.each([
+ ["the root", "/"],
+ ["the sign-in page (the SSO button's default)", "/auth/sign-in"],
+ ["the step itself", "/onboarding"],
+ ])("ignores %s", (_, path) => {
+ expect(
+ getDeepLinkCallbackRedirectPath(`${window.location.origin}${path}`),
+ ).toBeUndefined();
+ });
+
+ it.each([
+ ["another origin", "https://evil.example/project/p1"],
+ ["a protocol-relative URL", "//evil.example/project/p1"],
+ ["a script URL", "javascript:alert(1)"],
+ ["a repeated query param", ["/project/p1", "/project/p2"]],
+ ])("ignores %s", (_, value) => {
+ expect(getDeepLinkCallbackRedirectPath(value)).toBeUndefined();
+ });
+
+ it("strips the base path, which the router adds again", () => {
+ envState.NEXT_PUBLIC_BASE_PATH = "/langfuse";
+ expect(
+ getDeepLinkCallbackRedirectPath(
+ `${window.location.origin}/langfuse${DEEP_LINK}`,
+ ),
+ ).toBe(DEEP_LINK);
+ });
+});
+
+describe("getSignupCallbackUrl", () => {
+ it("sends a self-hosted deep link through the step", () => {
+ expect(
+ getSignupCallbackUrl({ targetPath: DEEP_LINK, isLangfuseCloud: false }),
+ ).toBe(`/onboarding?targetPath=${encodeURIComponent(DEEP_LINK)}`);
+ });
+
+ it.each([undefined, "/"])(
+ "sends a self-hosted sign-up without a deep link (%s) to the step",
+ (targetPath) => {
+ expect(getSignupCallbackUrl({ targetPath, isLangfuseCloud: false })).toBe(
+ "/onboarding",
+ );
+ },
+ );
+
+ it("keeps the base path on the step and strips it from the deep link", () => {
+ envState.NEXT_PUBLIC_BASE_PATH = "/langfuse";
+ expect(
+ getSignupCallbackUrl({
+ targetPath: `/langfuse${DEEP_LINK}`,
+ isLangfuseCloud: false,
+ }),
+ ).toBe(`/langfuse/onboarding?targetPath=${encodeURIComponent(DEEP_LINK)}`);
+ });
+
+ it.each([
+ ["a demo path", "/demo", "/onboarding?targetPath=%2Fdemo"],
+ ["another deep link", DEEP_LINK, DEEP_LINK],
+ ["no target path", undefined, "/onboarding"],
+ ])("keeps Cloud's handling of %s", (_, targetPath, expected) => {
+ expect(getSignupCallbackUrl({ targetPath, isLangfuseCloud: true })).toBe(
+ expected,
+ );
+ });
+});
diff --git a/web/src/features/onboarding/lib/demoCallbackRedirect.ts b/web/src/features/onboarding/lib/demoCallbackRedirect.ts
index 7dabe74e79..921c944ebf 100644
--- a/web/src/features/onboarding/lib/demoCallbackRedirect.ts
+++ b/web/src/features/onboarding/lib/demoCallbackRedirect.ts
@@ -1,3 +1,4 @@
+import { env } from "@/src/env.mjs";
import { getSafeRedirectPath, stripBasePath } from "@/src/utils/redirect";
const getCallbackPath = (url: string): string | null => {
@@ -13,7 +14,7 @@ const getCallbackPath = (url: string): string | null => {
}
};
-export const getDemoTargetPath = (value: unknown): string | undefined => {
+const getDemoTargetPath = (value: unknown): string | undefined => {
if (typeof value !== "string") return undefined;
const redirectPath = stripBasePath(getSafeRedirectPath(value));
const pathname = new URL(redirectPath, "https://langfuse.invalid").pathname;
@@ -30,3 +31,58 @@ export const getDemoCallbackRedirectPath = (
if (!callbackPath) return undefined;
return getDemoTargetPath(callbackPath);
};
+
+/** Same-origin deep link to forward to after the step; undefined for "/", the auth pages and /onboarding. */
+export const getDeepLinkCallbackRedirectPath = (
+ value: unknown,
+): string | undefined => {
+ if (typeof value !== "string") return undefined;
+ const callbackPath = getCallbackPath(value);
+ if (!callbackPath) return undefined;
+ return getDeepLinkTargetPath(callbackPath);
+};
+
+/** The path a sign-up carries through /onboarding: Cloud keeps demo links only, self-hosted any deep link. */
+export const getOnboardingTargetPath = ({
+ targetPath,
+ isLangfuseCloud,
+}: {
+ targetPath: unknown;
+ isLangfuseCloud: boolean;
+}): string | undefined =>
+ isLangfuseCloud
+ ? getDemoTargetPath(targetPath)
+ : getDeepLinkTargetPath(targetPath);
+
+/** callbackUrl of the sign-in right after a credentials sign-up: /onboarding, carrying a path it forwards to. */
+export const getSignupCallbackUrl = ({
+ targetPath,
+ isLangfuseCloud,
+}: {
+ targetPath: string | undefined;
+ isLangfuseCloud: boolean;
+}): string => {
+ const onboardingPath = `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding`;
+ const onboardingTargetPath = getOnboardingTargetPath({
+ targetPath,
+ isLangfuseCloud,
+ });
+ if (onboardingTargetPath) {
+ return `${onboardingPath}?targetPath=${encodeURIComponent(onboardingTargetPath)}`;
+ }
+ if (isLangfuseCloud) return targetPath ?? onboardingPath;
+ return onboardingPath;
+};
+
+const getDeepLinkTargetPath = (value: unknown): string | undefined => {
+ if (typeof value !== "string") return undefined;
+ const redirectPath = stripBasePath(getSafeRedirectPath(value));
+ const pathname = new URL(redirectPath, "https://langfuse.invalid").pathname;
+ return isDeepLinkPathname(pathname) ? redirectPath : undefined;
+};
+
+/** "/", the auth pages and the step itself say where a sign-in started, not where the user was headed. */
+const isDeepLinkPathname = (pathname: string) =>
+ pathname !== "/" &&
+ pathname !== "/onboarding" &&
+ !pathname.startsWith("/auth/");
diff --git a/web/src/features/onboarding/lib/fallbackRedirect.ts b/web/src/features/onboarding/lib/fallbackRedirect.ts
new file mode 100644
index 0000000000..e4e9a8aad9
--- /dev/null
+++ b/web/src/features/onboarding/lib/fallbackRedirect.ts
@@ -0,0 +1,8 @@
+/** Where a user lands without a known destination: "/" for members (it lists their projects), else /setup if they can create an organization. */
+export const getFallbackRedirectPath = ({
+ hasOrganizations,
+ canCreateOrganizations,
+}: {
+ hasOrganizations: boolean;
+ canCreateOrganizations: boolean;
+}) => (canCreateOrganizations && !hasOrganizations ? "/setup" : "/");
diff --git a/web/src/features/onboarding/lib/newsletterSignup.clienttest.ts b/web/src/features/onboarding/lib/newsletterSignup.clienttest.ts
new file mode 100644
index 0000000000..ab86e836f1
--- /dev/null
+++ b/web/src/features/onboarding/lib/newsletterSignup.clienttest.ts
@@ -0,0 +1,102 @@
+import {
+ checkLangfuseReachable,
+ subscribeToNewsletter,
+} from "./newsletterSignup";
+
+const fetchMock = vi.fn<typeof fetch>();
+
+beforeEach(() => {
+ fetchMock.mockReset();
+ vi.stubGlobal("fetch", fetchMock);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+const rejectOnAbort: typeof fetch = (_input, init) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(init.signal?.reason));
+ });
+
+describe("checkLangfuseReachable", () => {
+ it("treats an opaque response as reachable", async () => {
+ fetchMock.mockResolvedValue(new Response(null, { status: 200 }));
+
+ await expect(checkLangfuseReachable()).resolves.toBe(true);
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://langfuse.com/api/latest-releases",
+ expect.objectContaining({
+ mode: "no-cors",
+ cache: "no-store",
+ credentials: "omit",
+ referrerPolicy: "no-referrer",
+ }),
+ );
+ });
+
+ it("treats a network error as unreachable", async () => {
+ fetchMock.mockRejectedValue(new TypeError("Failed to fetch"));
+
+ await expect(checkLangfuseReachable()).resolves.toBe(false);
+ });
+
+ it("gives up after 3 seconds", async () => {
+ const timeout = new AbortController();
+ const timeoutSpy = vi
+ .spyOn(AbortSignal, "timeout")
+ .mockReturnValue(timeout.signal);
+ fetchMock.mockImplementation(rejectOnAbort);
+
+ const result = checkLangfuseReachable();
+ timeout.abort(new DOMException("Timed out", "TimeoutError"));
+
+ await expect(result).resolves.toBe(false);
+ expect(timeoutSpy).toHaveBeenCalledWith(3_000);
+ });
+});
+
+describe("subscribeToNewsletter", () => {
+ const email = "[email protected]";
+
+ it("posts the address, lists and source and reports a 200 as subscribed", async () => {
+ const timeoutSpy = vi.spyOn(AbortSignal, "timeout");
+ fetchMock.mockResolvedValue(new Response(null, { status: 200 }));
+
+ await expect(
+ subscribeToNewsletter({ email, lists: ["product", "oss"] }),
+ ).resolves.toBe("subscribed");
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://langfuse.com/api/productUpdateSignup",
+ expect.objectContaining({
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "omit",
+ referrerPolicy: "no-referrer",
+ }),
+ );
+ expect(JSON.parse(fetchMock.mock.calls[0][1]?.body as string)).toEqual({
+ email,
+ lists: ["product", "oss"],
+ source: "self-hosted-onboarding",
+ });
+ expect(timeoutSpy).toHaveBeenCalledWith(5_000);
+ });
+
+ it("reports any other status as failed", async () => {
+ fetchMock.mockResolvedValue(new Response(null, { status: 500 }));
+
+ await expect(
+ subscribeToNewsletter({ email, lists: ["product"] }),
+ ).resolves.toBe("failed");
+ });
+
+ it("reports a network error as failed", async () => {
+ fetchMock.mockRejectedValue(new TypeError("Failed to fetch"));
+
+ await expect(
+ subscribeToNewsletter({ email, lists: ["product"] }),
+ ).resolves.toBe("failed");
+ });
+});
diff --git a/web/src/features/onboarding/lib/newsletterSignup.ts b/web/src/features/onboarding/lib/newsletterSignup.ts
new file mode 100644
index 0000000000..7fe12abc8a
--- /dev/null
+++ b/web/src/features/onboarding/lib/newsletterSignup.ts
@@ -0,0 +1,70 @@
+export const NEWSLETTER_OUTCOMES = [
+ "subscribed",
+ "declined",
+ "unreachable",
+ "failed",
+] as const;
+
+const REACHABILITY_CHECK_URL = "https://langfuse.com/api/latest-releases";
+export const NEWSLETTER_SIGNUP_URL =
+ "https://langfuse.com/api/productUpdateSignup";
+const SIGNUP_SOURCE = "self-hosted-onboarding";
+const REACHABILITY_CHECK_TIMEOUT_MS = 3_000;
+const SIGNUP_TIMEOUT_MS = 5_000;
+const CHANGELOG_URL = "https://langfuse.com/changelog";
+const OSS_NEWSLETTER_URL = "https://langfuse.com/self-hosting/oss-newsletter";
+const FALLBACK_URLS: Record<NewsletterList, string> = {
+ oss: OSS_NEWSLETTER_URL,
+ product: CHANGELOG_URL,
+};
+const FALLBACK_ORDER: NewsletterList[] = ["oss", "product"];
+
+/** Resolves false when the browser cannot reach langfuse.com within 3 s; never rejects. */
+export const checkLangfuseReachable = async (): Promise<boolean> => {
+ try {
+ await fetch(REACHABILITY_CHECK_URL, {
+ mode: "no-cors",
+ cache: "no-store",
+ credentials: "omit",
+ referrerPolicy: "no-referrer",
+ signal: AbortSignal.timeout(REACHABILITY_CHECK_TIMEOUT_MS),
+ });
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+/** Sends the address straight from the browser to langfuse.com; never rejects. */
+export const subscribeToNewsletter = async ({
+ email,
+ lists,
+}: {
+ email: string;
+ lists: NewsletterList[];
+}): Promise<"subscribed" | "failed"> => {
+ try {
+ const response = await fetch(NEWSLETTER_SIGNUP_URL, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ email, lists, source: SIGNUP_SOURCE }),
+ credentials: "omit",
+ referrerPolicy: "no-referrer",
+ signal: AbortSignal.timeout(SIGNUP_TIMEOUT_MS),
+ });
+ return response.status === 200 ? "subscribed" : "failed";
+ } catch {
+ return "failed";
+ }
+};
+
+/** Pages where users sign up by hand for each offered list when the browser cannot do it for them. */
+export const getNewsletterFallbackLinks = (lists: NewsletterList[]) =>
+ FALLBACK_ORDER.filter((list) => lists.includes(list)).map((list) => ({
+ list,
+ url: FALLBACK_URLS[list],
+ }));
+
+export type NewsletterList = "product" | "oss";
+/** How the self-hosted onboarding step ended; the server stores it with the lists it offered. */
+export type NewsletterOutcome = (typeof NEWSLETTER_OUTCOMES)[number];
diff --git a/web/src/features/onboarding/server/index.ts b/web/src/features/onboarding/server/index.ts
index b04990ac70..57ef325611 100644
--- a/web/src/features/onboarding/server/index.ts
+++ b/web/src/features/onboarding/server/index.ts
@@ -1,6 +1,7 @@
export {
- completeCloudSignupOnboarding,
- getCloudSignupOnboardingStatus,
+ completeSignupOnboarding,
+ getSignupOnboardingStatus,
+ isSignupOnboardingEnabled,
provisionStarterOrganizationForNewUser,
resolveOnboardingRedirectTarget,
type RealOrganizationMembership,
diff --git a/web/src/features/onboarding/server/onboardingRouter.ts b/web/src/features/onboarding/server/onboardingRouter.ts
index f053e7c2da..db25338f7a 100644
--- a/web/src/features/onboarding/server/onboardingRouter.ts
+++ b/web/src/features/onboarding/server/onboardingRouter.ts
@@ -1,7 +1,7 @@
import { z } from "zod";
import {
- completeCloudSignupOnboarding,
- getCloudSignupOnboardingStatus,
+ completeSignupOnboarding,
+ getSignupOnboardingStatus,
} from "@/src/features/onboarding/server/onboardingService";
import {
createTRPCRouter,
@@ -13,10 +13,11 @@ import {
BUILD_INTENT_OTHER_MAX_LENGTH,
EXCLUSIVE_BUILD_INTENT,
} from "@/src/features/onboarding/lib/buildIntent";
+import { NEWSLETTER_OUTCOMES } from "@/src/features/onboarding/lib/newsletterSignup";
export const onboardingRouter = createTRPCRouter({
status: authenticatedProcedure.query(async ({ ctx }) => {
- return getCloudSignupOnboardingStatus({
+ return getSignupOnboardingStatus({
prisma: ctx.prisma,
userId: ctx.session.user.id,
canCreateOrganizations: ctx.session.user.canCreateOrganizations,
@@ -49,6 +50,9 @@ export const onboardingRouter = createTRPCRouter({
.trim()
.max(BUILD_INTENT_OTHER_MAX_LENGTH)
.optional(),
+ newsletter: z
+ .object({ outcome: z.enum(NEWSLETTER_OUTCOMES) })
+ .optional(),
})
.refine(
({ buildIntents }) =>
@@ -66,7 +70,7 @@ export const onboardingRouter = createTRPCRouter({
.optional(),
)
.mutation(async ({ ctx, input }) => {
- return completeCloudSignupOnboarding({
+ return completeSignupOnboarding({
prisma: ctx.prisma,
userId: ctx.session.user.id,
userEmail: ctx.session.user.email,
@@ -76,6 +80,7 @@ export const onboardingRouter = createTRPCRouter({
buildIntents: input?.buildIntents,
buildIntentPositions: input?.buildIntentPositions,
buildIntentOther: input?.buildIntentOther,
+ newsletter: input?.newsletter,
});
}),
});
diff --git a/web/src/features/onboarding/server/onboardingService.ts b/web/src/features/onboarding/server/onboardingService.ts
index 09964ceb68..0482b84bdc 100644
--- a/web/src/features/onboarding/server/onboardingService.ts
+++ b/web/src/features/onboarding/server/onboardingService.ts
@@ -17,8 +17,15 @@ import {
import { projectRoleAccessRights } from "@langfuse/shared";
import { createProjectRoute } from "@/src/features/setup";
import { type BuildIntentId } from "@/src/features/onboarding/lib/buildIntent";
+import { getFallbackRedirectPath } from "@/src/features/onboarding/lib/fallbackRedirect";
+import {
+ type NewsletterList,
+ type NewsletterOutcome,
+} from "@/src/features/onboarding/lib/newsletterSignup";
const DEFAULT_STARTER_PROJECT_NAME = "My Project";
+const INSTALLER_NEWSLETTER_LISTS: NewsletterList[] = ["product", "oss"];
+const INVITED_NEWSLETTER_LISTS: NewsletterList[] = ["product"];
const STARTER_ORGANIZATION_METADATA = {
langfuseOnboarding: {
starterOrganization: true,
@@ -149,12 +156,14 @@ export const resolveOnboardingRedirectTarget = async ({
}: {
prisma: Pick<PrismaClient, "organizationMembership">;
userId: string;
-}): Promise<OnboardingRedirectTarget | null> => {
- const organizationMemberships = await getRealOrganizationMemberships({
- prisma,
- userId,
- });
+}): Promise<OnboardingRedirectTarget | null> =>
+ getRedirectTargetForMemberships(
+ await getRealOrganizationMemberships({ prisma, userId }),
+ );
+const getRedirectTargetForMemberships = (
+ organizationMemberships: RealOrganizationMembership[],
+): OnboardingRedirectTarget | null => {
const starterOrganizationMembership = organizationMemberships.find(
(membership) =>
membership.role === Role.OWNER &&
@@ -223,11 +232,19 @@ const resolveOnboardingRedirectTargetWithFallback = async ({
userId: string;
canCreateOrganizations: boolean;
}): Promise<OnboardingRedirectTarget> =>
- (await resolveOnboardingRedirectTarget({ prisma, userId })) ?? {
- redirectTo: canCreateOrganizations ? "/setup" : "/",
- };
-
-export const getCloudSignupOnboardingStatus = async ({
+ (await resolveOnboardingRedirectTarget({ prisma, userId })) ??
+ getFallbackRedirectTarget(canCreateOrganizations);
+
+/**
+ * Always on for Cloud. Self-hosted turns it off with
+ * `LANGFUSE_DISABLE_SIGNUP_ONBOARDING=true`: status then reports the step as
+ * completed and completion writes nothing.
+ */
+export const isSignupOnboardingEnabled = () =>
+ Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) ||
+ env.LANGFUSE_DISABLE_SIGNUP_ONBOARDING !== "true";
+
+export const getSignupOnboardingStatus = async ({
prisma,
userId,
canCreateOrganizations,
@@ -236,7 +253,46 @@ export const getCloudSignupOnboardingStatus = async ({
userId: string;
canCreateOrganizations: boolean;
}) => {
- const completedSurvey = await prisma.survey.findFirst({
+ const organizationMemberships = await getRealOrganizationMemberships({
+ prisma,
+ userId,
+ });
+ const redirectTarget =
+ getRedirectTargetForMemberships(organizationMemberships) ??
+ getFallbackRedirectTarget(canCreateOrganizations);
+
+ if (
+ !isSignupOnboardingEnabled() ||
+ (await hasCompletedOnboardingSurvey({ prisma, userId }))
+ ) {
+ return {
+ completed: true as const,
+ redirectTo: redirectTarget.redirectTo,
+ };
+ }
+
+ return {
+ completed: false as const,
+ canConfigureAiFeatures: redirectTarget.canConfigureAiFeatures === true,
+ ...(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
+ ? {}
+ : {
+ newsletterLists: getNewsletterLists({
+ organizationMemberships,
+ canCreateOrganizations,
+ }),
+ }),
+ };
+};
+
+const hasCompletedOnboardingSurvey = async ({
+ prisma,
+ userId,
+}: {
+ prisma: Pick<PrismaClient, "survey">;
+ userId: string;
+}) =>
+ (await prisma.survey.findFirst({
where: {
userId,
surveyName: SurveyName.USER_ONBOARDING,
@@ -244,34 +300,29 @@ export const getCloudSignupOnboardingStatus = async ({
select: {
id: true,
},
- });
+ })) !== null;
- if (!completedSurvey) {
- const redirectTarget = await resolveOnboardingRedirectTargetWithFallback({
- prisma,
- userId,
- canCreateOrganizations,
- });
-
- return {
- completed: false as const,
- canConfigureAiFeatures: redirectTarget.canConfigureAiFeatures === true,
- };
- }
-
- const redirectTarget = await resolveOnboardingRedirectTargetWithFallback({
- prisma,
- userId,
- canCreateOrganizations,
- });
+/** Installers (no membership yet, free to create an org) and org owners/admins also get the self-hosting list. */
+const getNewsletterLists = ({
+ organizationMemberships,
+ canCreateOrganizations,
+}: {
+ organizationMemberships: RealOrganizationMembership[];
+ canCreateOrganizations: boolean;
+}) => {
+ const isInstaller =
+ organizationMemberships.length === 0 && canCreateOrganizations;
+ const isOrganizationAdmin = organizationMemberships.some(
+ (membership) =>
+ membership.role === Role.OWNER || membership.role === Role.ADMIN,
+ );
- return {
- completed: true as const,
- redirectTo: redirectTarget.redirectTo,
- };
+ return isInstaller || isOrganizationAdmin
+ ? INSTALLER_NEWSLETTER_LISTS
+ : INVITED_NEWSLETTER_LISTS;
};
-export const completeCloudSignupOnboarding = async ({
+export const completeSignupOnboarding = async ({
prisma,
userId,
userEmail,
@@ -281,6 +332,7 @@ export const completeCloudSignupOnboarding = async ({
buildIntents,
buildIntentPositions,
buildIntentOther,
+ newsletter,
}: {
prisma: PrismaClient;
userId: string;
@@ -291,8 +343,19 @@ export const completeCloudSignupOnboarding = async ({
buildIntents?: BuildIntentId[];
buildIntentPositions?: number[];
buildIntentOther?: string;
-}) =>
- prisma.$transaction(async (tx) => {
+ newsletter?: { outcome: NewsletterOutcome };
+}) => {
+ if (!isSignupOnboardingEnabled()) {
+ const redirectTarget = await resolveOnboardingRedirectTargetWithFallback({
+ prisma,
+ userId,
+ canCreateOrganizations,
+ });
+
+ return { redirectTo: redirectTarget.redirectTo, surveyCreated: false };
+ }
+
+ return prisma.$transaction(async (tx) => {
await tx.$queryRaw`
SELECT id
FROM users
@@ -300,23 +363,19 @@ export const completeCloudSignupOnboarding = async ({
FOR UPDATE
`;
- const existingSurvey = await tx.survey.findFirst({
- where: {
- userId,
- surveyName: SurveyName.USER_ONBOARDING,
- },
- select: {
- id: true,
- },
+ const hasCompletedSurvey = await hasCompletedOnboardingSurvey({
+ prisma: tx,
+ userId,
});
-
- const redirectTarget = await resolveOnboardingRedirectTargetWithFallback({
+ const organizationMemberships = await getRealOrganizationMemberships({
prisma: tx,
userId,
- canCreateOrganizations,
});
+ const redirectTarget =
+ getRedirectTargetForMemberships(organizationMemberships) ??
+ getFallbackRedirectTarget(canCreateOrganizations);
- if (!existingSurvey) {
+ if (!hasCompletedSurvey) {
const normalizedReferralSource = referralSource?.trim();
if (
@@ -344,6 +403,17 @@ export const completeCloudSignupOnboarding = async ({
...(buildIntentOther ? { buildIntentOther } : {}),
}
: {}),
+ ...(newsletter && !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
+ ? {
+ newsletter: {
+ lists: getNewsletterLists({
+ organizationMemberships,
+ canCreateOrganizations,
+ }),
+ outcome: newsletter.outcome,
+ },
+ }
+ : {}),
},
userId,
userEmail: userEmail ?? undefined,
@@ -354,9 +424,10 @@ export const completeCloudSignupOnboarding = async ({
return {
redirectTo: redirectTarget.redirectTo,
- surveyCreated: !existingSurvey,
+ surveyCreated: !hasCompletedSurvey,
};
});
+};
export const provisionStarterOrganizationForNewUser = async ({
prisma,
@@ -456,3 +527,13 @@ export const provisionStarterOrganizationForNewUser = async ({
return createdResources;
};
+
+/** Only reached without real memberships: any membership has its own target in getRedirectTargetForMemberships. */
+const getFallbackRedirectTarget = (
+ canCreateOrganizations: boolean,
+): OnboardingRedirectTarget => ({
+ redirectTo: getFallbackRedirectPath({
+ hasOrganizations: false,
+ canCreateOrganizations,
+ }),
+});
diff --git a/web/src/pages/onboarding.tsx b/web/src/pages/onboarding.tsx
index a7cc7355bb..b1a0b18646 100644
--- a/web/src/pages/onboarding.tsx
+++ b/web/src/pages/onboarding.tsx
@@ -1,4 +1,4 @@
-// This page is part of the cloud signup flow and can also be opened directly for local testing.
+// The step new users see after signing up: the survey on Cloud, the newsletter opt-in on self-hosted.
import Head from "next/head";
import { ConnectedOnboardingSurvey } from "@/src/features/onboarding/components/ConnectedOnboardingSurvey";
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index 8a686491a9..9649eca276 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -91,6 +91,7 @@ import {
isV4UpgradeUiAvailable,
} from "@/src/features/events/server";
import { canCreateOrganizations } from "@/src/features/organizations/server";
+import { isSignupOnboardingEnabled } from "@/src/features/onboarding/server";
const staticProviders: Provider[] = [
CredentialsProvider({
@@ -1180,7 +1181,7 @@ export async function getAuthOptions(
pages: {
signIn: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/sign-in`,
error: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/error`,
- ...(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
+ ...(isSignupOnboardingEnabled()
? {
newUser: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding`,
}
diff --git a/web/src/utils/redirect.ts b/web/src/utils/redirect.ts
index 377f997b95..4fdb9ccf89 100644
--- a/web/src/utils/redirect.ts
+++ b/web/src/utils/redirect.ts
@@ -123,6 +123,7 @@ export function stripBasePath(path: string): string {
return cleaned || "/";
}
- const stripped = cleaned.slice(basePath.length) || "/";
- return stripped.startsWith("/") ? stripped : `/${stripped}`;
+ // A remainder starting with "//" or "/\" would be protocol-relative.
+ const stripped = cleaned.slice(basePath.length).replace(/^[/\\]+/, "");
+ return `/${stripped}`;
}