Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat(dashboard): redesign sign-in, sign-up and onboarding (#591)

Carl-Gerhard Lindesvärd0486cccb4b2b
diff --git a/apps/public/content/docs/mcp/index.mdx b/apps/public/content/docs/mcp/index.mdx
index 7e79c8afd..503ca204f 100644
--- a/apps/public/content/docs/mcp/index.mdx
+++ b/apps/public/content/docs/mcp/index.mdx
@@ -40,7 +40,7 @@ base64(clientId:clientSecret)
The easiest way to get your MCP token is directly from the dashboard — no terminal needed:
- **New client** — after creating a client via **Settings → API Clients**, the success screen shows the **MCP Token** field ready to copy.
-- **Onboarding** — the connect step in the onboarding flow shows the MCP Token alongside your client ID and secret. Use the **Save** button to download all three values as `credentials.txt`.
+- **Onboarding** — creating a project also creates a read-only MCP client for it. The install step shows that client's MCP Token once, next to the write client's ID and secret; **Download** saves all three as a text file.
#### From the terminal
diff --git a/apps/start/e2e/auth-helpers.ts b/apps/start/e2e/auth-helpers.ts
index 92c749208..0b3d2df2b 100644
--- a/apps/start/e2e/auth-helpers.ts
+++ b/apps/start/e2e/auth-helpers.ts
@@ -41,7 +41,7 @@ export async function submitSignIn(
): Promise<Response> {
await waitForSignInSlot();
await page.getByLabel('Email').fill(credentials.email);
- await page.getByLabel('Password').fill(credentials.password);
+ await page.getByLabel('Password', { exact: true }).fill(credentials.password);
const answer = page.waitForResponse((response) =>
response.url().includes('/trpc/auth.signInEmail')
);
diff --git a/apps/start/e2e/auth-login.spec.ts b/apps/start/e2e/auth-login.spec.ts
index 161beb6b7..39d34ca21 100644
--- a/apps/start/e2e/auth-login.spec.ts
+++ b/apps/start/e2e/auth-login.spec.ts
@@ -39,7 +39,9 @@ test('signed-out visitors are sent to /login from every protected route', async
await page.goto(path);
await expect(page, `from ${path}`).toHaveURL(/\/login$/);
}
- await expect(page.getByRole('heading', { name: 'Sign in' })).toBeVisible();
+ await expect(
+ page.getByRole('heading', { name: 'Welcome back' })
+ ).toBeVisible();
// The onboarding steps send a signed-out visitor to the sign-up page instead.
await page.goto('/onboarding/project');
@@ -68,17 +70,19 @@ test('the login form validates before it calls the API', async ({ page }) => {
await expect(fieldErrors.first()).toHaveText('Invalid email address');
await page.getByLabel('Email').fill('not-an-email');
- await page.getByLabel('Password').fill('short');
- await page.getByLabel('Password').press('Enter');
+ await page.getByLabel('Password', { exact: true }).fill('short');
+ await page.getByLabel('Password', { exact: true }).press('Enter');
await expect(fieldErrors).toHaveCount(2);
await page.getByLabel('Email').fill('[email protected]');
- await page.getByLabel('Password').fill('long-enough-password');
+ await page
+ .getByLabel('Password', { exact: true })
+ .fill('long-enough-password');
await page.getByLabel('Email').press('Tab');
await expect(fieldErrors).toHaveCount(0);
await expect(
- page.getByRole('link', { name: 'Create one today' })
+ page.getByRole('link', { name: 'Create an account' })
).toHaveAttribute('href', '/onboarding');
expect(signInRequests).toBe(0);
await expect(page).toHaveURL(/\/login$/);
@@ -212,7 +216,9 @@ test('a submit before hydration never puts the password in the URL', async ({
);
await page.goto('/login');
await page.getByLabel('Email').fill('[email protected]');
- await page.getByLabel('Password').fill('super-secret-password');
+ await page
+ .getByLabel('Password', { exact: true })
+ .fill('super-secret-password');
await page.getByRole('button', { name: 'Sign in', exact: true }).click();
await page.waitForLoadState('load');
expect(page.url()).not.toContain('super-secret-password');
diff --git a/apps/start/e2e/auth-onboarding.spec.ts b/apps/start/e2e/auth-onboarding.spec.ts
index fcd4bc616..331e00035 100644
--- a/apps/start/e2e/auth-onboarding.spec.ts
+++ b/apps/start/e2e/auth-onboarding.spec.ts
@@ -36,7 +36,8 @@ const DESKTOP_VIEWPORT = { width: 1280, height: 720 };
const RECOVERY_CODE_COUNT = 10;
const RECOVERY_CODE_PATTERN = /[A-Z2-9]{5}-[A-Z2-9]{5}/g;
const TOTP_SECRET_PATTERN = /[A-Z2-7]{32}/;
-const FRAMEWORK_COUNT = 15;
+const FRAMEWORK_COUNT = 17;
+const WEBSITE_FRAMEWORK_COUNT = 8;
const EVENT_ARRIVAL_TIMEOUT_MS = 45_000;
interface ProjectState {
@@ -133,33 +134,25 @@ test('sign-up validates every field before it calls the API', async ({
});
await gotoHydrated(page, '/onboarding');
await expect(
- page.getByRole('heading', { name: 'Start tracking in minutes' })
+ page.getByRole('heading', { name: 'Create your account' })
).toBeVisible();
await expect(page.getByRole('link', { name: 'Sign in' })).toHaveAttribute(
'href',
'/login'
);
+ const fieldErrors = page.locator('[data-slot="field-error"]');
const submit = page.getByRole('button', { name: 'Create account' });
await submit.click();
- await expect(page.getByText('Issues')).toHaveCount(5);
+ await expect(fieldErrors).toHaveCount(4);
await page.getByLabel('First name').fill('E2E');
await page.getByLabel('Last name').fill('Auth');
await page.getByLabel('Email').fill(`e2e-auth-${RUN_ID}@example.com`);
await page.getByLabel('Password', { exact: true }).fill('short');
- await page.getByLabel('Confirm password').fill('short');
await submit.click();
- await expect(page.getByText('Issues')).toHaveCount(2);
-
- await page.getByLabel('Password', { exact: true }).fill('long-enough-1');
- await page.getByLabel('Confirm password').fill('long-enough-2');
- await submit.click();
- await expect(page.getByText('Issues')).toHaveCount(1);
- await page.getByText('Issues').hover();
- await expect(page.getByRole('tooltip')).toContainText(
- 'Passwords do not match'
- );
+ await expect(fieldErrors).toHaveCount(1);
+ await expect(fieldErrors.first()).toContainText('8');
await page.screenshot({ path: `${SHOTS_DIR}/sign-up-validation.png` });
expect(signUpRequests).toBe(0);
@@ -178,8 +171,7 @@ test('sign up creates the account and opens the project step', async ({
await page.getByLabel('Last name').fill('Auth');
await page.getByLabel('Email').fill(email);
await page.getByLabel('Password', { exact: true }).fill(password);
- await page.getByLabel('Confirm password').fill(password);
- await page.getByLabel('Confirm password').press('Enter');
+ await page.getByLabel('Password', { exact: true }).press('Enter');
// No organization yet: `/` forwards to the project step.
await expect(page).toHaveURL(/\/onboarding\/project$/, { timeout: 20_000 });
@@ -200,7 +192,6 @@ test('signing up again with the same email is refused', async ({ page }) => {
await page.getByLabel('Last name').fill('Twin');
await page.getByLabel('Email').fill(state.email);
await page.getByLabel('Password', { exact: true }).fill('another-password');
- await page.getByLabel('Confirm password').fill('another-password');
await page.getByRole('button', { name: 'Create account' }).click();
await expect(toast(page, 'User already exists')).toBeVisible();
await expect(page).toHaveURL(/\/onboarding$/);
@@ -220,35 +211,38 @@ test('the project step validates the workspace, the name, the type and the domai
}
});
await gotoHydrated(page, '/onboarding/project');
- await expect(page.getByText('Create project')).toBeVisible();
- // Nothing to reuse yet.
+ await expect(
+ page.getByRole('heading', { name: 'Create your first project' })
+ ).toBeVisible();
+ // Nothing to reuse yet, so there is no workspace switch.
await expect(
page.getByRole('button', { name: 'Use existing workspace' })
- ).toBeDisabled();
+ ).toHaveCount(0);
- const next = page.getByRole('button', { name: 'Next' });
- await next.click();
+ const fieldErrors = page.locator('[data-slot="field-error"]');
+ const create = page.getByRole('button', { name: 'Create project' });
+ await create.click();
await expect(
- page.getByText('At least one type must be selected')
+ page.getByText('Pick at least one thing to track')
).toBeVisible();
- await expect(page.getByText('Issues')).toHaveCount(2);
-
- await page.getByLabel('Workspace name').fill(`E2E auth ${RUN_ID}`);
- await page.getByLabel('Your first project name').fill('ab');
- await page.getByText('Website', { exact: true }).click();
- await next.click();
- // Too short a name, and a website needs its domain.
- await expect(page.getByText('Issues')).toHaveCount(2);
+ // The project name, and the workspace name that follows it.
+ await expect(fieldErrors).toHaveCount(2);
+
+ await page.getByLabel('Project name').fill('ab');
+ await page.getByRole('button', { name: /^Website/ }).click();
+ await create.click();
+ // Too short a name, and a website needs its URL.
+ await expect(fieldErrors).toHaveCount(2);
await page.screenshot({
path: `${SHOTS_DIR}/onboarding-project-invalid.png`,
});
// App and backend projects have no domain to ask for.
- await page.getByText('Website', { exact: true }).click();
- await expect(page.getByLabel('Domain')).toBeHidden();
- await page.getByText('App', { exact: true }).click();
- await next.click();
- await expect(page.getByText('Issues')).toHaveCount(1);
+ await page.getByRole('button', { name: /^Website/ }).click();
+ await expect(page.getByLabel('Website URL')).toBeHidden();
+ await page.getByRole('button', { name: /^App/ }).click();
+ await create.click();
+ await expect(fieldErrors).toHaveCount(1);
expect(projectRequests).toBe(0);
expect(issues.unexpected()).toEqual([]);
@@ -261,6 +255,7 @@ test('the timezone picker searches and keeps the choice', async ({
}) => {
await continueAsUser(context, baseURL);
await gotoHydrated(page, '/onboarding/project');
+ await page.getByRole('button', { name: 'Change' }).click();
const timezone = page.getByRole('combobox').first();
// Defaults to the browser's zone.
await expect(timezone).toHaveText(/\w+\/\w+|UTC/);
@@ -289,39 +284,40 @@ test('a website project leads to the connect step with its one-time credentials'
const issues = watchIssues(page);
const organizationName = `E2E auth ${RUN_ID}`;
await gotoHydrated(page, '/onboarding/project');
+ await page.getByLabel('Project name').fill(`E2E auth web ${RUN_ID}`);
+ await page.getByRole('button', { name: /^Website/ }).click();
+
+ // A bare host becomes an origin, and that origin is allowed by default.
+ const domain = `e2e-auth-${RUN_ID}.example.com`;
+ await page.getByLabel('Website URL').fill(domain);
+ await page.getByLabel('Website URL').blur();
+ await expect(page.getByLabel('Website URL')).toHaveValue(`https://${domain}`);
+ await page.getByText('Also track other domains').click();
+ await expect(page.locator(`[data-tag="https://${domain}"]`)).toBeVisible();
+
+ // The workspace is named after the project until it is edited.
+ await page.getByRole('button', { name: 'Change' }).click();
+ await expect(page.getByLabel('Workspace name')).toHaveValue(
+ `E2E auth web ${RUN_ID}`
+ );
await page.getByLabel('Workspace name').fill(organizationName);
await page.getByRole('combobox').first().click();
await page.getByPlaceholder(/search/i).fill('UTC');
await page.getByRole('option', { name: 'UTC', exact: true }).click();
- await page
- .getByLabel('Your first project name')
- .fill(`E2E auth web ${RUN_ID}`);
- await page.getByText('Website', { exact: true }).click();
-
- // A bare host becomes an origin, and that origin is allowed by default.
- const domain = `e2e-auth-${RUN_ID}.example.com`;
- await page.getByLabel('Domain').fill(domain);
- await page.getByLabel('Domain').blur();
- await expect(page.getByLabel('Domain')).toHaveValue(`https://${domain}`);
- await page
- .getByText('will be allowed. Do you want to allow any other?')
- .click();
- await expect(
- page.getByText(`https://${domain}`, { exact: true }).last()
- ).toBeVisible();
await page.screenshot({
path: `${SHOTS_DIR}/onboarding-project-website.png`,
+ fullPage: true,
});
const created = page.waitForResponse((response) =>
response.url().includes('/trpc/onboarding.project')
);
- await page.getByRole('button', { name: 'Next' }).click();
+ await page.getByRole('button', { name: 'Create project' }).click();
const client = (await (await created).json()).result.data.json;
await expect(page).toHaveURL(
new RegExp(`/onboarding/${client.projectId}/connect$`)
);
- await expect(page.getByText('Client credentials')).toBeVisible();
+ await expect(page.getByText('Listening for your first event')).toBeVisible();
writeState({
organizationId: client.organizationId,
organizationName,
@@ -332,56 +328,82 @@ test('a website project leads to the connect step with its one-time credentials'
},
});
+ // The secret and the MCP token are only known right after creation. The
+ // token belongs to a separate read-only client, so it is not derived from
+ // the write client's secret.
await expect(page.getByText(client.id).first()).toBeVisible();
await expect(page.getByText(client.secret)).toBeVisible();
- await expect(
- page.getByText(btoa(`${client.id}:${client.secret}`))
- ).toBeVisible();
+ // The assistant card is collapsed until asked for.
+ await expect(page.getByText(client.mcpToken)).toHaveCount(0);
+ await page.getByRole('button', { name: /Connect an AI assistant/ }).click();
+ await expect(page.getByText(client.mcpToken)).toBeVisible();
+ expect(client.mcpToken).not.toBe(btoa(`${client.id}:${client.secret}`));
+
+ // Manual setup starts with the script tag for a website, with the real client id.
+ await page.getByRole('tab', { name: 'Manual setup' }).click();
await expect(page.locator('code').first()).toContainText(
`clientId: '${client.id}'`
);
- await expect(
- page.locator('button').filter({ has: page.locator('.font-semibold') })
- ).toHaveCount(FRAMEWORK_COUNT);
await page.screenshot({
path: `${SHOTS_DIR}/onboarding-connect.png`,
fullPage: true,
});
- // Each framework opens its instructions next to the page.
- for (const framework of ['Next.js', 'Rest API', 'iOS (swift)']) {
- await page.getByRole('button', { name: framework, exact: true }).click();
- const sheet = page.getByRole('dialog');
- await expect(sheet.locator(`iframe[title="${framework}"]`)).toBeVisible();
- await sheet.getByRole('button', { name: 'Close' }).first().click();
- await expect(sheet).toBeHidden();
- }
+ // The framework dropdown suggests the website SDKs first and lists the rest.
+ const frameworkSelect = page.getByRole('combobox', { name: 'Framework' });
+ await frameworkSelect.click();
+ await expect(
+ page.getByRole('group', { name: 'For websites' }).getByRole('option')
+ ).toHaveCount(WEBSITE_FRAMEWORK_COUNT);
+ await expect(page.getByRole('option')).toHaveCount(FRAMEWORK_COUNT);
+
+ // Each framework shows its own snippet and links to its guide.
+ await page.getByRole('option', { name: 'Next.js' }).click();
+ await expect(page.locator('code').first()).toContainText('@openpanel/nextjs');
+ await expect(
+ page.getByRole('link', { name: 'Full Next.js guide' })
+ ).toHaveAttribute('href', 'https://openpanel.dev/docs/sdks/nextjs');
+ await frameworkSelect.click();
+ await page.getByRole('option', { name: 'iOS (swift)' }).click();
+ await expect(page.locator('code').last()).toContainText(
+ `clientSecret: "${client.secret}"`
+ );
// The secret is stored hashed: after a reload in a new tab it cannot be shown again.
await page.evaluate(() => sessionStorage.clear());
await page.reload();
- await expect(page.getByText('Client credentials')).toBeVisible();
+ await waitForHydration(page);
+ await expect(page.getByText(client.id).first()).toBeVisible();
await expect(page.getByText(client.secret)).toHaveCount(0);
- await expect(page.getByText('is only shown once')).toBeVisible();
+ await expect(page.getByText(client.mcpToken)).toHaveCount(0);
+ await expect(page.getByText('Secrets are shown once')).toBeVisible();
expect(issues.unexpected()).toEqual([]);
});
-// Open defect: TanStack's `Link` builds its href from `to`, so a LinkButton's
-// `href` is dropped and `target="_blank"` links open the page you are already on.
-test('"More details" in the framework instructions links to the docs', async ({
+test('the AI prompt carries the client id and the chosen framework guide', async ({
page,
context,
baseURL,
}) => {
const state = await continueAsUser(context, baseURL);
- await gotoHydrated(page, `/onboarding/${state.webProject?.id}/connect`);
- await page.getByRole('button', { name: 'Next.js', exact: true }).click();
+ const project = state.webProject;
+ if (!project) {
+ throw new Error('The website project was not created; see its failure.');
+ }
+ await gotoHydrated(page, `/onboarding/${project.id}/connect`);
+ const prompt = page.locator('pre');
+ await expect(prompt).toContainText(`Client ID: ${project.clientId}`);
+ await expect(prompt).toContainText('https://openpanel.dev/docs/sdks');
+
+ await page.getByRole('combobox', { name: 'Framework (optional)' }).click();
+ await page.getByRole('option', { name: 'Next.js' }).click();
+ await expect(prompt).toContainText('https://openpanel.dev/docs/sdks/nextjs');
await expect(
- page.getByRole('dialog').getByRole('link', { name: 'More details' })
- ).toHaveAttribute('href', /^https:\/\/openpanel\.dev\/docs/);
+ page.getByRole('link', { name: 'Open in Cursor' })
+ ).toHaveAttribute('href', /^cursor:\/\//);
});
-test('the verify step turns green when the first event arrives', async ({
+test('the install step turns green when the first event arrives', async ({
page,
context,
baseURL,
@@ -393,29 +415,30 @@ test('the verify step turns green when the first event arrives', async ({
}
const issues = watchIssues(page);
await gotoHydrated(page, `/onboarding/${project.id}/connect`);
- await page.getByRole('link', { name: 'Next' }).click();
- await expect(page).toHaveURL(new RegExp(`/onboarding/${project.id}/verify$`));
- await expect(page.getByText('Waiting for events')).toBeVisible();
- await expect(page.getByRole('link', { name: 'Skip for now' })).toBeVisible();
-
- await page.getByRole('button', { name: 'No events received?' }).click();
- await expect(page.getByText('Ensure client ID is correct')).toBeVisible();
- await expect(page.getByText(project.clientId).first()).toBeVisible();
- await page.getByRole('button', { name: 'Personal curl example' }).click();
- await expect(page.locator('code').last()).toContainText(
+ await expect(page.getByText('Listening for your first event')).toBeVisible();
+ await expect(
+ page.getByRole('link', { name: 'Skip for now, I will install later' })
+ ).toBeVisible();
+ // Troubleshooting lives behind a quiet link inside the listener.
+ await page.getByRole('button', { name: "I'm not receiving events" }).click();
+ const troubleshooting = page.getByRole('dialog', {
+ name: 'Not seeing events?',
+ });
+ await expect(
+ troubleshooting.getByText('Is the client ID the one for this project?')
+ ).toBeVisible();
+ await expect(
+ troubleshooting.getByText(project.clientId).first()
+ ).toBeVisible();
+ await expect(troubleshooting.locator('code').last()).toContainText(
`openpanel-client-id: ${project.clientId}`
);
await page.screenshot({
- path: `${SHOTS_DIR}/onboarding-verify-waiting.png`,
+ path: `${SHOTS_DIR}/onboarding-connect-waiting.png`,
fullPage: true,
});
-
- // Back and forward keep the step.
- await page.getByRole('link', { name: 'Back' }).click();
- await expect(page).toHaveURL(/\/connect$/);
- await page.goBack();
- await expect(page).toHaveURL(/\/verify$/);
- await expect(page.getByText('Waiting for events')).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(troubleshooting).toHaveCount(0);
expect(
trackEvent(
@@ -423,22 +446,23 @@ test('the verify step turns green when the first event arrives', async ({
'e2e_auth_first_event'
)
).toBe('200');
- await expect(page.getByText('Successfully connected')).toBeVisible({
+ await expect(page.getByText('Connected! Events are coming in.')).toBeVisible({
timeout: EVENT_ARRIVAL_TIMEOUT_MS,
});
await expect(page.getByText('e2e_auth_first_event')).toBeVisible();
- await expect(page.getByRole('link', { name: 'Skip for now' })).toHaveCount(0);
+ await expect(
+ page.getByRole('link', { name: 'Skip for now, I will install later' })
+ ).toHaveCount(0);
await page.screenshot({
- path: `${SHOTS_DIR}/onboarding-verify-connected.png`,
+ path: `${SHOTS_DIR}/onboarding-connect-connected.png`,
});
- await page.getByRole('link', { name: 'Your dashboard' }).click();
+ await page.getByRole('link', { name: 'Open dashboard' }).first().click();
await expect(page).toHaveURL(
new RegExp(`/${state.organizationId}/${project.id}$`)
);
expect(issues.unexpected()).toEqual([]);
});
-
test('an app and backend project can be added to the existing workspace', async ({
page,
context,
@@ -448,24 +472,23 @@ test('an app and backend project can be added to the existing workspace', async
const issues = watchIssues(page);
await gotoHydrated(page, '/onboarding/project');
// With a workspace in hand, reusing it is the default.
- await expect(page.getByLabel('Workspace name')).toHaveCount(0);
- await page.getByRole('combobox').click();
+ await expect(
+ page.getByRole('button', { name: 'Use existing workspace' })
+ ).toHaveAttribute('aria-pressed', 'true');
+ await page.getByRole('combobox', { name: 'Which workspace?' }).click();
await page.getByRole('option', { name: state.organizationName }).click();
- await page
- .getByLabel('Your first project name')
- .fill(`E2E auth server ${RUN_ID}`);
- await page.getByText('App', { exact: true }).click();
- await page.getByText('Backend / API', { exact: true }).click();
- await expect(page.getByLabel('Domain')).toBeHidden();
+ await page.getByLabel('Project name').fill(`E2E auth server ${RUN_ID}`);
+ await page.getByRole('button', { name: /^App/ }).click();
+ await page.getByRole('button', { name: /^Backend \/ API/ }).click();
+ await expect(page.getByLabel('Website URL')).toBeHidden();
const created = page.waitForResponse((response) =>
response.url().includes('/trpc/onboarding.project')
);
- await page.getByRole('button', { name: 'Next' }).click();
+ await page.getByRole('button', { name: 'Create project' }).click();
const client = (await (await created).json()).result.data.json;
expect(client.organizationId).toBe(state.organizationId);
- await expect(page.getByText('Client credentials')).toBeVisible();
- await expect(page.getByText(client.secret)).toBeVisible();
+ await expect(page.getByText('Listening for your first event')).toBeVisible();
writeState({
serverProject: {
id: client.projectId,
@@ -474,17 +497,22 @@ test('an app and backend project can be added to the existing workspace', async
},
});
- await page.getByRole('link', { name: 'Next' }).click();
- await expect(page).toHaveURL(/\/verify$/);
- await page.getByRole('button', { name: 'Personal curl example' }).click();
- // A backend project gets a server-side example, with the real secret while it is known.
- const example = page.locator('code').last();
- await expect(example).toContainText('"name":"test_event"');
+ // Server platforms get the secret in their snippets while it is known.
+ await page.getByRole('tab', { name: 'Manual setup' }).click();
+ await expect(page.locator('code').last()).toContainText(
+ `clientSecret: '${client.secret}'`
+ );
+ await page.getByRole('button', { name: "I'm not receiving events" }).click();
+ const example = page.getByRole('dialog').locator('code').last();
+ await expect(example).toContainText('"name":"openpanel_test_event"');
await expect(example).toContainText(
`openpanel-client-secret: ${client.secret}`
);
+ await page.keyboard.press('Escape');
- await page.getByRole('link', { name: 'Skip for now' }).click();
+ await page
+ .getByRole('link', { name: 'Skip for now, I will install later' })
+ .click();
await expect(page).toHaveURL(
new RegExp(`/${state.organizationId}/${client.projectId}$`)
);
@@ -501,7 +529,6 @@ test('the onboarding steps fit a phone screen', async ({
for (const [name, path] of [
['project', '/onboarding/project'],
['connect', `/onboarding/${state.webProject?.id}/connect`],
- ['verify', `/onboarding/${state.webProject?.id}/verify`],
['account', `/${state.organizationId}/account`],
['two-factor', `/${state.organizationId}/account/two-factor`],
] as const) {
diff --git a/apps/start/e2e/auth-session.spec.ts b/apps/start/e2e/auth-session.spec.ts
index 33e5e8aa8..8d7197506 100644
--- a/apps/start/e2e/auth-session.spec.ts
+++ b/apps/start/e2e/auth-session.spec.ts
@@ -29,7 +29,9 @@ test('an invalid session cookie is treated as signed out, not as an error', asyn
]);
await page.goto(`/${seed.organizationId}`);
await expect(page).toHaveURL(/\/login$/);
- await expect(page.getByRole('heading', { name: 'Sign in' })).toBeVisible();
+ await expect(
+ page.getByRole('heading', { name: 'Welcome back' })
+ ).toBeVisible();
const session = await request.get(`${apiUrl()}/trpc/auth.session`, {
headers: { cookie: 'session=not-a-session' },
@@ -78,7 +80,6 @@ test('a password with a trailing space signs in after signing up with it', async
lastName: 'Auth',
email,
password,
- confirmPassword: password,
},
},
});
diff --git a/apps/start/e2e/auth.setup.ts b/apps/start/e2e/auth.setup.ts
index d7a972f20..e2c126c62 100644
--- a/apps/start/e2e/auth.setup.ts
+++ b/apps/start/e2e/auth.setup.ts
@@ -15,7 +15,9 @@ setup('sign in as the seeded user', async ({ page }) => {
// until the values stick, then submit.
await expect(async () => {
await page.getByLabel('Email').fill(manifest.user.email);
- await page.getByLabel('Password').fill(manifest.user.password);
+ await page
+ .getByLabel('Password', { exact: true })
+ .fill(manifest.user.password);
await page.waitForTimeout(500);
await expect(page.getByLabel('Email')).toHaveValue(manifest.user.email);
}).toPass({ timeout: 15_000 });
diff --git a/apps/start/e2e/org-create-project.spec.ts b/apps/start/e2e/org-create-project.spec.ts
index e32b2ac5e..8cf447a23 100644
--- a/apps/start/e2e/org-create-project.spec.ts
+++ b/apps/start/e2e/org-create-project.spec.ts
@@ -169,15 +169,13 @@ test('a website + backend project is created with its domains and leads into set
await dialog.getByRole('link', { name: 'Set up tracking' }).click();
await expect(page).toHaveURL(new RegExp(`/onboarding/${project.id}/connect`));
+ await expect(page.getByText('Listening for your first event')).toBeVisible();
// The secret is read from sessionStorage after hydration.
await expect(page.getByText(/sec_[0-9a-f]{20}/).first()).toBeVisible({
timeout: HYDRATION_TIMEOUT_MS,
});
- await page.getByRole('link', { name: 'Next' }).click();
- await expect(page).toHaveURL(new RegExp(`/onboarding/${project.id}/verify`));
- await expect(page.getByText('Waiting for events')).toBeVisible();
await expect(
- page.getByRole('link', { name: 'Skip for now' })
+ page.getByRole('link', { name: 'Skip for now, I will install later' })
).toHaveAttribute('href', `/${seed.organizationId}/${project.id}`);
await deleteProjectThroughSettings(page, seed.organizationId, project.id);
diff --git a/apps/start/e2e/org-members.spec.ts b/apps/start/e2e/org-members.spec.ts
index 44ab84004..cbd076e5c 100644
--- a/apps/start/e2e/org-members.spec.ts
+++ b/apps/start/e2e/org-members.spec.ts
@@ -118,12 +118,11 @@ const signUpThroughInvite = async (
const guest = await context.newPage();
await dismissFeedbackPrompt(guest);
await gotoHydrated(guest, `/onboarding?inviteId=${inviteId}`);
- await expect(guest.getByText('Invitation to Acme')).toBeVisible();
+ await expect(guest.getByText('You are invited to Acme')).toBeVisible();
await guest.getByLabel('First name').fill('E2E');
await guest.getByLabel('Last name').fill('OrgMember');
await guest.getByLabel('Email').fill(email);
await guest.getByLabel('Password', { exact: true }).fill(GUEST_PASSWORD);
- await guest.getByLabel('Confirm password').fill(GUEST_PASSWORD);
await guest.getByRole('button', { name: 'Create account' }).click();
await guest.waitForURL(/\/acme$/, { timeout: 60_000 });
return { context, guest };
diff --git a/apps/start/e2e/org-multi.spec.ts b/apps/start/e2e/org-multi.spec.ts
index d9fc54beb..8034b9707 100644
--- a/apps/start/e2e/org-multi.spec.ts
+++ b/apps/start/e2e/org-multi.spec.ts
@@ -42,10 +42,12 @@ const createWorkspace = async (
if (await createNew.isVisible()) {
await createNew.click();
}
+ await page.getByLabel('Project name').fill(project);
+ // The workspace name follows the project name until it is edited.
+ await page.getByRole('button', { name: 'Change' }).click();
await page.getByLabel('Workspace name').fill(workspace);
- await page.getByLabel('Your first project name').fill(project);
- await page.getByRole('button', { name: 'Backend / API' }).click();
- await page.getByRole('button', { name: 'Next' }).click();
+ await page.getByRole('button', { name: /^Backend \/ API/ }).click();
+ await page.getByRole('button', { name: 'Create project' }).click();
await page.waitForURL(/\/onboarding\/.+\/connect/, {
timeout: NAVIGATION_TIMEOUT_MS,
});
@@ -82,7 +84,6 @@ test('a user with two organizations can switch between them and delete one', asy
await page.getByLabel('Last name').fill('OrgOwner');
await page.getByLabel('Email').fill(`e2e-org-owner-${stamp}@example.com`);
await page.getByLabel('Password', { exact: true }).fill(PASSWORD);
- await page.getByLabel('Confirm password').fill(PASSWORD);
await page.getByRole('button', { name: 'Create account' }).click();
await page.waitForURL(/\/onboarding\/project/, {
timeout: NAVIGATION_TIMEOUT_MS,
diff --git a/apps/start/e2e/settings-access.spec.ts b/apps/start/e2e/settings-access.spec.ts
index 417ed24f3..e9a8e7843 100644
--- a/apps/start/e2e/settings-access.spec.ts
+++ b/apps/start/e2e/settings-access.spec.ts
@@ -95,7 +95,6 @@ test.beforeAll(async ({ seed }) => {
lastName: 'Outsider',
email: `e2e-settings-outsider-${Date.now()}@openpanel.local`,
password: OUTSIDER_PASSWORD,
- confirmPassword: OUTSIDER_PASSWORD,
});
expect(signedUp.status, signedUp.errorMessage).toBe(200);
});
diff --git a/apps/start/e2e/verify-a-org.spec.ts b/apps/start/e2e/verify-a-org.spec.ts
index 5a2820096..0506fc3cf 100644
--- a/apps/start/e2e/verify-a-org.spec.ts
+++ b/apps/start/e2e/verify-a-org.spec.ts
@@ -27,7 +27,6 @@ test('cancelling an organization deletion keeps a project that was already sched
lastName: 'VerifyA',
email: `e2e-verify-a-${stamp}@example.com`,
password: PASSWORD,
- confirmPassword: PASSWORD,
});
const project = {
domain: null,
diff --git a/apps/start/src/components/auth/auth-shell.tsx b/apps/start/src/components/auth/auth-shell.tsx
new file mode 100644
index 000000000..caecbf836
--- /dev/null
+++ b/apps/start/src/components/auth/auth-shell.tsx
@@ -0,0 +1,82 @@
+import { LogoSquare } from '../logo';
+import { AuthShowcase } from './auth-showcase';
+import { useAppContext } from '@/hooks/use-app-context';
+
+const SELF_HOSTED_LINKS = [
+ { label: 'OpenPanel Cloud', href: 'https://openpanel.dev' },
+ {
+ label: 'Mixpanel alternative',
+ href: 'https://openpanel.dev/compare/mixpanel-alternative',
+ },
+ {
+ label: 'PostHog alternative',
+ href: 'https://openpanel.dev/compare/posthog-alternative',
+ },
+ {
+ label: 'Open source analytics',
+ href: 'https://openpanel.dev/articles/open-source-web-analytics',
+ },
+] as const;
+
+/** Two columns: the form on the left, social proof on the right. On small screens only the form remains. */
+export function AuthShell({ children }: { children: React.ReactNode }) {
+ const { isSelfHosted } = useAppContext();
+ return (
+ <div className="min-h-screen bg-background lg:grid lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)] xl:grid-cols-[minmax(0,5fr)_minmax(0,6fr)]">
+ <div className="flex min-h-screen flex-col">
+ <header className="flex items-center justify-between p-6 lg:px-10 lg:py-8">
+ <a
+ className="row items-center gap-2.5 font-medium"
+ href="https://openpanel.dev"
+ >
+ <LogoSquare className="size-8 shrink-0" />
+ <span>OpenPanel</span>
+ </a>
+ {isSelfHosted && (
+ <span className="rounded-full bg-def-200 px-2.5 py-1 text-muted-foreground text-xs">
+ Self-hosted
+ </span>
+ )}
+ </header>
+ <main className="flex flex-1 items-center justify-center px-6 py-6 lg:px-10">
+ <div className="w-full max-w-[400px]">{children}</div>
+ </main>
+ <footer className="p-6 text-center text-muted-foreground text-xs lg:px-10">
+ {isSelfHosted ? (
+ <nav>
+ <ul className="row flex-wrap justify-center gap-x-4 gap-y-1">
+ {SELF_HOSTED_LINKS.map((link) => (
+ <li key={link.href}>
+ <a className="hover:text-foreground" href={link.href}>
+ {link.label}
+ </a>
+ </li>
+ ))}
+ </ul>
+ </nav>
+ ) : (
+ <span>Open source product analytics · openpanel.dev</span>
+ )}
+ </footer>
+ </div>
+ <AuthShowcase />
+ </div>
+ );
+}
+
+export function AuthHeading({
+ title,
+ description,
+}: {
+ title: string;
+ description?: React.ReactNode;
+}) {
+ return (
+ <div className="col gap-2">
+ <h1 className="font-semibold text-2xl tracking-tight">{title}</h1>
+ {description && (
+ <p className="text-base text-muted-foreground">{description}</p>
+ )}
+ </div>
+ );
+}
diff --git a/apps/start/src/components/auth/auth-showcase.tsx b/apps/start/src/components/auth/auth-showcase.tsx
new file mode 100644
index 000000000..a3758b362
--- /dev/null
+++ b/apps/start/src/components/auth/auth-showcase.tsx
@@ -0,0 +1,114 @@
+import { useEffect, useState } from 'react';
+import { ChatPreview } from './chat-preview';
+import { cn } from '@/utils/cn';
+
+const ROTATE_EVERY_MS = 7000;
+
+const TESTIMONIALS: { quote: string; author: string; site?: string }[] = [
+ {
+ quote:
+ "OpenPanel is by far the best open-source analytics I've ever seen. Better UX, more features, and incredible support from the founder.",
+ author: 'Thomas Sanlis',
+ site: 'uneed.best',
+ },
+ {
+ quote:
+ 'It combines the power of Mixpanel with the ease of use of Plausible into a fully open-source product.',
+ author: 'Steven Tey',
+ site: 'dub.co',
+ },
+ {
+ quote:
+ 'After testing several product analytics tools we chose OpenPanel. Profiles and conversion events are our favorite features.',
+ author: 'Julien Hany',
+ site: 'strackr.com',
+ },
+ {
+ quote:
+ 'The Overview tab has everything I need: stats, graph, traffic sources, locations, devices. Clean, modern, very pleasing to the eye.',
+ author: 'Piotr Kulpinski',
+ site: 'producthunt.com',
+ },
+ {
+ quote:
+ 'After paying a lot to PostHog for years, OpenPanel gives us the same analytics while keeping full ownership of our data.',
+ author: 'Self-hosting team',
+ },
+];
+
+function useRotatingIndex(length: number) {
+ const [index, setIndex] = useState(0);
+ useEffect(() => {
+ const timer = window.setInterval(
+ () => setIndex((current) => (current + 1) % length),
+ ROTATE_EVERY_MS
+ );
+ return () => window.clearInterval(timer);
+ }, [length]);
+ return [index, setIndex] as const;
+}
+
+export function AuthShowcase() {
+ const [index, setIndex] = useRotatingIndex(TESTIMONIALS.length);
+ const testimonial = TESTIMONIALS[index] ?? TESTIMONIALS[0]!;
+
+ return (
+ // Pinned to the viewport so the page height never follows the chat
+ // replay; the replay takes whatever height is left between the headline
+ // and the testimonial, which always sits at the bottom.
+ <aside className="relative hidden overflow-hidden lg:sticky lg:top-3 lg:m-3 lg:flex lg:h-[calc(100vh-1.5rem)] lg:flex-col lg:self-start lg:rounded-2xl lg:bg-def-200 lg:p-12 xl:p-16">
+ <div
+ aria-hidden="true"
+ className="pointer-events-none absolute -top-40 -right-40 size-[32rem] rounded-full bg-highlight/10 blur-3xl"
+ />
+ <div className="col relative max-w-lg shrink-0 gap-4">
+ <h2 className="font-semibold text-3xl leading-tight tracking-tight">
+ Ask your analytics a question. Get the chart back.
+ </h2>
+ <p className="text-base text-muted-foreground [@media(max-height:820px)]:hidden">
+ Web and product analytics in one place, open source, and a chat that
+ answers with charts.
+ </p>
+ </div>
+ <div className="relative mt-6 min-h-0 max-w-lg flex-1">
+ <ChatPreview className="h-full" />
+ </div>
+
+ <figure className="col relative mt-6 max-w-lg shrink-0 gap-5 rounded-xl bg-background p-6 shadow-sm">
+ <blockquote
+ className="fade-in animate-in text-base leading-relaxed duration-500 motion-reduce:animate-none"
+ key={testimonial.author}
+ >
+ “{testimonial.quote}”
+ </blockquote>
+ <div className="row items-center justify-between gap-4">
+ <figcaption className="text-sm">
+ <span className="font-medium">{testimonial.author}</span>
+ {testimonial.site && (
+ <span className="text-muted-foreground">
+ {' '}
+ · {testimonial.site}
+ </span>
+ )}
+ </figcaption>
+ <div aria-hidden="true" className="row gap-1.5">
+ {TESTIMONIALS.map((item, dotIndex) => (
+ <button
+ className={cn(
+ 'h-1.5 rounded-full transition-all',
+ dotIndex === index
+ ? 'w-5 bg-foreground'
+ : 'w-1.5 bg-def-400 hover:bg-foreground/60'
+ )}
+ key={item.author}
+ onClick={() => setIndex(dotIndex)}
+ tabIndex={-1}
+ type="button"
+ />
+ ))}
+ </div>
+ </div>
+ </figure>
+ </aside>
+ );
+}
diff --git a/apps/start/src/components/auth/chat-preview.tsx b/apps/start/src/components/auth/chat-preview.tsx
new file mode 100644
index 000000000..e4694c8d2
--- /dev/null
+++ b/apps/start/src/components/auth/chat-preview.tsx
@@ -0,0 +1,295 @@
+import { ArrowUpIcon, SparklesIcon } from 'lucide-react';
+import {
+ AnimatePresence,
+ LayoutGroup,
+ motion,
+ useReducedMotion,
+} from 'motion/react';
+import { useEffect, useState } from 'react';
+import { cn } from '@/utils/cn';
+
+// A scripted replay of the dashboard chat: the visitor sees a question go
+// in and an answer with a chart come back, without anything to click.
+type ChartKind = 'trend' | 'breakdown' | 'funnel';
+
+type Turn =
+ | { role: 'user'; text: string }
+ | { role: 'assistant'; text: string; chart?: ChartKind };
+
+const SCRIPT: Turn[] = [
+ { role: 'user', text: 'How did signups do this week?' },
+ {
+ role: 'assistant',
+ text: 'Up 18% on last week: 1,284 signups against 1,089. The jump came on Tuesday.',
+ chart: 'trend',
+ },
+ { role: 'user', text: 'Where did they come from?' },
+ {
+ role: 'assistant',
+ text: 'Mostly Google and Product Hunt. Direct visitors convert best.',
+ chart: 'breakdown',
+ },
+ { role: 'user', text: 'Build a funnel from pricing to checkout' },
+ {
+ role: 'assistant',
+ text: '41% of pricing visitors start checkout; the drop is on the plan step.',
+ chart: 'funnel',
+ },
+];
+
+const THINKING_MS = 900;
+const AFTER_USER_MS = 500;
+const AFTER_ASSISTANT_MS = 2600;
+const RESTART_MS = 5000;
+
+// Messages slide up together as a new one arrives, like the real chat.
+const ENTER_TRANSITION = {
+ type: 'spring',
+ stiffness: 260,
+ damping: 28,
+} as const;
+const INSTANT = { duration: 0 } as const;
+
+const TREND = [96, 132, 148, 212, 240, 226, 230];
+const BREAKDOWN = [
+ { label: 'Google', value: 48 },
+ { label: 'Product Hunt', value: 27 },
+ { label: 'Direct', value: 17 },
+ { label: 'X / Twitter', value: 8 },
+];
+const FUNNEL = [
+ { label: 'Viewed pricing', value: 100, count: '3,120' },
+ { label: 'Picked a plan', value: 58, count: '1,810' },
+ { label: 'Started checkout', value: 41, count: '1,279' },
+];
+
+/** How many turns are on screen, and whether the assistant is "thinking" about the next one. */
+function useScriptedReplay(length: number, reducedMotion: boolean) {
+ // Starts at one turn on server and client alike; reduced motion reveals
+ // the rest in the effect, so hydration never sees a different list.
+ const [shown, setShown] = useState(1);
+ const [thinking, setThinking] = useState(false);
+
+ useEffect(() => {
+ if (reducedMotion) {
+ setThinking(false);
+ setShown(length);
+ return;
+ }
+ if (shown >= length) {
+ const restart = window.setTimeout(() => setShown(1), RESTART_MS);
+ return () => window.clearTimeout(restart);
+ }
+ const next = SCRIPT[shown];
+ const previous = SCRIPT[shown - 1];
+ const timers: number[] = [];
+ if (next?.role === 'assistant') {
+ timers.push(window.setTimeout(() => setThinking(true), AFTER_USER_MS));
+ timers.push(
+ window.setTimeout(() => {
+ setThinking(false);
+ setShown((count) => count + 1);
+ }, AFTER_USER_MS + THINKING_MS)
+ );
+ } else {
+ timers.push(
+ window.setTimeout(
+ () => setShown((count) => count + 1),
+ previous?.role === 'assistant' ? AFTER_ASSISTANT_MS : AFTER_USER_MS
+ )
+ );
+ }
+ return () => {
+ for (const timer of timers) {
+ window.clearTimeout(timer);
+ }
+ };
+ }, [shown, length, reducedMotion]);
+
+ return { shown, thinking };
+}
+
+export function ChatPreview({ className }: { className?: string }) {
+ const reducedMotion = useReducedMotion() ?? false;
+ const { shown, thinking } = useScriptedReplay(SCRIPT.length, reducedMotion);
+ const turns = SCRIPT.slice(0, shown);
+
+ return (
+ <div
+ aria-hidden="true"
+ className={cn(
+ 'flex max-h-[38rem] flex-col overflow-hidden rounded-xl border bg-background shadow-sm',
+ className
+ )}
+ >
+ <LayoutGroup>
+ <div className="flex flex-1 flex-col justify-end gap-3 overflow-hidden p-4 [mask-image:linear-gradient(to_bottom,transparent,black_3rem)]">
+ <AnimatePresence initial={false}>
+ {turns.map((turn, index) => (
+ <motion.div
+ animate={{ opacity: 1, y: 0 }}
+ className={
+ turn.role === 'user' ? 'flex justify-end' : 'col gap-2'
+ }
+ exit={{ opacity: 0, transition: { duration: 0.15 } }}
+ initial={{ opacity: 0, y: 16 }}
+ key={`${index}-${turn.text}`}
+ layout="position"
+ transition={reducedMotion ? INSTANT : ENTER_TRANSITION}
+ >
+ {turn.role === 'user' ? (
+ <div className="max-w-[85%] rounded-2xl rounded-br-md bg-primary px-4 py-2.5 text-primary-foreground text-sm">
+ {turn.text}
+ </div>
+ ) : (
+ <>
+ <p className="text-sm">{turn.text}</p>
+ {turn.chart && <ChartCard kind={turn.chart} />}
+ </>
+ )}
+ </motion.div>
+ ))}
+ {thinking && (
+ <motion.div
+ animate={{ opacity: 1, y: 0 }}
+ className="op-shimmer font-medium text-muted-foreground text-sm"
+ exit={{ opacity: 0, transition: { duration: 0.15 } }}
+ initial={{ opacity: 0, y: 8 }}
+ key="thinking"
+ layout="position"
+ transition={reducedMotion ? INSTANT : ENTER_TRANSITION}
+ >
+ Thinking…
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </div>
+ </LayoutGroup>
+ <div className="row m-3 mt-0 items-center gap-3 rounded-2xl border bg-card px-4 py-2.5">
+ <SparklesIcon className="size-4 shrink-0 text-muted-foreground" />
+ <span className="flex-1 truncate text-muted-foreground/70 text-sm">
+ Ask about your data, build a chart, or ask how something works…
+ </span>
+ <span className="center-center size-7 shrink-0 rounded-full bg-primary text-primary-foreground">
+ <ArrowUpIcon className="size-3.5" />
+ </span>
+ </div>
+ </div>
+ );
+}
+
+function ChartCard({ kind }: { kind: ChartKind }) {
+ const titles: Record<ChartKind, [string, string]> = {
+ trend: ['Signups', 'Last 7 days, by day'],
+ breakdown: ['Signups by referrer', 'Last 7 days'],
+ funnel: ['Pricing to checkout', 'Last 30 days'],
+ };
+ const [title, subtitle] = titles[kind];
+ return (
+ <div className="overflow-hidden rounded-xl border bg-card">
+ <div className="px-4 pt-3 pb-1">
+ <div className="font-medium text-sm">{title}</div>
+ <div className="text-muted-foreground text-xs">{subtitle}</div>
+ </div>
+ <div className="px-4 pt-1 pb-4">
+ {kind === 'trend' && <TrendChart />}
+ {kind === 'breakdown' && <BreakdownChart />}
+ {kind === 'funnel' && <FunnelChart />}
+ </div>
+ </div>
+ );
+}
+
+const TREND_WIDTH = 300;
+const TREND_HEIGHT = 72;
+
+function TrendChart() {
+ const max = Math.max(...TREND);
+ const stepX = TREND_WIDTH / (TREND.length - 1);
+ const points = TREND.map(
+ (value, index) =>
+ [
+ index * stepX,
+ TREND_HEIGHT - (value / max) * (TREND_HEIGHT - 8),
+ ] as const
+ );
+ const line = points.map(([x, y]) => `${x},${y}`).join(' ');
+ const area = `0,${TREND_HEIGHT} ${line} ${TREND_WIDTH},${TREND_HEIGHT}`;
+ return (
+ <div className="col gap-2">
+ <div className="row items-baseline gap-2">
+ <span className="font-semibold text-xl tabular-nums">1,284</span>
+ <span className="text-emerald-600 text-xs tabular-nums dark:text-emerald-400">
+ +18%
+ </span>
+ </div>
+ <svg
+ className="h-[72px] w-full"
+ preserveAspectRatio="none"
+ viewBox={`0 0 ${TREND_WIDTH} ${TREND_HEIGHT}`}
+ >
+ <title>Signups trend</title>
+ <polygon
+ className="fill-chart-0/15"
+ points={area}
+ vectorEffect="non-scaling-stroke"
+ />
+ <polyline
+ className="stroke-chart-0"
+ fill="none"
+ points={line}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ vectorEffect="non-scaling-stroke"
+ />
+ </svg>
+ </div>
+ );
+}
+
+function BreakdownChart() {
+ return (
+ <ul className="col gap-2">
+ {BREAKDOWN.map((row) => (
+ <li className="col gap-1" key={row.label}>
+ <div className="row justify-between text-xs">
+ <span>{row.label}</span>
+ <span className="text-muted-foreground tabular-nums">
+ {row.value}%
+ </span>
+ </div>
+ <div className="h-1.5 rounded-full bg-def-200 dark:bg-def-300">
+ <div
+ className="h-full rounded-full bg-chart-0"
+ style={{ width: `${row.value}%` }}
+ />
+ </div>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+function FunnelChart() {
+ return (
+ <ul className="col gap-2">
+ {FUNNEL.map((step) => (
+ <li className="col gap-1" key={step.label}>
+ <div className="row justify-between text-xs">
+ <span>{step.label}</span>
+ <span className="text-muted-foreground tabular-nums">
+ {step.count} · {step.value}%
+ </span>
+ </div>
+ <div className="h-2 rounded bg-def-200 dark:bg-def-300">
+ <div
+ className="h-full rounded bg-chart-0"
+ style={{ width: `${step.value}%` }}
+ />
+ </div>
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/apps/start/src/components/auth/last-used-badge.tsx b/apps/start/src/components/auth/last-used-badge.tsx
new file mode 100644
index 000000000..12cbf9fd7
--- /dev/null
+++ b/apps/start/src/components/auth/last-used-badge.tsx
@@ -0,0 +1,7 @@
+export function LastUsedBadge() {
+ return (
+ <span className="absolute -top-2.5 right-3 rounded-full bg-highlight px-2 py-0.5 font-medium text-2xs text-white leading-none">
+ Used last time
+ </span>
+ );
+}
diff --git a/apps/start/src/components/auth/or.tsx b/apps/start/src/components/auth/or.tsx
index 6263b26f0..030ad67f3 100644
--- a/apps/start/src/components/auth/or.tsx
+++ b/apps/start/src/components/auth/or.tsx
@@ -1,11 +1,17 @@
import { cn } from '@/utils/cn';
-export function Or({ className }: { className?: string }) {
+export function Or({
+ className,
+ children = 'or',
+}: {
+ className?: string;
+ children?: React.ReactNode;
+}) {
return (
- <div className={cn('row items-center gap-4', className)}>
- <div className="h-px w-full bg-def-300" />
- <span className="px-2 font-medium text-muted-foreground text-sm">OR</span>
- <div className="h-px w-full bg-def-300" />
+ <div className={cn('row items-center gap-4', className)} role="separator">
+ <div className="h-px flex-1 bg-border" />
+ <span className="text-muted-foreground text-sm">{children}</span>
+ <div className="h-px flex-1 bg-border" />
</div>
);
}
diff --git a/apps/start/src/components/auth/password-input.tsx b/apps/start/src/components/auth/password-input.tsx
new file mode 100644
index 000000000..9e8e0286a
--- /dev/null
+++ b/apps/start/src/components/auth/password-input.tsx
@@ -0,0 +1,56 @@
+import { EyeIcon, EyeOffIcon } from 'lucide-react';
+import { forwardRef, useId, useState } from 'react';
+import { fieldMessageId, WithLabel } from '../forms/input-with-label';
+import { Input, type InputProps } from '../ui/input';
+
+type Props = Omit<InputProps, 'type'> & {
+ label: string;
+ error?: string | undefined;
+ hint?: React.ReactNode;
+ /** Rendered at the right end of the label row, e.g. a "Forgot password?" link. */
+ action?: React.ReactNode;
+};
+
+export const PasswordInput = forwardRef<HTMLInputElement, Props>(
+ ({ label, error, hint, action, className, size, ...inputProps }, ref) => {
+ const [visible, setVisible] = useState(false);
+ const generatedId = useId();
+ const fieldId = inputProps.id ?? generatedId;
+ const hasMessage = Boolean(error ?? hint);
+ return (
+ <WithLabel
+ action={action}
+ className={className}
+ error={error}
+ hint={hint}
+ id={fieldId}
+ label={label}
+ >
+ <div className="relative">
+ <Input
+ error={error}
+ ref={ref}
+ size={size}
+ {...inputProps}
+ aria-describedby={hasMessage ? fieldMessageId(fieldId) : undefined}
+ autoComplete={inputProps.autoComplete ?? 'current-password'}
+ className="pr-11"
+ id={fieldId}
+ type={visible ? 'text' : 'password'}
+ />
+ <button
+ aria-label={visible ? 'Hide password' : 'Show password'}
+ aria-pressed={visible}
+ className="absolute inset-y-0 right-0 flex w-11 items-center justify-center rounded-r-lg text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={() => setVisible((current) => !current)}
+ type="button"
+ >
+ {visible ? <EyeOffIcon size={18} /> : <EyeIcon size={18} />}
+ </button>
+ </div>
+ </WithLabel>
+ );
+ }
+);
+
+PasswordInput.displayName = 'PasswordInput';
diff --git a/apps/start/src/components/auth/reset-password-form.tsx b/apps/start/src/components/auth/reset-password-form.tsx
index 463097b94..67ceab64f 100644
--- a/apps/start/src/components/auth/reset-password-form.tsx
+++ b/apps/start/src/components/auth/reset-password-form.tsx
@@ -5,8 +5,9 @@ import { useNavigate } from '@tanstack/react-router';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
-import { InputWithLabel } from '../forms/input-with-label';
import { Button } from '../ui/button';
+import { AuthHeading } from './auth-shell';
+import { PasswordInput } from './password-input';
import { useTRPC } from '@/integrations/trpc/react';
const validator = zResetPassword;
@@ -43,26 +44,30 @@ export function ResetPasswordForm({ token }: { token: string }) {
return (
<div className="col gap-8">
- <div>
- <h1 className="mb-2 font-bold text-3xl text-foreground">
- Reset your password
- </h1>
- <p className="text-muted-foreground">
- Already have an account?{' '}
- <a className="underline" href="/login">
- Sign in
- </a>
- </p>
- </div>
- <form className="col gap-6" method="post" onSubmit={onSubmit}>
- <InputWithLabel
+ <AuthHeading
+ description="Choose a new password for your account."
+ title="Reset your password"
+ />
+ <form className="col gap-5" method="post" onSubmit={onSubmit}>
+ <PasswordInput
+ autoComplete="new-password"
+ error={form.formState.errors.password?.message}
+ hint="At least 8 characters"
label="New password"
placeholder="New password"
- type="password"
+ size="xl"
{...form.register('password')}
/>
- <Button type="submit">Reset password</Button>
+ <Button loading={mutation.isPending} size="xl" type="submit">
+ Reset password
+ </Button>
</form>
+ <p className="text-center text-muted-foreground text-sm">
+ Remembered it after all?{' '}
+ <a className="font-medium text-foreground underline" href="/login">
+ Sign in
+ </a>
+ </p>
</div>
);
}
diff --git a/apps/start/src/components/auth/sign-in-dev.tsx b/apps/start/src/components/auth/sign-in-dev.tsx
index f7b9fae9d..fb8ba6bb0 100644
--- a/apps/start/src/components/auth/sign-in-dev.tsx
+++ b/apps/start/src/components/auth/sign-in-dev.tsx
@@ -24,12 +24,12 @@ export function SignInDev({ inviteId }: { inviteId?: string }) {
return (
<Button
className="w-full"
+ icon={TerminalIcon}
loading={mutation.isPending}
onClick={() => mutation.mutate({ inviteId })}
- size="lg"
- variant="outline"
+ size="xl"
+ variant="secondary"
>
- <TerminalIcon className="mr-2 size-4" />
Dev login
</Button>
);
diff --git a/apps/start/src/components/auth/sign-in-email-form.tsx b/apps/start/src/components/auth/sign-in-email-form.tsx
index 116e831ea..ab2d2956c 100644
--- a/apps/start/src/components/auth/sign-in-email-form.tsx
+++ b/apps/start/src/components/auth/sign-in-email-form.tsx
@@ -1,13 +1,20 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { zSignInEmail } from '@openpanel/core/modules/auth/auth.constants';
import { useMutation } from '@tanstack/react-query';
-import { type SubmitHandler, useForm } from 'react-hook-form';
+import {
+ type SubmitErrorHandler,
+ type SubmitHandler,
+ useForm,
+} from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
import { InputWithLabel } from '../forms/input-with-label';
import { Button } from '../ui/button';
+import { LastUsedBadge } from './last-used-badge';
+import { PasswordInput } from './password-input';
import { useTRPC } from '@/integrations/trpc/react';
import { pushModal } from '@/modals';
+import { failureReason, trackFunnel } from '@/utils/funnel-tracking';
const validator = zSignInEmail;
type IForm = z.infer<typeof validator>;
@@ -23,6 +30,10 @@ export function SignInEmailForm({
const mutation = useMutation(
trpc.auth.signInEmail.mutationOptions({
async onSuccess(data) {
+ trackFunnel('auth_signin_succeeded', {
+ provider: 'email',
+ totpRequired: data.type === 'totp_required',
+ });
if (data.type === 'totp_required') {
window.location.href = '/verify';
return;
@@ -31,6 +42,10 @@ export function SignInEmailForm({
window.location.href = '/';
},
onError(error) {
+ trackFunnel('auth_signin_failed', {
+ provider: 'email',
+ reason: failureReason(error),
+ });
toast.error(error.message);
},
})
@@ -43,50 +58,71 @@ export function SignInEmailForm({
},
});
const onSubmit: SubmitHandler<IForm> = (values) => {
+ trackFunnel('auth_provider_clicked', {
+ page: 'login',
+ provider: 'email',
+ isLastUsed: Boolean(isLastUsed),
+ });
mutation.mutate({
...values,
inviteId,
});
};
+ const onInvalid: SubmitErrorHandler<IForm> = (errors) => {
+ trackFunnel('auth_form_invalid', {
+ page: 'login',
+ fields: Object.keys(errors),
+ });
+ };
return (
<form
- className="col gap-4"
+ className="col gap-5"
method="post"
- onSubmit={form.handleSubmit(onSubmit)}
+ onSubmit={form.handleSubmit(onSubmit, onInvalid)}
>
<InputWithLabel
{...form.register('email')}
+ autoComplete="email"
error={form.formState.errors.email?.message}
+ inputMode="email"
label="Email"
+ placeholder="[email protected]"
+ size="xl"
+ type="email"
/>
- <InputWithLabel
+ <PasswordInput
{...form.register('password')}
+ action={
+ <button
+ className="text-muted-foreground text-sm transition-colors hover:text-foreground hover:underline"
+ onClick={() => {
+ trackFunnel('auth_forgot_password_clicked');
+ pushModal('RequestPasswordReset', {
+ email: form.getValues('email'),
+ });
+ }}
+ type="button"
+ >
+ Forgot password?
+ </button>
+ }
error={form.formState.errors.password?.message}
label="Password"
- type="password"
+ placeholder="Your password"
+ size="xl"
/>
- <div className="relative">
- <Button className="w-full" size="lg" type="submit">
+ <div className="relative mt-1">
+ <Button
+ className="w-full"
+ loading={mutation.isPending}
+ size="xl"
+ type="submit"
+ >
Sign in
</Button>
- {isLastUsed && (
- <span className="absolute -top-2 right-3 rounded-full bg-highlight px-1.5 py-0.5 font-medium text-2xs text-white leading-none">
- Used last time
- </span>
- )}
+ {isLastUsed && <LastUsedBadge />}
</div>
- <button
- className="mt-2 text-center text-muted-foreground text-sm transition-colors duration-200 hover:text-highlight hover:underline"
- onClick={() =>
- pushModal('RequestPasswordReset', {
- email: form.getValues('email'),
- })
- }
- type="button"
- >
- Forgot password?
- </button>
</form>
);
}
diff --git a/apps/start/src/components/auth/sign-in-github.tsx b/apps/start/src/components/auth/sign-in-github.tsx
deleted file mode 100644
index 78fb5ae70..000000000
--- a/apps/start/src/components/auth/sign-in-github.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { useMutation } from '@tanstack/react-query';
-import { Button } from '../ui/button';
-import { useTRPC } from '@/integrations/trpc/react';
-
-export function SignInGithub({
- type,
- inviteId,
- isLastUsed,
-}: {
- type: 'sign-in' | 'sign-up';
- inviteId?: string;
- isLastUsed?: boolean;
-}) {
- const trpc = useTRPC();
- const mutation = useMutation(
- trpc.auth.signInOAuth.mutationOptions({
- onSuccess(res) {
- if (res.url) {
- window.location.href = res.url;
- }
- },
- })
- );
- const title = () => {
- if (type === 'sign-in') {
- return 'Sign in with Github';
- }
- if (type === 'sign-up') {
- return 'Sign up with Github';
- }
- };
- return (
- <div className="relative">
- <Button
- className="w-full bg-primary text-primary-foreground shadow-sm transition-all duration-200 hover:bg-primary/90 hover:shadow-md [&_svg]:shrink-0"
- onClick={() =>
- mutation.mutate({
- provider: 'github',
- inviteId,
- })
- }
- size="lg"
- >
- <svg
- className="mr-2 size-4"
- fill="currentColor"
- height="24"
- viewBox="0 0 24 24"
- width="24"
- xmlns="http://www.w3.org/2000/svg"
- >
- <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
- </svg>
- {title()}
- </Button>
- {isLastUsed && (
- <span className="absolute -top-2 right-3 rounded-full bg-highlight px-1.5 py-0.5 font-medium text-2xs text-white leading-none">
- Used last time
- </span>
- )}
- </div>
- );
-}
diff --git a/apps/start/src/components/auth/sign-in-google.tsx b/apps/start/src/components/auth/sign-in-google.tsx
deleted file mode 100644
index 125f59117..000000000
--- a/apps/start/src/components/auth/sign-in-google.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import { useMutation } from '@tanstack/react-query';
-import { Button } from '../ui/button';
-import { useTRPC } from '@/integrations/trpc/react';
-
-export function SignInGoogle({
- type,
- inviteId,
- isLastUsed,
-}: {
- type: 'sign-in' | 'sign-up';
- inviteId?: string;
- isLastUsed?: boolean;
-}) {
- const trpc = useTRPC();
- const mutation = useMutation(
- trpc.auth.signInOAuth.mutationOptions({
- onSuccess(res) {
- if (res.url) {
- window.location.href = res.url;
- }
- },
- })
- );
- const title = () => {
- if (type === 'sign-in') {
- return 'Sign in with Google';
- }
- if (type === 'sign-up') {
- return 'Sign up with Google';
- }
- };
- return (
- <div className="relative">
- <Button
- className="w-full border border-def-300 bg-background text-foreground shadow-sm transition-all duration-200 hover:bg-def-100 hover:shadow-md [&_svg]:shrink-0"
- onClick={() =>
- mutation.mutate({
- provider: 'google',
- inviteId,
- })
- }
- size="lg"
- >
- <svg
- className="mr-2 size-4"
- viewBox="0 0 24 24"
- xmlns="http://www.w3.org/2000/svg"
- >
- <path
- d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
- fill="#4285F4"
- />
- <path
- d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
- fill="#34A853"
- />
- <path
- d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
- fill="#FBBC05"
- />
- <path
- d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
- fill="#EA4335"
- />
- </svg>
- {title()}
- </Button>
- {isLastUsed && (
- <span className="absolute -top-2 right-3 rounded-full bg-highlight px-1.5 py-0.5 font-medium text-2xs text-white leading-none">
- Used last time
- </span>
- )}
- </div>
- );
-}
diff --git a/apps/start/src/components/auth/sign-in-oauth.tsx b/apps/start/src/components/auth/sign-in-oauth.tsx
new file mode 100644
index 000000000..8cdf6941e
--- /dev/null
+++ b/apps/start/src/components/auth/sign-in-oauth.tsx
@@ -0,0 +1,108 @@
+import { useMutation } from '@tanstack/react-query';
+import { toast } from 'sonner';
+import { Button } from '../ui/button';
+import { LastUsedBadge } from './last-used-badge';
+import { useTRPC } from '@/integrations/trpc/react';
+import { failureReason, trackFunnel } from '@/utils/funnel-tracking';
+
+export type OAuthProvider = 'google' | 'github';
+
+const PROVIDER_LABELS: Record<OAuthProvider, string> = {
+ google: 'Google',
+ github: 'GitHub',
+};
+
+function GoogleIcon() {
+ return (
+ <svg
+ aria-hidden="true"
+ className="size-5 shrink-0"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
+ fill="#4285F4"
+ />
+ <path
+ d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
+ fill="#34A853"
+ />
+ <path
+ d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
+ fill="#FBBC05"
+ />
+ <path
+ d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
+ fill="#EA4335"
+ />
+ </svg>
+ );
+}
+
+function GithubIcon() {
+ return (
+ <svg
+ aria-hidden="true"
+ className="size-5 shrink-0"
+ fill="currentColor"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
+ </svg>
+ );
+}
+
+export function SignInOAuth({
+ provider,
+ type,
+ inviteId,
+ isLastUsed,
+}: {
+ provider: OAuthProvider;
+ type: 'sign-in' | 'sign-up';
+ inviteId?: string;
+ isLastUsed?: boolean;
+}) {
+ const trpc = useTRPC();
+ const mutation = useMutation(
+ trpc.auth.signInOAuth.mutationOptions({
+ onSuccess(res) {
+ if (res.url) {
+ window.location.href = res.url;
+ }
+ },
+ onError(error) {
+ trackFunnel(
+ type === 'sign-in' ? 'auth_signin_failed' : 'auth_signup_failed',
+ { provider, reason: failureReason(error) }
+ );
+ toast.error(error.message);
+ },
+ })
+ );
+ const verb = type === 'sign-in' ? 'Sign in' : 'Sign up';
+ return (
+ <div className="relative">
+ <Button
+ className="w-full gap-3 border-def-300 bg-background hover:bg-def-100 dark:hover:bg-def-200"
+ loading={mutation.isPending}
+ onClick={() => {
+ trackFunnel('auth_provider_clicked', {
+ page: type === 'sign-in' ? 'login' : 'signup',
+ provider,
+ isLastUsed: Boolean(isLastUsed),
+ });
+ mutation.mutate({ provider, inviteId });
+ }}
+ size="xl"
+ variant="outline"
+ >
+ {provider === 'google' ? <GoogleIcon /> : <GithubIcon />}
+ {verb} with {PROVIDER_LABELS[provider]}
+ </Button>
+ {isLastUsed && <LastUsedBadge />}
+ </div>
+ );
+}
diff --git a/apps/start/src/components/auth/sign-up-email-form.tsx b/apps/start/src/components/auth/sign-up-email-form.tsx
index 49498db55..c391e3760 100644
--- a/apps/start/src/components/auth/sign-up-email-form.tsx
+++ b/apps/start/src/components/auth/sign-up-email-form.tsx
@@ -1,12 +1,18 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { zSignUpEmail } from '@openpanel/core/modules/auth/auth.constants';
import { useMutation } from '@tanstack/react-query';
-import { type SubmitHandler, useForm } from 'react-hook-form';
+import {
+ type SubmitErrorHandler,
+ type SubmitHandler,
+ useForm,
+} from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
import { InputWithLabel } from '../forms/input-with-label';
import { Button } from '../ui/button';
+import { PasswordInput } from './password-input';
import { useTRPC } from '@/integrations/trpc/react';
+import { failureReason, trackFunnel } from '@/utils/funnel-tracking';
const validator = zSignUpEmail;
type IForm = z.infer<typeof validator>;
@@ -20,10 +26,18 @@ export function SignUpEmailForm({
const mutation = useMutation(
trpc.auth.signUpEmail.mutationOptions({
async onSuccess() {
+ trackFunnel('auth_signup_succeeded', {
+ provider: 'email',
+ hasInvite: Boolean(inviteId),
+ });
toast.success('Successfully signed up');
window.location.href = '/';
},
onError(error) {
+ trackFunnel('auth_signup_failed', {
+ provider: 'email',
+ reason: failureReason(error),
+ });
toast.error(error.message);
},
})
@@ -32,57 +46,69 @@ export function SignUpEmailForm({
resolver: zodResolver(validator),
});
const onSubmit: SubmitHandler<IForm> = (values) => {
+ trackFunnel('auth_provider_clicked', { page: 'signup', provider: 'email' });
mutation.mutate({
...values,
inviteId,
});
};
+ const onInvalid: SubmitErrorHandler<IForm> = (errors) => {
+ trackFunnel('auth_form_invalid', {
+ page: 'signup',
+ fields: Object.keys(errors),
+ });
+ };
return (
<form
- className="col gap-4"
+ className="col gap-5"
method="post"
- onSubmit={form.handleSubmit(onSubmit)}
+ onSubmit={form.handleSubmit(onSubmit, onInvalid)}
>
- <div className="row w-full flex-1 gap-4">
+ <div className="grid gap-4 sm:grid-cols-2">
<InputWithLabel
- className="flex-1"
+ autoComplete="given-name"
label="First name"
+ placeholder="Ada"
+ size="xl"
type="text"
{...form.register('firstName')}
error={form.formState.errors.firstName?.message}
/>
<InputWithLabel
- className="flex-1"
+ autoComplete="family-name"
label="Last name"
+ placeholder="Lovelace"
+ size="xl"
type="text"
{...form.register('lastName')}
error={form.formState.errors.lastName?.message}
/>
</div>
<InputWithLabel
- className="w-full"
+ autoComplete="email"
+ inputMode="email"
label="Email"
+ placeholder="[email protected]"
+ size="xl"
type="email"
{...form.register('email')}
error={form.formState.errors.email?.message}
/>
- <div className="row w-full gap-4">
- <InputWithLabel
- className="flex-1"
- label="Password"
- type="password"
- {...form.register('password')}
- error={form.formState.errors.password?.message}
- />
- <InputWithLabel
- className="flex-1"
- label="Confirm password"
- type="password"
- {...form.register('confirmPassword')}
- error={form.formState.errors.confirmPassword?.message}
- />
- </div>
- <Button className="w-full" size="lg" type="submit">
+ <PasswordInput
+ autoComplete="new-password"
+ hint="At least 8 characters"
+ label="Password"
+ placeholder="Pick a strong password"
+ size="xl"
+ {...form.register('password')}
+ error={form.formState.errors.password?.message}
+ />
+ <Button
+ className="mt-1 w-full"
+ loading={mutation.isPending}
+ size="xl"
+ type="submit"
+ >
Create account
</Button>
</form>
diff --git a/apps/start/src/components/chat/chat-empty.tsx b/apps/start/src/components/chat/chat-empty.tsx
index bb63ddbe4..f90227f4d 100644
--- a/apps/start/src/components/chat/chat-empty.tsx
+++ b/apps/start/src/components/chat/chat-empty.tsx
@@ -46,6 +46,13 @@ function promptsFor(hint?: ChatLaunchHint): string[] {
'Which pages are losing traffic?',
'Chart pageviews for /pricing over time',
];
+ case 'onboarding':
+ return [
+ 'Why are no events arriving?',
+ 'Check my install on my website',
+ 'Which SDK fits my stack?',
+ 'Show the last events that reached this project',
+ ];
case 'events':
return [
'Which events fire most often?',
diff --git a/apps/start/src/components/clients/create-client-success.tsx b/apps/start/src/components/clients/create-client-success.tsx
index 2a252822b..0317c1066 100644
--- a/apps/start/src/components/clients/create-client-success.tsx
+++ b/apps/start/src/components/clients/create-client-success.tsx
@@ -5,7 +5,9 @@ import { Button } from '@/components/ui/button';
import { isRealClientSecret } from '@/hooks/use-client-secret';
import { clipboard } from '@/utils/clipboard';
-type Props = { id: string; secret: string; type?: 'read' | 'write' | 'root' };
+// `type` is required on purpose: MCP rejects write clients, so a caller that
+// forgets it must not get a token rendered by accident.
+type Props = { id: string; secret: string; type: 'read' | 'write' | 'root' };
export function CreateClientSuccess({ id, secret, type }: Props) {
// Only derive credentials from a real secret — the '[CLIENT_SECRET]'
@@ -51,6 +53,12 @@ export function CreateClientSuccess({ id, secret, type }: Props) {
</p>
</div>
)}
+ {type === 'write' && (
+ <p className="text-muted-foreground text-sm">
+ Write clients cannot be used with MCP. For an AI assistant, create a
+ read client under Settings → MCP.
+ </p>
+ )}
<div className="row gap-2 [&>*]:flex-1">
<Button
icon={CopyIcon}
diff --git a/apps/start/src/components/forms/copy-input.tsx b/apps/start/src/components/forms/copy-input.tsx
index ec7c36d5e..10698fee4 100644
--- a/apps/start/src/components/forms/copy-input.tsx
+++ b/apps/start/src/components/forms/copy-input.tsx
@@ -3,17 +3,21 @@ import { Label } from '../ui/label';
import { clipboard } from '@/utils/clipboard';
import { cn } from '@/utils/cn';
-type Props = {
+interface Props {
label: React.ReactNode;
value: string;
className?: string;
-};
+ onCopy?: () => void;
+}
-const CopyInput = ({ label, value, className }: Props) => {
+const CopyInput = ({ label, value, className, onCopy }: Props) => {
return (
<button
className={cn('w-full min-w-0 text-left', className)}
- onClick={() => clipboard(value)}
+ onClick={() => {
+ clipboard(value);
+ onCopy?.();
+ }}
type="button"
>
{!!label && <Label>{label}</Label>}
diff --git a/apps/start/src/components/forms/input-with-label.tsx b/apps/start/src/components/forms/input-with-label.tsx
index 9e43aa782..74c560a5a 100644
--- a/apps/start/src/components/forms/input-with-label.tsx
+++ b/apps/start/src/components/forms/input-with-label.tsx
@@ -15,6 +15,8 @@ interface WithLabel {
/** Shown under the field; replaced by the error while there is one. */
hint?: React.ReactNode;
info?: React.ReactNode;
+ /** Rendered at the right end of the label row, e.g. a "Forgot password?" link. */
+ action?: React.ReactNode;
className?: string;
}
type InputWithLabelProps = InputProps & Omit<WithLabel, 'children'>;
@@ -31,20 +33,31 @@ export const WithLabel = ({
id,
hint,
info,
+ action,
error,
}: WithLabel) => {
const message = error ?? hint;
const fieldId = id ?? label;
+ const labelElement = (
+ <Label className="mb-0 flex items-center gap-1" htmlFor={fieldId}>
+ {label}
+ {info && (
+ <Tooltiper content={info}>
+ <InfoIcon className="text-muted-foreground" size={14} />
+ </Tooltiper>
+ )}
+ </Label>
+ );
return (
<div className={cn('flex flex-col gap-1.5', className)}>
- <Label className="mb-0 flex items-center gap-1" htmlFor={fieldId}>
- {label}
- {info && (
- <Tooltiper content={info}>
- <InfoIcon className="text-muted-foreground" size={14} />
- </Tooltiper>
- )}
- </Label>
+ {action ? (
+ <div className="flex items-center justify-between gap-2">
+ {labelElement}
+ {action}
+ </div>
+ ) : (
+ labelElement
+ )}
{children}
{message && (
<p
@@ -64,7 +77,7 @@ export const WithLabel = ({
};
export const InputWithLabel = forwardRef<HTMLInputElement, InputWithLabelProps>(
- ({ className, label, hint, info, error, ...inputProps }, ref) => {
+ ({ className, label, hint, info, action, error, ...inputProps }, ref) => {
const hasMessage = Boolean(error ?? hint);
const generatedId = useId();
// A caller's own id and description are kept; the message is added to them.
@@ -75,6 +88,7 @@ export const InputWithLabel = forwardRef<HTMLInputElement, InputWithLabelProps>(
.join(' ') || undefined;
return (
<WithLabel
+ action={action}
className={className}
error={error}
hint={hint}
diff --git a/apps/start/src/components/onboarding-left-panel.tsx b/apps/start/src/components/onboarding-left-panel.tsx
deleted file mode 100644
index 320a9ee07..000000000
--- a/apps/start/src/components/onboarding-left-panel.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-import Autoplay from 'embla-carousel-autoplay';
-import { QuoteIcon } from 'lucide-react';
-import {
- Carousel,
- CarouselContent,
- CarouselItem,
-} from '@/components/ui/carousel';
-
-const testimonials = [
- {
- key: 'thomas',
- bgImage: '/img-1.webp',
- quote:
- "OpenPanel is BY FAR the best open-source analytics I've ever seen. Better UX/UI, many more features, and incredible support from the founder.",
- author: 'Thomas Sanlis',
- site: 'uneed.best',
- },
- {
- key: 'julien',
- bgImage: '/img-2.webp',
- quote:
- 'After testing several product analytics tools, we chose OpenPanel and we are very satisfied. Profiles and Conversion Events are our favorite features.',
- author: 'Julien Hany',
- site: 'strackr.com',
- },
- {
- key: 'piotr',
- bgImage: '/img-3.webp',
- quote:
- 'The Overview tab is great — it has everything I need. The UI is beautiful, clean, modern, very pleasing to the eye.',
- author: 'Piotr Kulpinski',
- site: 'producthunt.com',
- },
- {
- key: 'selfhost',
- bgImage: '/img-4.webp',
- quote:
- "After paying a lot to PostHog for years, OpenPanel gives us the same — in many ways better — analytics while keeping full ownership of our data. We don't want to run any business without OpenPanel anymore.",
- author: 'Self-hosting user',
- site: undefined,
- },
-];
-
-function TestimonialSlide({
- bgImage,
- quote,
- author,
- site,
-}: {
- bgImage: string;
- quote: string;
- author: string;
- site?: string;
-}) {
- return (
- <div className="relative flex h-full select-none flex-col justify-end p-10">
- <img
- alt=""
- className="absolute inset-0 h-full w-full object-cover"
- src={bgImage}
- />
- <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-black/10" />
- <div className="relative z-10 flex flex-col gap-4">
- <QuoteIcon className="size-10 stroke-1 text-white/40" />
- <blockquote className="font-medium text-2xl text-white leading-relaxed">
- {quote}
- </blockquote>
- <figcaption className="text-sm text-white/60">
- — {author}
- {site && <span className="ml-1 text-white/40">· {site}</span>}
- </figcaption>
- </div>
- </div>
- );
-}
-
-export function OnboardingLeftPanel() {
- return (
- <div className="sticky top-0 h-screen overflow-hidden">
- <div className="mt-24 flex h-full items-center justify-center">
- <Carousel
- className="h-full w-full [&>div]:h-full [&>div]:min-h-full"
- opts={{ loop: true, align: 'center' }}
- plugins={[Autoplay({ delay: 6000, stopOnInteraction: false })]}
- >
- <CarouselContent className="h-full">
- {testimonials.map((t) => (
- <CarouselItem className="p-8 pt-0 pb-32" key={t.key}>
- <div className="h-full min-h-full overflow-hidden rounded-xl border border-border bg-card shadow-lg">
- <TestimonialSlide
- author={t.author}
- bgImage={t.bgImage}
- quote={t.quote}
- site={t.site}
- />
- </div>
- </CarouselItem>
- ))}
- </CarouselContent>
- </Carousel>
- </div>
- </div>
- );
-}
diff --git a/apps/start/src/components/onboarding/ai-install-prompt.ts b/apps/start/src/components/onboarding/ai-install-prompt.ts
new file mode 100644
index 000000000..ed2ede924
--- /dev/null
+++ b/apps/start/src/components/onboarding/ai-install-prompt.ts
@@ -0,0 +1,157 @@
+import type { Framework } from '@openpanel/sdk-info';
+import {
+ curlSnippet,
+ getInstallSnippets,
+ type SnippetContext,
+ scriptTagSnippet,
+ usesClientSecret,
+} from './install-snippets';
+
+const DOCS_INDEX_URL = 'https://openpanel.dev/llms.txt';
+const SDK_OVERVIEW_URL = 'https://openpanel.dev/docs/sdks';
+const TRACK_API_URL = 'https://openpanel.dev/docs/api/track';
+export const CURSOR_PROMPT_DEEPLINK =
+ 'cursor://anysphere.cursor-deeplink/prompt?text=';
+
+type ProjectType = 'website' | 'app' | 'backend';
+
+export interface AiPromptInput {
+ projectName: string;
+ projectTypes: ProjectType[];
+ /** Null means "let the agent detect the framework". */
+ framework: Framework | null;
+ context: SnippetContext;
+}
+
+const TYPE_LABELS: Record<ProjectType, string> = {
+ website: 'a website',
+ app: 'a mobile app',
+ backend: 'a backend service',
+};
+
+// What to install per platform when the agent has to pick itself. Kept to
+// the packages we publish so it cannot invent one.
+const PACKAGES_BY_TYPE: Record<ProjectType, string[]> = {
+ website: [
+ 'Next.js: @openpanel/nextjs (render <OpenPanelComponent clientId="…" /> in the root layout)',
+ 'Nuxt: @openpanel/nuxt (add the module and an `openpanel` block to nuxt.config)',
+ 'Astro: @openpanel/astro (render <OpenPanelComponent /> in the layout head)',
+ 'React, Vue, Svelte, Remix or any other browser app: @openpanel/web (one shared `new OpenPanel({ clientId })` instance)',
+ 'Plain HTML or no build step: the script tag at the end of this prompt',
+ ],
+ app: [
+ 'React Native / Expo: @openpanel/react-native plus expo-application and expo-constants',
+ 'iOS: Swift package https://github.com/Openpanel-dev/swift-sdk',
+ 'Android: dev.openpanel:openpanel',
+ ],
+ backend: [
+ 'Node or Bun: @openpanel/sdk; Express: @openpanel/express (middleware)',
+ 'Python: pip install openpanel; Ruby: gem openpanel-sdk; Rust: cargo add openpanel-sdk',
+ `Anything else: POST to the track API (${TRACK_API_URL})`,
+ ],
+};
+
+function describeTarget(input: AiPromptInput): string {
+ const types = input.projectTypes.map((type) => TYPE_LABELS[type]);
+ return types.length > 0 ? types.join(' and ') : 'an application';
+}
+
+function needsSecret(input: AiPromptInput): boolean {
+ if (input.framework) {
+ return usesClientSecret(input.framework);
+ }
+ return input.projectTypes.some((type) => type !== 'website');
+}
+
+function contextLines(input: AiPromptInput): string[] {
+ const lines = [
+ `- OpenPanel project: "${input.projectName}" (${describeTarget(input)})`,
+ `- Client ID: ${input.context.clientId} (public; fine to ship to a browser)`,
+ ];
+ if (needsSecret(input)) {
+ lines.push(
+ `- Client secret: ${input.context.clientSecret ?? 'ask me for it before you start'} (server and native code only; read it from an environment variable, never commit it or send it to a browser)`
+ );
+ }
+ if (input.context.apiUrl) {
+ lines.push(
+ `- API URL: ${input.context.apiUrl} (self-hosted instance; pass it as the \`apiUrl\` option)`
+ );
+ }
+ lines.push(
+ input.framework
+ ? `- Guide: ${input.framework.href} (every doc: ${DOCS_INDEX_URL})`
+ : `- Guides: ${SDK_OVERVIEW_URL} (every doc: ${DOCS_INDEX_URL})`
+ );
+ return lines;
+}
+
+function installSteps(input: AiPromptInput): string[] {
+ if (input.framework) {
+ const snippets = getInstallSnippets(input.framework, input.context);
+ if (snippets.length === 0) {
+ return [
+ `1. Install the ${input.framework.name} SDK as described in the guide above, using the package manager this repository already uses.`,
+ '2. Initialize it once, where the app starts, with the credentials above.',
+ ];
+ }
+ return snippets.map(
+ (snippet, index) =>
+ `${index + 1}. ${snippet.title}${index === 0 ? ' (use the package manager this repository already uses)' : ''}:\n${indent(snippet.code)}`
+ );
+ }
+ const packages = input.projectTypes.flatMap((type) => PACKAGES_BY_TYPE[type]);
+ return [
+ '1. Detect the framework from this repository and pick the matching OpenPanel package:',
+ ...packages.map((line) => ` - ${line}`),
+ '2. Install it with the package manager this repository already uses, then initialize it once, where the app starts, with the credentials above. Follow its guide for the exact code.',
+ ];
+}
+
+function verificationStep(input: AiPromptInput, number: number): string[] {
+ const lines = [
+ `${number}. Make one event reach OpenPanel: start the app and open a screen, or send a test request. The OpenPanel dashboard is open and shows the first event as soon as it arrives.`,
+ ];
+ if (needsSecret(input) && input.context.clientSecret) {
+ lines.push(
+ ' Test request:',
+ indent(curlSnippet(input.context, 'openpanel_test_event'))
+ );
+ }
+ return lines;
+}
+
+function indent(code: string): string {
+ return code
+ .split('\n')
+ .map((line) => ` ${line}`)
+ .join('\n');
+}
+
+function fallbackSnippet(input: AiPromptInput): string[] {
+ const includesWebsite = input.projectTypes.includes('website');
+ if (input.framework || !includesWebsite) {
+ return [];
+ }
+ return ['', 'Script tag for plain HTML:', scriptTagSnippet(input.context)];
+}
+
+export function buildAiInstallPrompt(input: AiPromptInput): string {
+ const steps = installSteps(input);
+ const nextNumber = input.framework
+ ? steps.length + 1
+ : steps.filter((line) => /^\d+\. /.test(line)).length + 1;
+ return [
+ 'Set up OpenPanel analytics in this repository.',
+ '',
+ 'Context',
+ ...contextLines(input),
+ '',
+ 'Steps',
+ ...steps,
+ `${nextNumber}. Keep automatic screen view tracking on. Do not add custom events and do not change unrelated files.${needsSecret(input) ? ' The snippet shows the secret inline for clarity; move it to an environment variable before committing.' : ''}`,
+ ...verificationStep(input, nextNumber + 1),
+ `${nextNumber + 2}. Reply with the files you changed and anything I still have to do (environment variables, restart).`,
+ ...fallbackSnippet(input),
+ ].join('\n');
+}
diff --git a/apps/start/src/components/onboarding/client-credentials.tsx b/apps/start/src/components/onboarding/client-credentials.tsx
new file mode 100644
index 000000000..c1d81188c
--- /dev/null
+++ b/apps/start/src/components/onboarding/client-credentials.tsx
@@ -0,0 +1,96 @@
+import { CopyIcon, DownloadIcon, KeyRoundIcon } from 'lucide-react';
+import CopyInput from '@/components/forms/copy-input';
+import { Button } from '@/components/ui/button';
+import { clipboard } from '@/utils/clipboard';
+import { trackFunnel } from '@/utils/funnel-tracking';
+
+interface Props {
+ clientId: string;
+ /** Only known in the browser session that created the client; stored hashed otherwise. */
+ clientSecret: string | null;
+ /** Token of the read-only MCP client created with the project; same one-time rule. */
+ mcpToken: string | null;
+ projectId: string;
+}
+
+/** What the SDKs need to send events; the MCP token rides along in the download. */
+export function ClientCredentials({
+ clientId,
+ clientSecret,
+ mcpToken,
+ projectId,
+}: Props) {
+ const isOneTimeView = Boolean(clientSecret);
+ const credentials = [
+ `CLIENT_ID=${clientId}`,
+ clientSecret && `CLIENT_SECRET=${clientSecret}`,
+ mcpToken && `MCP_TOKEN=${mcpToken}`,
+ ]
+ .filter(Boolean)
+ .join('\n');
+
+ const copied = (what: string) =>
+ trackFunnel('onboarding_credentials_copied', { projectId, what });
+
+ const download = () => {
+ copied('download');
+ const blob = new Blob([credentials], { type: 'text/plain' });
+ const url = URL.createObjectURL(blob);
+ const anchor = document.createElement('a');
+ anchor.href = url;
+ anchor.download = 'openpanel-credentials.txt';
+ anchor.click();
+ URL.revokeObjectURL(url);
+ };
+
+ return (
+ <section className="col gap-4 rounded-xl border p-5">
+ <div className="row items-center gap-2">
+ <KeyRoundIcon className="text-muted-foreground" size={16} />
+ <h2 className="font-semibold text-base">Your keys</h2>
+ </div>
+ <div className="grid gap-3 [&>*]:min-w-0">
+ <CopyInput
+ label="Client ID"
+ onCopy={() => copied('clientId')}
+ value={clientId}
+ />
+ {clientSecret && (
+ <CopyInput
+ label="Client secret"
+ onCopy={() => copied('clientSecret')}
+ value={clientSecret}
+ />
+ )}
+ </div>
+ <p className="text-muted-foreground text-sm">
+ {isOneTimeView
+ ? 'The secret is shown only once. Save it if you track from a server or an app.'
+ : 'Secrets are shown once, right after a project is created. Create a new client under Settings → Clients if you need another.'}
+ </p>
+ {isOneTimeView && (
+ <div className="row flex-wrap gap-2">
+ <Button
+ icon={CopyIcon}
+ onClick={() => {
+ copied('all');
+ clipboard(credentials);
+ }}
+ size="sm"
+ variant="outline"
+ >
+ Copy all
+ </Button>
+ <Button
+ icon={DownloadIcon}
+ onClick={download}
+ size="sm"
+ variant="outline"
+ >
+ Download
+ </Button>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/apps/start/src/components/onboarding/connect-web.tsx b/apps/start/src/components/onboarding/connect-web.tsx
deleted file mode 100644
index 4f6d4233d..000000000
--- a/apps/start/src/components/onboarding/connect-web.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import type { IPublicClient } from '@openpanel/core';
-import { frameworks } from '@openpanel/sdk-info';
-import { CopyIcon, PlugIcon } from 'lucide-react';
-import { Button } from '../ui/button';
-import Syntax from '@/components/syntax';
-import { useAppContext } from '@/hooks/use-app-context';
-import { pushModal } from '@/modals';
-import { clipboard } from '@/utils/clipboard';
-
-interface Props {
- client: IPublicClient | null;
-}
-
-const ConnectWeb = ({ client }: Props) => {
- const context = useAppContext();
- const code = `<script>
- window.op=window.op||function(){var n=[];return new Proxy(function(){arguments.length&&n.push([].slice.call(arguments))},{get:function(t,r){return"q"===r?n:function(){n.push([r].concat([].slice.call(arguments)))}} ,has:function(t,r){return"q"===r}}) }();
- window.op('init', {${context.isSelfHosted ? `\n\tapiUrl: '${context.apiUrl}',` : ''}
- clientId: '${client?.id ?? 'YOUR_CLIENT_ID'}',
- trackScreenViews: true,
- trackOutgoingLinks: true,
- trackAttributes: true,
- // sessionReplay: {
- // enabled: true,
- // },
- });
-</script>
-<script src="https://openpanel.dev/op1.js" defer async></script>`;
- return (
- <div className="col gap-4">
- <div className="col gap-2">
- <div className="row items-center justify-between gap-4">
- <div className="flex items-center gap-2 font-bold text-xl capitalize">
- <PlugIcon className="size-4" />
- Quick start
- </div>
- <div className="row gap-2">
- <Button
- icon={CopyIcon}
- onClick={() => clipboard(code, null)}
- variant="outline"
- >
- Copy
- </Button>
- </div>
- </div>
- <Syntax className="border" code={code} copyable={false} />
- </div>
- <div className="col gap-4">
- <p className="text-center text-muted-foreground text-sm">
- Or pick a framework below to get started.
- </p>
- <div className="grid gap-4 md:grid-cols-2">
- {frameworks.map((framework) => (
- <button
- className="flex items-center gap-4 rounded-md border p-2 text-left"
- key={framework.name}
- onClick={() =>
- pushModal('Instructions', {
- framework,
- client,
- })
- }
- type="button"
- >
- <div className="h-10 w-10 rounded-md bg-def-200 p-2">
- <framework.IconComponent className="h-full w-full" />
- </div>
- <div className="flex-1 font-semibold">{framework.name}</div>
- </button>
- ))}
- </div>
- <p className="text-center text-muted-foreground text-sm">
- Missing a framework?{' '}
- <a
- className="text-foreground underline"
- href="mailto:[email protected]"
- >
- Let us know!
- </a>
- </p>
- </div>
- </div>
- );
-};
-
-export default ConnectWeb;
diff --git a/apps/start/src/components/onboarding/first-event-status.tsx b/apps/start/src/components/onboarding/first-event-status.tsx
new file mode 100644
index 000000000..41773858a
--- /dev/null
+++ b/apps/start/src/components/onboarding/first-event-status.tsx
@@ -0,0 +1,132 @@
+import type { IServiceEvent } from '@openpanel/core';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { CheckIcon, PartyPopperIcon } from 'lucide-react';
+import { useEffect } from 'react';
+import { Ping } from '@/components/ping';
+import useWS from '@/hooks/use-ws';
+import { useTRPC } from '@/integrations/trpc/react';
+import { cn } from '@/utils/cn';
+import { timeAgo } from '@/utils/date';
+import { trackFunnel } from '@/utils/funnel-tracking';
+
+const FALLBACK_POLL_MS = 10_000;
+const SHOWN_EVENTS = 5;
+
+/** The project's latest events, refreshed live while the user installs the SDK. */
+export function useFirstEvents(projectId: string, secondsOnStep: () => number) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const { data } = useQuery(
+ trpc.event.events.queryOptions(
+ { projectId },
+ {
+ // The websocket below flips the status instantly; polling only covers
+ // a socket that cannot connect.
+ refetchInterval: FALLBACK_POLL_MS,
+ }
+ )
+ );
+ useWS(`/live/events/${projectId}`, () => {
+ queryClient.invalidateQueries(trpc.event.events.queryFilter({ projectId }));
+ });
+ const events = data?.data ?? [];
+ const isVerified = events.length > 0;
+
+ const firstEvent = events.at(-1);
+ useEffect(() => {
+ if (isVerified) {
+ trackFunnel('onboarding_first_event_verified', {
+ projectId,
+ secondsOnStep: secondsOnStep(),
+ eventCount: events.length,
+ firstEventName: firstEvent?.name ?? null,
+ sdk: firstEvent?.sdkName || null,
+ });
+ }
+ // Fires once, when the status flips; later refetches must not repeat it.
+ }, [isVerified, projectId]);
+
+ return { events, isVerified };
+}
+
+export function FirstEventStatus({
+ events,
+ className,
+ children,
+ help,
+}: {
+ events: IServiceEvent[];
+ className?: string;
+ /** Shown beside the headline, e.g. the "Open dashboard" button once connected. */
+ children?: React.ReactNode;
+ /** Shown under the waiting text, e.g. a way into troubleshooting. */
+ help?: React.ReactNode;
+}) {
+ const isVerified = events.length > 0;
+ return (
+ <section
+ aria-live="polite"
+ className={cn(
+ '@container col gap-4 rounded-xl p-5 transition-colors',
+ isVerified
+ ? 'bg-emerald-500/10 text-emerald-950 dark:text-emerald-50'
+ : 'bg-def-200 dark:bg-def-300',
+ className
+ )}
+ >
+ <div className="flex @md:flex-row flex-col @md:items-center gap-4">
+ <span
+ className={cn(
+ 'center-center size-10 shrink-0 rounded-full',
+ isVerified ? 'bg-emerald-500 text-white' : 'bg-background'
+ )}
+ >
+ {isVerified ? (
+ <PartyPopperIcon size={18} />
+ ) : (
+ <Ping className="size-2.5 bg-highlight" />
+ )}
+ </span>
+ <div className="col min-w-0 flex-1">
+ <div className="font-semibold text-base">
+ {isVerified
+ ? 'Connected! Events are coming in.'
+ : 'Listening for your first event'}
+ </div>
+ <p
+ className={cn(
+ 'text-sm',
+ isVerified
+ ? 'text-emerald-900/70 dark:text-emerald-100/70'
+ : 'text-muted-foreground'
+ )}
+ >
+ {isVerified
+ ? 'Your setup works. Open the dashboard whenever you are ready.'
+ : 'Install the snippet, open your site or app once, and this turns green by itself.'}
+ </p>
+ {!isVerified && help && <div className="mt-2">{help}</div>}
+ </div>
+ {children && <div className="@md:ml-auto shrink-0">{children}</div>}
+ </div>
+ {isVerified && (
+ <ul className="col gap-1 rounded-lg bg-background/60 p-3 text-sm">
+ {events.slice(0, SHOWN_EVENTS).map((event) => (
+ <li className="row items-center gap-2" key={event.id}>
+ <CheckIcon className="shrink-0 text-emerald-600" size={14} />
+ <span className="truncate font-medium">{event.name}</span>
+ <span className="ml-auto shrink-0 text-muted-foreground tabular-nums">
+ {timeAgo(event.createdAt, 'round')}
+ </span>
+ </li>
+ ))}
+ {events.length > SHOWN_EVENTS && (
+ <li className="text-muted-foreground">
+ and {events.length - SHOWN_EVENTS} more
+ </li>
+ )}
+ </ul>
+ )}
+ </section>
+ );
+}
diff --git a/apps/start/src/components/onboarding/framework-picker.tsx b/apps/start/src/components/onboarding/framework-picker.tsx
new file mode 100644
index 000000000..a4d3b3ef8
--- /dev/null
+++ b/apps/start/src/components/onboarding/framework-picker.tsx
@@ -0,0 +1,127 @@
+import { type Framework, frameworks } from '@openpanel/sdk-info';
+import { WandSparklesIcon } from 'lucide-react';
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { cn } from '@/utils/cn';
+
+type ProjectType = 'website' | 'app' | 'backend';
+
+interface Props {
+ projectTypes: ProjectType[];
+ value: Framework | null;
+ onChange: (framework: Framework | null) => void;
+ /** Offer a "detect it for me" option, selected when `value` is null. */
+ allowNone?: boolean;
+ /** Id of the visible label, so the trigger has an accessible name. */
+ labelId?: string;
+ className?: string;
+}
+
+const GENERIC_FRAMEWORK_KEY = 'rest';
+const DETECT_OPTION = 'auto';
+const PLATFORM_LABELS: Record<ProjectType, string> = {
+ website: 'websites',
+ app: 'apps',
+ backend: 'backends',
+};
+
+/**
+ * Frameworks matching the project's platforms come first; the rest sit in
+ * a second group. The HTTP API fits every platform, so it goes last among
+ * the suggestions and never becomes the default.
+ */
+export function frameworksFor(projectTypes: ProjectType[]) {
+ const matching =
+ projectTypes.length === 0
+ ? frameworks
+ : frameworks.filter((framework) =>
+ framework.type.some((type) => projectTypes.includes(type))
+ );
+ const suggested = [
+ ...matching.filter((framework) => framework.key !== GENERIC_FRAMEWORK_KEY),
+ ...matching.filter((framework) => framework.key === GENERIC_FRAMEWORK_KEY),
+ ];
+ const others = frameworks.filter(
+ (framework) => !suggested.includes(framework)
+ );
+ return { suggested, others };
+}
+
+function suggestedLabel(projectTypes: ProjectType[]) {
+ if (projectTypes.length === 0) {
+ return 'Frameworks';
+ }
+ return `For ${projectTypes.map((type) => PLATFORM_LABELS[type]).join(' and ')}`;
+}
+
+export function FrameworkPicker({
+ projectTypes,
+ value,
+ onChange,
+ allowNone,
+ labelId,
+ className,
+}: Props) {
+ const { suggested, others } = frameworksFor(projectTypes);
+ const selected = value?.key ?? (allowNone ? DETECT_OPTION : undefined);
+
+ const select = (key: string) => {
+ if (key === DETECT_OPTION) {
+ onChange(null);
+ return;
+ }
+ const framework = frameworks.find((candidate) => candidate.key === key);
+ if (framework) {
+ onChange(framework);
+ }
+ };
+
+ return (
+ <Select onValueChange={select} value={selected}>
+ <SelectTrigger
+ aria-labelledby={labelId}
+ className={cn('w-full sm:w-64', className)}
+ >
+ <SelectValue placeholder="Pick a framework" />
+ </SelectTrigger>
+ <SelectContent>
+ {allowNone && (
+ <SelectItem value={DETECT_OPTION}>
+ <WandSparklesIcon className="size-4 shrink-0" />
+ Detect it for me
+ </SelectItem>
+ )}
+ <SelectGroup>
+ <SelectLabel>{suggestedLabel(projectTypes)}</SelectLabel>
+ {suggested.map((framework) => (
+ <FrameworkItem framework={framework} key={framework.key} />
+ ))}
+ </SelectGroup>
+ {others.length > 0 && (
+ <SelectGroup>
+ <SelectLabel>Other frameworks</SelectLabel>
+ {others.map((framework) => (
+ <FrameworkItem framework={framework} key={framework.key} />
+ ))}
+ </SelectGroup>
+ )}
+ </SelectContent>
+ </Select>
+ );
+}
+
+function FrameworkItem({ framework }: { framework: Framework }) {
+ return (
+ <SelectItem value={framework.key}>
+ <framework.IconComponent className="size-4 shrink-0" />
+ {framework.name}
+ </SelectItem>
+ );
+}
diff --git a/apps/start/src/components/onboarding/install-guide.tsx b/apps/start/src/components/onboarding/install-guide.tsx
new file mode 100644
index 000000000..67837e684
--- /dev/null
+++ b/apps/start/src/components/onboarding/install-guide.tsx
@@ -0,0 +1,105 @@
+import { useState } from 'react';
+import { InstallManual } from './install-manual';
+import type { SnippetContext } from './install-snippets';
+import { InstallWithAi } from './install-with-ai';
+import { cn } from '@/utils/cn';
+import { trackFunnel } from '@/utils/funnel-tracking';
+
+type InstallMethod = 'ai' | 'manual';
+type ProjectType = 'website' | 'app' | 'backend';
+
+const METHODS: { key: InstallMethod; label: string; hint: string }[] = [
+ {
+ key: 'ai',
+ label: 'Install with AI',
+ hint: 'Paste one prompt into your coding assistant',
+ },
+ {
+ key: 'manual',
+ label: 'Manual setup',
+ hint: 'Copy the snippet for your framework',
+ },
+];
+
+interface Props {
+ projectId: string;
+ projectName: string;
+ projectTypes: ProjectType[];
+ context: SnippetContext;
+ defaultMethod?: InstallMethod;
+}
+
+/** The two ways to add the SDK, as a segmented switch. */
+export function InstallGuide({
+ projectId,
+ projectName,
+ projectTypes,
+ context,
+ defaultMethod = 'ai',
+}: Props) {
+ const [method, setMethod] = useState<InstallMethod>(defaultMethod);
+
+ const select = (next: InstallMethod) => {
+ trackFunnel('onboarding_install_method_selected', {
+ projectId,
+ method: next,
+ });
+ setMethod(next);
+ };
+
+ return (
+ <div className="col gap-6">
+ <div
+ aria-label="Installation method"
+ className="grid grid-cols-2 gap-1 rounded-xl bg-def-200 p-1 dark:bg-def-300"
+ role="tablist"
+ >
+ {METHODS.map((item) => {
+ const active = item.key === method;
+ return (
+ <button
+ aria-controls={`install-${item.key}`}
+ aria-selected={active}
+ className={cn(
+ 'col items-start gap-0.5 rounded-lg px-4 py-2.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
+ active
+ ? 'bg-background shadow-sm'
+ : 'text-muted-foreground hover:text-foreground'
+ )}
+ id={`install-tab-${item.key}`}
+ key={item.key}
+ onClick={() => select(item.key)}
+ role="tab"
+ type="button"
+ >
+ <span className="font-medium">{item.label}</span>
+ <span className="hidden text-muted-foreground text-xs sm:block">
+ {item.hint}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ <div
+ aria-labelledby={`install-tab-${method}`}
+ id={`install-${method}`}
+ role="tabpanel"
+ >
+ {method === 'ai' ? (
+ <InstallWithAi
+ context={context}
+ projectId={projectId}
+ projectName={projectName}
+ projectTypes={projectTypes}
+ />
+ ) : (
+ <InstallManual
+ context={context}
+ projectId={projectId}
+ projectTypes={projectTypes}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/start/src/components/onboarding/install-manual.tsx b/apps/start/src/components/onboarding/install-manual.tsx
new file mode 100644
index 000000000..f204a84c2
--- /dev/null
+++ b/apps/start/src/components/onboarding/install-manual.tsx
@@ -0,0 +1,109 @@
+import type { Framework } from '@openpanel/sdk-info';
+import { ExternalLinkIcon } from 'lucide-react';
+import { useId, useState } from 'react';
+import { FrameworkPicker, frameworksFor } from './framework-picker';
+import {
+ getInstallSnippets,
+ type SnippetContext,
+ usesClientSecret,
+} from './install-snippets';
+import Syntax from '@/components/syntax';
+import { trackFunnel } from '@/utils/funnel-tracking';
+
+type ProjectType = 'website' | 'app' | 'backend';
+
+interface Props {
+ projectId: string;
+ projectTypes: ProjectType[];
+ context: SnippetContext;
+}
+
+export function InstallManual({ projectId, projectTypes, context }: Props) {
+ const [framework, setFramework] = useState<Framework>(
+ () => frameworksFor(projectTypes).suggested[0]!
+ );
+ const frameworkLabelId = useId();
+ const snippets = getInstallSnippets(framework, context);
+ const secretMissing = usesClientSecret(framework) && !context.clientSecret;
+
+ const select = (next: Framework | null) => {
+ if (!next) {
+ return;
+ }
+ trackFunnel('onboarding_framework_selected', {
+ projectId,
+ framework: next.key,
+ });
+ setFramework(next);
+ };
+
+ return (
+ <div className="col gap-6">
+ <div className="row flex-wrap items-center gap-3">
+ <span className="font-medium" id={frameworkLabelId}>
+ Framework
+ </span>
+ <FrameworkPicker
+ labelId={frameworkLabelId}
+ onChange={select}
+ projectTypes={projectTypes}
+ value={framework}
+ />
+ </div>
+
+ <div className="col gap-5">
+ {snippets.map((snippet, index) => (
+ <div className="col gap-2" key={snippet.title}>
+ <div className="row items-center gap-2 font-medium">
+ <span className="center-center size-5 rounded-full bg-def-200 text-xs tabular-nums dark:bg-def-300">
+ {index + 1}
+ </span>
+ {snippet.title}
+ </div>
+ <Syntax
+ className="border"
+ code={snippet.code}
+ language={snippet.language}
+ onCopy={() =>
+ trackFunnel('onboarding_snippet_copied', {
+ projectId,
+ framework: framework.key,
+ step: index + 1,
+ })
+ }
+ wrapLines={snippet.language === 'markdown'}
+ />
+ </div>
+ ))}
+ {snippets.length === 0 && (
+ <p className="text-muted-foreground">
+ {framework.name} is a community SDK. Its guide covers installation
+ and usage.
+ </p>
+ )}
+ {secretMissing && (
+ <p className="rounded-lg bg-def-200 p-3 text-muted-foreground text-sm dark:bg-def-300">
+ The client secret is only shown once, right after the client is
+ created. Replace YOUR_CLIENT_SECRET with the one you saved, or
+ create a new client under Settings → Clients.
+ </p>
+ )}
+ <a
+ className="row items-center gap-1.5 self-start text-sm underline hover:text-foreground"
+ href={framework.href}
+ onClick={() =>
+ trackFunnel('onboarding_framework_guide_clicked', {
+ projectId,
+ framework: framework.key,
+ })
+ }
+ rel="noreferrer"
+ target="_blank"
+ >
+ Full {framework.name} guide
+ <ExternalLinkIcon size={14} />
+ </a>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/start/src/components/onboarding/install-snippets.ts b/apps/start/src/components/onboarding/install-snippets.ts
new file mode 100644
index 000000000..5fe5d38ad
--- /dev/null
+++ b/apps/start/src/components/onboarding/install-snippets.ts
@@ -0,0 +1,328 @@
+import type { Framework } from '@openpanel/sdk-info';
+
+export interface SnippetContext {
+ clientId: string;
+ /** Known only in the browser session that created the client. */
+ clientSecret: string | null;
+ /** Set on self-hosted installs so snippets point at the right API. */
+ apiUrl: string | null;
+}
+
+export interface InstallSnippet {
+ title: string;
+ code: string;
+ language: 'bash' | 'typescript' | 'json' | 'markdown';
+}
+
+const SECRET_PLACEHOLDER = 'YOUR_CLIENT_SECRET';
+export const SCRIPT_URL = 'https://openpanel.dev/op1.js';
+
+const secretOf = (context: SnippetContext) =>
+ context.clientSecret ?? SECRET_PLACEHOLDER;
+
+const apiUrlLine = (context: SnippetContext, indent: string) =>
+ context.apiUrl ? `\n${indent}apiUrl: '${context.apiUrl}',` : '';
+
+export function scriptTagSnippet(context: SnippetContext): string {
+ return `<script>
+ window.op=window.op||function(){var n=[];return new Proxy(function(){arguments.length&&n.push([].slice.call(arguments))},{get:function(t,r){return"q"===r?n:function(){n.push([r].concat([].slice.call(arguments)))}} ,has:function(t,r){return"q"===r}}) }();
+ window.op('init', {${apiUrlLine(context, ' ')}
+ clientId: '${context.clientId}',
+ trackScreenViews: true,
+ trackOutgoingLinks: true,
+ trackAttributes: true,
+ });
+</script>
+<script src="${SCRIPT_URL}" defer async></script>`;
+}
+
+function webSdkSnippets(context: SnippetContext): InstallSnippet[] {
+ return [
+ { title: 'Install', code: 'npm install @openpanel/web', language: 'bash' },
+ {
+ title: 'Create one shared instance',
+ language: 'typescript',
+ code: `// src/openpanel.ts
+import { OpenPanel } from '@openpanel/web';
+
+export const op = new OpenPanel({${apiUrlLine(context, ' ')}
+ clientId: '${context.clientId}',
+ trackScreenViews: true,
+ trackOutgoingLinks: true,
+ trackAttributes: true,
+});`,
+ },
+ ];
+}
+
+function serverSdkSnippets(context: SnippetContext): InstallSnippet[] {
+ return [
+ { title: 'Install', code: 'npm install @openpanel/sdk', language: 'bash' },
+ {
+ title: 'Initialize',
+ language: 'typescript',
+ code: `import { OpenPanel } from '@openpanel/sdk';
+
+const op = new OpenPanel({${apiUrlLine(context, ' ')}
+ clientId: '${context.clientId}',
+ clientSecret: '${secretOf(context)}',
+});
+
+op.track('my_event', { foo: 'bar' });`,
+ },
+ ];
+}
+
+const trackUrl = (context: SnippetContext) =>
+ `${context.apiUrl ?? 'https://api.openpanel.dev'}/track`;
+
+export function curlSnippet(context: SnippetContext, eventName: string) {
+ return `curl -X POST ${trackUrl(context)} \\
+ -H "Content-Type: application/json" \\
+ -H "openpanel-client-id: ${context.clientId}" \\
+ -H "openpanel-client-secret: ${secretOf(context)}" \\
+ -d '{"type":"track","payload":{"name":"${eventName}","properties":{"source":"curl"}}}'`;
+}
+
+const SNIPPETS: Record<string, (context: SnippetContext) => InstallSnippet[]> =
+ {
+ html: (context) => [
+ {
+ title: 'Paste before </head> on every page',
+ code: scriptTagSnippet(context),
+ language: 'markdown',
+ },
+ ],
+ react: webSdkSnippets,
+ vue: webSdkSnippets,
+ remix: webSdkSnippets,
+ nextjs: (context) => [
+ {
+ title: 'Install',
+ code: 'npm install @openpanel/nextjs',
+ language: 'bash',
+ },
+ {
+ title: 'Add to your root layout',
+ language: 'typescript',
+ code: `// app/layout.tsx
+import { OpenPanelComponent } from '@openpanel/nextjs';
+
+export default function RootLayout({ children }) {
+ return (
+ <html lang="en">
+ <body>
+ <OpenPanelComponent${context.apiUrl ? `\n apiUrl="${context.apiUrl}"` : ''}
+ clientId="${context.clientId}"
+ trackScreenViews={true}
+ trackOutgoingLinks={true}
+ trackAttributes={true}
+ />
+ {children}
+ </body>
+ </html>
+ );
+}`,
+ },
+ ],
+ nuxt: (context) => [
+ {
+ title: 'Install',
+ code: 'npm install @openpanel/nuxt',
+ language: 'bash',
+ },
+ {
+ title: 'Register the module',
+ language: 'typescript',
+ code: `// nuxt.config.ts
+export default defineNuxtConfig({
+ modules: ['@openpanel/nuxt'],
+ openpanel: {${apiUrlLine(context, ' ')}
+ clientId: '${context.clientId}',
+ trackScreenViews: true,
+ trackOutgoingLinks: true,
+ trackAttributes: true,
+ },
+});`,
+ },
+ ],
+ astro: (context) => [
+ {
+ title: 'Install',
+ code: 'npm install @openpanel/astro',
+ language: 'bash',
+ },
+ {
+ title: 'Add to your layout <head>',
+ language: 'markdown',
+ code: `---
+import { OpenPanelComponent } from '@openpanel/astro';
+---
+<html>
+ <head>
+ <OpenPanelComponent${context.apiUrl ? `\n apiUrl="${context.apiUrl}"` : ''}
+ clientId="${context.clientId}"
+ trackScreenViews={true}
+ trackOutgoingLinks={true}
+ trackAttributes={true}
+ />
+ </head>
+ <body>
+ <slot />
+ </body>
+</html>`,
+ },
+ ],
+ rest: (context) => [
+ {
+ title: 'Send an event over HTTP',
+ code: curlSnippet(context, 'my_event'),
+ language: 'bash',
+ },
+ ],
+ 'react-native': (context) => [
+ {
+ title: 'Install',
+ code: `npm install @openpanel/react-native
+npx expo install expo-application expo-constants`,
+ language: 'bash',
+ },
+ {
+ title: 'Initialize',
+ language: 'typescript',
+ code: `import { OpenPanel } from '@openpanel/react-native';
+
+export const op = new OpenPanel({${apiUrlLine(context, ' ')}
+ clientId: '${context.clientId}',
+ clientSecret: '${secretOf(context)}',
+});`,
+ },
+ ],
+ node: serverSdkSnippets,
+ express: (context) => [
+ {
+ title: 'Install',
+ code: 'npm install @openpanel/express',
+ language: 'bash',
+ },
+ {
+ title: 'Add the middleware',
+ language: 'typescript',
+ code: `import express from 'express';
+import createOpenpanelMiddleware from '@openpanel/express';
+
+const app = express();
+
+app.use(
+ createOpenpanelMiddleware({${apiUrlLine(context, ' ')}
+ clientId: '${context.clientId}',
+ clientSecret: '${secretOf(context)}',
+ })
+);
+
+app.post('/sign-up', (req, res) => {
+ req.op.track('sign_up', { email: req.body.email });
+ res.send('ok');
+});`,
+ },
+ ],
+ python: (context) => [
+ { title: 'Install', code: 'pip install openpanel', language: 'bash' },
+ {
+ title: 'Initialize',
+ language: 'typescript',
+ code: `from openpanel import OpenPanel
+
+op = OpenPanel(${context.apiUrl ? `\n api_url="${context.apiUrl}",` : ''}
+ client_id="${context.clientId}",
+ client_secret="${secretOf(context)}",
+)
+
+op.track("my_event", {"foo": "bar"})`,
+ },
+ ],
+ rust: (context) => [
+ { title: 'Install', code: 'cargo add openpanel-sdk', language: 'bash' },
+ {
+ title: 'Environment variables',
+ language: 'bash',
+ code: `OPENPANEL_TRACK_URL=${trackUrl(context)}
+OPENPANEL_CLIENT_ID=${context.clientId}
+OPENPANEL_CLIENT_SECRET=${secretOf(context)}`,
+ },
+ {
+ title: 'Initialize',
+ language: 'typescript',
+ code: `use openpanel_sdk::sdk::Tracker;
+
+let tracker = Tracker::try_new_from_env()?.with_default_headers()?;`,
+ },
+ ],
+ ruby: (context) => [
+ { title: 'Install', code: 'bundle add openpanel-sdk', language: 'bash' },
+ {
+ title: 'Environment variables',
+ language: 'bash',
+ code: `OPENPANEL_TRACK_URL=${trackUrl(context)}
+OPENPANEL_CLIENT_ID=${context.clientId}
+OPENPANEL_CLIENT_SECRET=${secretOf(context)}`,
+ },
+ {
+ title: 'Initialize',
+ language: 'typescript',
+ code: `require 'openpanel-sdk'
+
+tracker = OpenPanel::SDK::Tracker.new
+tracker.track('my_event', { foo: 'bar' })`,
+ },
+ ],
+ ios: (context) => [
+ {
+ title: 'Add the Swift package',
+ code: 'https://github.com/Openpanel-dev/swift-sdk',
+ language: 'bash',
+ },
+ {
+ title: 'Initialize',
+ language: 'typescript',
+ code: `import OpenPanel
+
+OpenPanel.initialize(options: .init(${context.apiUrl ? `\n apiUrl: "${context.apiUrl}",` : ''}
+ clientId: "${context.clientId}",
+ clientSecret: "${secretOf(context)}"
+))`,
+ },
+ ],
+ android: (context) => [
+ {
+ title: 'Add the dependency',
+ code: `dependencies {
+ implementation 'dev.openpanel:openpanel:0.0.1'
+}`,
+ language: 'bash',
+ },
+ {
+ title: 'Initialize',
+ language: 'typescript',
+ code: `val op = OpenPanel.create(
+ context,
+ OpenPanel.Options(${context.apiUrl ? `\n apiUrl = "${context.apiUrl}",` : ''}
+ clientId = "${context.clientId}",
+ clientSecret = "${secretOf(context)}"
+ )
+)`,
+ },
+ ],
+ };
+
+/** Frameworks without an inline snippet (community SDKs) only link to their guide. */
+export function getInstallSnippets(
+ framework: Framework,
+ context: SnippetContext
+): InstallSnippet[] {
+ return SNIPPETS[framework.key]?.(context) ?? [];
+}
+
+export function usesClientSecret(framework: Framework): boolean {
+ return !framework.type.includes('website') || framework.key === 'rest';
+}
diff --git a/apps/start/src/components/onboarding/install-troubleshooting.tsx b/apps/start/src/components/onboarding/install-troubleshooting.tsx
new file mode 100644
index 000000000..692e2b8c1
--- /dev/null
+++ b/apps/start/src/components/onboarding/install-troubleshooting.tsx
@@ -0,0 +1,232 @@
+import type { IServiceProjectWithClients } from '@openpanel/core';
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { Link } from '@tanstack/react-router';
+import { SparklesIcon } from 'lucide-react';
+import { toast } from 'sonner';
+import { curlSnippet, type SnippetContext } from './install-snippets';
+import CopyInput from '@/components/forms/copy-input';
+import { WithLabel } from '@/components/forms/input-with-label';
+import TagInput from '@/components/forms/tag-input';
+import Syntax from '@/components/syntax';
+import { buttonVariants } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogPortal,
+ DialogTitle,
+ DialogTrigger,
+} from '@/components/ui/dialog';
+import { handleError, useTRPC } from '@/integrations/trpc/react';
+import { cn } from '@/utils/cn';
+import { trackFunnel } from '@/utils/funnel-tracking';
+
+const TEST_EVENT_NAME = 'openpanel_test_event';
+
+// The assistant can fetch the site, read the snippet and compare it with the
+// project's client and allowed origins, so it finds most causes by itself.
+function diagnoseQuestion(project: IServiceProjectWithClients): string {
+ if (project.domain) {
+ return `No events have arrived for ${project.domain} after installing OpenPanel. Diagnose the install.`;
+ }
+ const kinds = project.types.length > 0 ? project.types.join(' and ') : 'app';
+ return `No events have arrived from my ${kinds} project after installing OpenPanel. Check what has reached the project and what could block events.`;
+}
+
+function normalizeOrigins(values: string[]) {
+ return values
+ .map((value) => value.trim())
+ .filter(Boolean)
+ .map((value) =>
+ value === '*' || /^https?:\/\//.test(value) ? value : `https://${value}`
+ );
+}
+
+/** A quiet link under the listener that opens the troubleshooting checks. */
+export function InstallTroubleshootingDialog({
+ project,
+ context,
+}: {
+ project: IServiceProjectWithClients;
+ context: SnippetContext;
+}) {
+ return (
+ <Dialog
+ onOpenChange={(open) =>
+ trackFunnel('onboarding_troubleshooting_toggled', {
+ projectId: project.id,
+ open,
+ })
+ }
+ >
+ <DialogTrigger className="text-muted-foreground text-sm underline-offset-4 hover:text-foreground hover:underline">
+ I'm not receiving events
+ </DialogTrigger>
+ <DialogPortal>
+ <DialogContent className="sm:max-w-2xl" showCloseButton>
+ <DialogHeader>
+ <DialogTitle>Not seeing events?</DialogTitle>
+ <DialogDescription>
+ The checks that solve most installs, in the order they usually
+ apply.
+ </DialogDescription>
+ </DialogHeader>
+ <InstallTroubleshooting context={context} project={project} />
+ </DialogContent>
+ </DialogPortal>
+ </Dialog>
+ );
+}
+
+/** The checks that resolve most "no events" reports, in the order they usually apply. */
+export function InstallTroubleshooting({
+ project,
+ context,
+}: {
+ project: IServiceProjectWithClients;
+ context: SnippetContext;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const updateProject = useMutation(
+ trpc.project.update.mutationOptions({
+ onError: handleError,
+ onSuccess: () => {
+ queryClient.invalidateQueries(
+ trpc.project.getProjectWithClients.queryFilter({
+ projectId: project.id,
+ })
+ );
+ toast.success('Allowed domains updated');
+ },
+ })
+ );
+ const isWebsite = project.types.includes('website');
+
+ return (
+ <ol className="col gap-6">
+ <li className="row flex-wrap items-center justify-between gap-3 rounded-xl bg-def-200 p-4 dark:bg-def-300">
+ <div className="col gap-0.5">
+ <div className="font-medium">Let the assistant find it</div>
+ <p className="text-muted-foreground text-sm">
+ It fetches your site, reads the snippet and checks it against this
+ project's keys and allowed domains.
+ </p>
+ </div>
+ <Link
+ className={cn(buttonVariants({ size: 'default' }))}
+ onClick={() =>
+ trackFunnel('onboarding_assistant_opened', {
+ projectId: project.id,
+ hasDomain: Boolean(project.domain),
+ })
+ }
+ params={{
+ organizationId: project.organizationId,
+ projectId: project.id,
+ }}
+ search={{
+ q: diagnoseQuestion(project),
+ hint: { page: 'onboarding' },
+ }}
+ to="/$organizationId/$projectId/chat"
+ >
+ <SparklesIcon className="mr-2 size-4" />
+ Diagnose with the assistant
+ </Link>
+ </li>
+ <li className="col gap-2">
+ <div className="font-medium">
+ 1. Did the page or app actually load with the snippet?
+ </div>
+ <p className="text-muted-foreground">
+ Events are sent when a screen is viewed. Deploy or run the code, then
+ open it once and reload this page. Ad blockers can also stop the
+ request; try an incognito window without extensions.
+ </p>
+ </li>
+ <li className="col gap-3">
+ <div className="font-medium">
+ 2. Is the client ID the one for this project?
+ </div>
+ <CopyInput label="Client ID" value={context.clientId} />
+ </li>
+ {isWebsite && (
+ <li className="col gap-3">
+ <div className="font-medium">3. Is your domain allowed?</div>
+ <p className="text-muted-foreground">
+ Browser events are accepted only from these origins. Add every
+ domain your site runs on, including localhost while testing.
+ </p>
+ <WithLabel label="Allowed domains">
+ <TagInput
+ onChange={(values) => {
+ const cors = normalizeOrigins(values);
+ trackFunnel('onboarding_allowed_domains_updated', {
+ projectId: project.id,
+ count: cors.length,
+ wildcard: cors.includes('*'),
+ });
+ updateProject.mutate({ id: project.id, cors });
+ }}
+ placeholder="Add a domain and press Enter"
+ renderTag={(tag) => (tag === '*' ? 'Any domain' : tag)}
+ value={project.cors ?? []}
+ />
+ </WithLabel>
+ </li>
+ )}
+ <li className="col gap-3">
+ <div className="font-medium">
+ {isWebsite ? '4.' : '3.'} Send a test event from your terminal
+ </div>
+ <p className="text-muted-foreground">
+ This bypasses your code entirely. If it shows up above, the project is
+ fine and the problem is in the integration.
+ </p>
+ <Syntax
+ code={curlSnippet(context, TEST_EVENT_NAME)}
+ language="bash"
+ onCopy={() =>
+ trackFunnel('onboarding_test_curl_copied', {
+ projectId: project.id,
+ })
+ }
+ wrapLines
+ />
+ </li>
+ <li className="text-muted-foreground">
+ Still stuck? Write to{' '}
+ <a
+ className="underline"
+ href="mailto:[email protected]"
+ onClick={() =>
+ trackFunnel('onboarding_support_link_clicked', {
+ projectId: project.id,
+ target: 'email',
+ })
+ }
+ >
+ </a>{' '}
+ or join the{' '}
+ <a
+ className="underline"
+ href="https://go.openpanel.dev/discord"
+ onClick={() =>
+ trackFunnel('onboarding_support_link_clicked', {
+ projectId: project.id,
+ target: 'discord',
+ })
+ }
+ rel="noreferrer"
+ target="_blank"
+ >
+ Discord
+ </a>
+ . We answer quickly.
+ </li>
+ </ol>
+ );
+}
diff --git a/apps/start/src/components/onboarding/install-with-ai.tsx b/apps/start/src/components/onboarding/install-with-ai.tsx
new file mode 100644
index 000000000..120b6882f
--- /dev/null
+++ b/apps/start/src/components/onboarding/install-with-ai.tsx
@@ -0,0 +1,96 @@
+import type { Framework } from '@openpanel/sdk-info';
+import { CopyIcon, SparklesIcon } from 'lucide-react';
+import { useId, useMemo, useState } from 'react';
+import {
+ buildAiInstallPrompt,
+ CURSOR_PROMPT_DEEPLINK,
+} from './ai-install-prompt';
+import { FrameworkPicker } from './framework-picker';
+import type { SnippetContext } from './install-snippets';
+import { Button, buttonVariants } from '@/components/ui/button';
+import { clipboard } from '@/utils/clipboard';
+import { trackFunnel } from '@/utils/funnel-tracking';
+
+interface Props {
+ projectId: string;
+ projectName: string;
+ projectTypes: ('website' | 'app' | 'backend')[];
+ context: SnippetContext;
+}
+
+export function InstallWithAi({
+ projectId,
+ projectName,
+ projectTypes,
+ context,
+}: Props) {
+ const [framework, setFramework] = useState<Framework | null>(null);
+ const frameworkLabelId = useId();
+ const prompt = useMemo(
+ () =>
+ buildAiInstallPrompt({ projectName, projectTypes, framework, context }),
+ [projectName, projectTypes, framework, context]
+ );
+
+ const copyPrompt = () => {
+ trackFunnel('onboarding_ai_prompt_copied', {
+ projectId,
+ framework: framework?.key ?? 'auto',
+ promptLength: prompt.length,
+ });
+ clipboard(prompt, 'Paste it into your coding assistant');
+ };
+
+ return (
+ <div className="col gap-6">
+ <div className="row flex-wrap items-center gap-3">
+ <span className="font-medium" id={frameworkLabelId}>
+ Framework{' '}
+ <span className="font-normal text-muted-foreground">(optional)</span>
+ </span>
+ <FrameworkPicker
+ allowNone
+ labelId={frameworkLabelId}
+ onChange={(next) => {
+ trackFunnel('onboarding_ai_framework_selected', {
+ projectId,
+ framework: next?.key ?? 'auto',
+ });
+ setFramework(next);
+ }}
+ projectTypes={projectTypes}
+ value={framework}
+ />
+ </div>
+
+ <div className="col gap-3">
+ <pre className="scrollbar-thin max-h-56 overflow-auto whitespace-pre-wrap break-words rounded-xl bg-def-200 p-4 font-mono text-xs leading-relaxed dark:bg-def-300">
+ {prompt}
+ </pre>
+ <div className="row flex-wrap gap-2">
+ <Button icon={CopyIcon} onClick={copyPrompt} size="xl">
+ Copy prompt
+ </Button>
+ <a
+ className={buttonVariants({ variant: 'outline', size: 'xl' })}
+ href={`${CURSOR_PROMPT_DEEPLINK}${encodeURIComponent(prompt)}`}
+ onClick={() =>
+ trackFunnel('onboarding_ai_prompt_opened_in_cursor', {
+ projectId,
+ framework: framework?.key ?? 'auto',
+ })
+ }
+ >
+ <SparklesIcon className="mr-2 size-4" />
+ Open in Cursor
+ </a>
+ </div>
+ <p className="text-muted-foreground text-sm">
+ Works with Claude Code, Cursor, Copilot, Windsurf or any agent that
+ can edit your code. It installs the SDK, adds your client ID and sends
+ a first event. This page lights up when it arrives.
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/start/src/components/onboarding/mcp-connect.tsx b/apps/start/src/components/onboarding/mcp-connect.tsx
new file mode 100644
index 000000000..605a396ea
--- /dev/null
+++ b/apps/start/src/components/onboarding/mcp-connect.tsx
@@ -0,0 +1,260 @@
+import { Link } from '@tanstack/react-router';
+import { BotIcon, CopyIcon, ExternalLinkIcon, ZapIcon } from 'lucide-react';
+import CopyInput from '@/components/forms/copy-input';
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from '@/components/ui/accordion';
+import { Button, buttonVariants } from '@/components/ui/button';
+import { clipboard } from '@/utils/clipboard';
+import { cn } from '@/utils/cn';
+import { trackFunnel } from '@/utils/funnel-tracking';
+
+const SERVER_NAME = 'openpanel';
+const PANEL = 'mcp';
+
+interface Connection {
+ endpoint: string;
+ token: string;
+}
+
+// Install links are documented by Cursor (base64 JSON config) and VS Code
+// (percent-encoded JSON). Claude Code takes one command. claude.ai and
+// ChatGPT have no deep link: the user pastes the URL as a custom connector,
+// with the token in the query string because neither can send headers.
+type Host =
+ | {
+ key: string;
+ label: string;
+ kind: 'install';
+ href: (connection: Connection) => string;
+ }
+ | {
+ key: string;
+ label: string;
+ kind: 'command';
+ command: (connection: Connection) => string;
+ }
+ | {
+ key: string;
+ label: string;
+ kind: 'paste';
+ settingsUrl: string;
+ hint: string;
+ };
+
+const HOSTS: Host[] = [
+ {
+ key: 'cursor',
+ label: 'Cursor',
+ kind: 'install',
+ href: ({ endpoint, token }) => {
+ const config = btoa(
+ JSON.stringify({
+ url: endpoint,
+ headers: { Authorization: `Bearer ${token}` },
+ })
+ );
+ return `cursor://anysphere.cursor-deeplink/mcp/install?name=${SERVER_NAME}&config=${encodeURIComponent(config)}`;
+ },
+ },
+ {
+ key: 'vscode',
+ label: 'VS Code',
+ kind: 'install',
+ href: ({ endpoint, token }) =>
+ `vscode:mcp/install?${encodeURIComponent(
+ JSON.stringify({
+ name: SERVER_NAME,
+ type: 'http',
+ url: endpoint,
+ headers: { Authorization: `Bearer ${token}` },
+ })
+ )}`,
+ },
+ {
+ key: 'claude-code',
+ label: 'Claude Code',
+ kind: 'command',
+ command: ({ endpoint, token }) =>
+ `claude mcp add --transport http ${SERVER_NAME} ${endpoint} --header "Authorization: Bearer ${token}"`,
+ },
+ {
+ key: 'claude',
+ label: 'Claude',
+ kind: 'paste',
+ settingsUrl: 'https://claude.ai/settings/connectors',
+ hint: 'Settings → Connectors → Add custom connector',
+ },
+ {
+ key: 'chatgpt',
+ label: 'ChatGPT',
+ kind: 'paste',
+ settingsUrl: 'https://chatgpt.com/#settings/Connectors',
+ hint: 'Settings → Connectors → Create (Developer mode)',
+ },
+];
+
+const KIND_CAPTIONS: Record<Host['kind'], string> = {
+ install: 'One click',
+ command: 'One command',
+ paste: 'Paste the URL',
+};
+
+interface Props {
+ projectId: string;
+ organizationId: string;
+ apiUrl: string;
+ /** Token of the project's read-only MCP client; null once the session that created it is gone. */
+ mcpToken: string | null;
+}
+
+/** The MCP token and the quickest documented route into each assistant. */
+export function McpConnect({
+ projectId,
+ organizationId,
+ apiUrl,
+ mcpToken,
+}: Props) {
+ const connection: Connection | null = mcpToken
+ ? { endpoint: `${apiUrl}/mcp`, token: mcpToken }
+ : null;
+
+ const track = (host: Host) =>
+ trackFunnel('onboarding_mcp_connect_clicked', {
+ projectId,
+ host: host.key,
+ kind: host.kind,
+ });
+
+ const renderAction = (host: Host, current: Connection) => {
+ if (host.kind === 'install') {
+ return (
+ <a
+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }))}
+ href={host.href(current)}
+ onClick={() => track(host)}
+ >
+ <ZapIcon className="mr-1.5 size-3.5" />
+ Install
+ </a>
+ );
+ }
+ if (host.kind === 'command') {
+ return (
+ <Button
+ icon={CopyIcon}
+ onClick={() => {
+ track(host);
+ clipboard(host.command(current), 'Run it in your terminal');
+ }}
+ size="sm"
+ variant="outline"
+ >
+ Copy command
+ </Button>
+ );
+ }
+ return (
+ <Button
+ icon={ExternalLinkIcon}
+ onClick={() => {
+ track(host);
+ clipboard(
+ `${current.endpoint}?token=${current.token}`,
+ `Paste it as the server URL: ${host.hint}`
+ );
+ window.open(host.settingsUrl, '_blank', 'noopener');
+ }}
+ size="sm"
+ variant="outline"
+ >
+ Copy URL
+ </Button>
+ );
+ };
+
+ return (
+ <Accordion
+ className="rounded-xl border"
+ collapsible
+ onValueChange={(value) =>
+ trackFunnel('onboarding_mcp_connect_toggled', {
+ projectId,
+ open: value === PANEL,
+ hadToken: Boolean(mcpToken),
+ })
+ }
+ type="single"
+ >
+ <AccordionItem className="border-b-0" value={PANEL}>
+ <AccordionTrigger className="gap-4 rounded-xl p-5 text-left">
+ <span className="col gap-1.5">
+ <span className="row items-center gap-2">
+ <BotIcon className="shrink-0 text-muted-foreground" size={16} />
+ <span className="font-semibold text-base">
+ Connect an AI assistant
+ </span>
+ </span>
+ <span className="font-normal text-muted-foreground text-sm">
+ Give Cursor, Claude or ChatGPT read access to this project over
+ MCP and ask it questions instead of building reports.
+ </span>
+ </span>
+ </AccordionTrigger>
+ <AccordionContent className="col gap-4 px-5 pb-5">
+ {connection ? (
+ <>
+ <ul className="col divide-y">
+ {HOSTS.map((host) => (
+ <li
+ className="row items-center justify-between gap-3 py-2.5"
+ key={host.key}
+ >
+ <div className="col">
+ <span className="font-medium text-sm">{host.label}</span>
+ <span className="text-muted-foreground text-xs">
+ {KIND_CAPTIONS[host.kind]}
+ </span>
+ </div>
+ {renderAction(host, connection)}
+ </li>
+ ))}
+ </ul>
+ <CopyInput
+ label="MCP token"
+ onCopy={() =>
+ trackFunnel('onboarding_credentials_copied', {
+ projectId,
+ what: 'mcpToken',
+ })
+ }
+ value={connection.token}
+ />
+ </>
+ ) : (
+ <p className="text-muted-foreground text-sm">
+ The MCP token was shown once when the project was created. Create
+ another MCP client to connect an assistant.
+ </p>
+ )}
+ <Link
+ className="self-start text-muted-foreground text-sm underline-offset-4 hover:text-foreground hover:underline"
+ onClick={() =>
+ trackFunnel('onboarding_mcp_settings_clicked', {
+ projectId,
+ hadToken: Boolean(mcpToken),
+ })
+ }
+ params={{ organizationId, projectId }}
+ to="/$organizationId/$projectId/settings/mcp"
+ >
+ Windsurf, Raycast and config files in Settings → MCP
+ </Link>
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
+ );
+}
diff --git a/apps/start/src/components/onboarding/onboarding-heading.tsx b/apps/start/src/components/onboarding/onboarding-heading.tsx
new file mode 100644
index 000000000..014891f54
--- /dev/null
+++ b/apps/start/src/components/onboarding/onboarding-heading.tsx
@@ -0,0 +1,20 @@
+import { cn } from '@/utils/cn';
+
+export function OnboardingHeading({
+ title,
+ description,
+ className,
+}: {
+ title: string;
+ description: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <div className={cn('col gap-3', className)}>
+ <h1 className="font-semibold text-3xl tracking-tight">{title}</h1>
+ <p className="max-w-prose text-base text-muted-foreground">
+ {description}
+ </p>
+ </div>
+ );
+}
diff --git a/apps/start/src/components/onboarding/onboarding-shell.tsx b/apps/start/src/components/onboarding/onboarding-shell.tsx
new file mode 100644
index 000000000..cf5c156c5
--- /dev/null
+++ b/apps/start/src/components/onboarding/onboarding-shell.tsx
@@ -0,0 +1,35 @@
+import { useMatches } from '@tanstack/react-router';
+
+export interface OnboardingShellConfig {
+ /** 1-based position in STEP_NAMES. */
+ step: number;
+ /** The install step has a sidebar and needs the wider container. */
+ wide: boolean;
+}
+
+export const STEP_NAMES = ['Create project', 'Install'] as const;
+
+const SHELL_BY_ROUTE: Record<string, OnboardingShellConfig> = {
+ '/_steps/onboarding/project': { step: 1, wide: false },
+ '/_steps/onboarding/$projectId/connect': { step: 2, wide: true },
+};
+
+const DEFAULT_CONFIG: OnboardingShellConfig = { step: 1, wide: false };
+
+/**
+ * Read from the committed matches, which change in the same render as the
+ * page the Outlet shows, so the frame and the step never disagree: not on
+ * the server, not on hydration and not for a frame during navigation.
+ * (Location-based matching flips as soon as a navigation starts.)
+ */
+export function useOnboardingShellConfig(): OnboardingShellConfig {
+ return useMatches({
+ select: (matches) => {
+ const stepMatch = matches.find(
+ (match) => match.routeId in SHELL_BY_ROUTE
+ );
+ return stepMatch ? SHELL_BY_ROUTE[stepMatch.routeId] : DEFAULT_CONFIG;
+ },
+ structuralSharing: true,
+ });
+}
diff --git a/apps/start/src/components/onboarding/onboarding-verify-listener.tsx b/apps/start/src/components/onboarding/onboarding-verify-listener.tsx
deleted file mode 100644
index 227643a24..000000000
--- a/apps/start/src/components/onboarding/onboarding-verify-listener.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import type { IServiceEvent } from '@openpanel/core';
-import { CheckCircle2Icon, CheckIcon, Loader2 } from 'lucide-react';
-import { cn } from '@/utils/cn';
-import { timeAgo } from '@/utils/date';
-
-interface Props {
- events: IServiceEvent[];
-}
-
-const VerifyListener = ({ events }: Props) => {
- const isConnected = events.length > 0;
-
- const renderIcon = () => {
- if (isConnected) {
- return (
- <CheckCircle2Icon
- className="shrink-0 text-emerald-600"
- size={40}
- strokeWidth={1.2}
- />
- );
- }
-
- return (
- <Loader2 className="shrink-0 animate-spin text-highlight" size={40} />
- );
- };
-
- return (
- <div>
- <div
- className={cn(
- 'flex gap-6 rounded-xl p-4 md:p-6',
- isConnected
- ? 'bg-emerald-100 dark:bg-emerald-700/10'
- : 'bg-blue-500/10'
- )}
- >
- {renderIcon()}
- <div className="flex-1">
- <div className="font-semibold text-foreground/90 text-lg">
- {isConnected ? 'Successfully connected' : 'Waiting for events'}
- </div>
- {isConnected ? (
- <div className="mt-2 flex flex-col-reverse gap-1">
- {events.length > 5 && (
- <div className="flex items-center gap-2">
- <CheckIcon size={14} />{' '}
- <span>{events.length - 5} more events</span>
- </div>
- )}
- {events.slice(-5).map((event) => (
- <div className="flex items-center gap-2" key={event.id}>
- <CheckIcon size={14} />{' '}
- <span className="font-medium">{event.name}</span>{' '}
- <span className="ml-auto text-foreground/50 text-sm">
- {timeAgo(event.createdAt, 'round')}
- </span>
- </div>
- ))}
- </div>
- ) : (
- <div className="text-foreground/50">
- Verify that your implementation works.
- </div>
- )}
- </div>
- </div>
- </div>
- );
-};
-
-export default VerifyListener;
diff --git a/apps/start/src/components/onboarding/skip-onboarding.tsx b/apps/start/src/components/onboarding/skip-onboarding.tsx
deleted file mode 100644
index 9d591ae42..000000000
--- a/apps/start/src/components/onboarding/skip-onboarding.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { useQuery } from '@tanstack/react-query';
-import { Link, useLocation, useNavigate } from '@tanstack/react-router';
-import { ChevronLastIcon, LogInIcon } from 'lucide-react';
-import { useEffect } from 'react';
-import { useLogout } from '@/hooks/use-logout';
-import { useTRPC } from '@/integrations/trpc/react';
-import { showConfirm } from '@/modals';
-
-const PUBLIC_SEGMENTS = [['onboarding']];
-
-export const SkipOnboarding = () => {
- const trpc = useTRPC();
- const navigate = useNavigate();
- const location = useLocation();
- const pathname = location.pathname;
- const segments = location.pathname.split('/').filter(Boolean);
- const isPublic = PUBLIC_SEGMENTS.some((segment) =>
- segments.every((s, index) => s === segment[index])
- );
- const res = useQuery(
- trpc.onboarding.skipOnboardingCheck.queryOptions(undefined, {
- enabled: !isPublic,
- })
- );
-
- const logout = useLogout();
- useEffect(() => {
- res.refetch();
- }, [pathname]);
-
- // Do not show skip onboarding for the first step (register account)
- if (isPublic) {
- return (
- <Link
- className="flex items-center gap-2 text-muted-foreground"
- to="/login"
- >
- Login
- <LogInIcon size={16} />
- </Link>
- );
- }
-
- if (res.isLoading || res.isError) {
- return null;
- }
-
- return (
- <button
- className="flex items-center gap-2 text-muted-foreground"
- onClick={() => {
- if (res.data?.canSkip) {
- navigate({ to: '/' });
- } else {
- showConfirm({
- title: 'Skip onboarding?',
- text: 'Are you sure you want to skip onboarding? Since you do not have any projects, you will be logged out.',
- onConfirm() {
- logout.mutate();
- },
- });
- }
- }}
- type="button"
- >
- Skip onboarding
- <ChevronLastIcon size={16} />
- </button>
- );
-};
diff --git a/apps/start/src/components/onboarding/steps.tsx b/apps/start/src/components/onboarding/steps.tsx
deleted file mode 100644
index e05083158..000000000
--- a/apps/start/src/components/onboarding/steps.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import { useLocation } from '@tanstack/react-router';
-import { CheckCheckIcon } from 'lucide-react';
-import { cn } from '@/lib/utils';
-
-type Step = {
- name: string;
- status: 'completed' | 'current' | 'pending';
- match: string;
-};
-
-type Props = {
- className?: string;
-};
-
-function useSteps(path: string) {
- const steps: Step[] = [
- {
- name: 'Create an account',
- status: 'pending',
- match: '/onboarding',
- },
- {
- name: 'Create a project',
- status: 'pending',
- match: '/onboarding/project',
- },
- {
- name: 'Connect your data',
- status: 'pending',
- match: '/onboarding/(.+)/connect',
- },
- {
- name: 'Verify',
- status: 'pending',
- match: '/onboarding/(.+)/verify',
- },
- ];
-
- // @ts-expect-error
- const matchIndex = steps.findLastIndex((step) =>
- path.match(new RegExp(step.match))
- );
-
- return steps.map((step, index) => {
- if (index < matchIndex) {
- return { ...step, status: 'completed' };
- }
- if (index === matchIndex) {
- return { ...step, status: 'current' };
- }
- return step;
- });
-}
-
-export const OnboardingSteps = ({ className }: Props) => {
- const location = useLocation();
- const path = location.pathname;
- const steps = useSteps(path);
- const currentIndex = steps.findIndex((i) => i.status === 'current');
- return (
- <div className="relative">
- <div className="absolute top-4 bottom-4 left-4 w-px bg-def-200" />
- <div
- className="absolute top-4 left-4 w-px bg-highlight"
- style={{
- height: `calc(${((currentIndex + 1) / steps.length) * 100}% - 3.5rem)`,
- }}
- />
- <div
- className={cn(
- 'relative flex gap-4 overflow-hidden md:-ml-3 md:flex-col md:gap-8',
- className
- )}
- >
- {steps.map((step, index) => (
- <div
- className={cn(
- 'flex flex-shrink-0 items-center gap-4 self-start px-3 py-1.5',
- step.status === 'current' &&
- 'rounded-xl border border-border bg-card',
- step.status === 'completed' &&
- index !== currentIndex - 1 &&
- 'max-md:hidden'
- )}
- key={step.name}
- >
- <div
- className={cn(
- 'relative flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-white'
- )}
- >
- <div
- className={cn(
- 'absolute inset-0 z-0 rounded-full bg-highlight',
- step.status === 'pending' && 'bg-def-400'
- )}
- />
- {step.status === 'current' && (
- <div className="absolute inset-1 z-0 animate-ping-slow rounded-full bg-highlight" />
- )}
- <div className="relative">
- {step.status === 'completed' && <CheckCheckIcon size={14} />}
- {(step.status === 'pending' || step.status === 'current') &&
- index + 1}
- </div>
- </div>
-
- <div className="font-medium">{step.name}</div>
- </div>
- ))}
- </div>
- </div>
- );
-};
diff --git a/apps/start/src/components/onboarding/verify-faq.tsx b/apps/start/src/components/onboarding/verify-faq.tsx
deleted file mode 100644
index 90303e6ef..000000000
--- a/apps/start/src/components/onboarding/verify-faq.tsx
+++ /dev/null
@@ -1,186 +0,0 @@
-import type { IServiceProjectWithClients } from '@openpanel/core';
-import { useMutation, useQueryClient } from '@tanstack/react-query';
-import { GlobeIcon, KeyIcon, UserIcon } from 'lucide-react';
-import { toast } from 'sonner';
-import CopyInput from '../forms/copy-input';
-import { WithLabel } from '../forms/input-with-label';
-import TagInput from '../forms/tag-input';
-import Syntax from '../syntax';
-import {
- Accordion,
- AccordionContent,
- AccordionItem,
- AccordionTrigger,
-} from '../ui/accordion';
-import { Alert, AlertDescription, AlertTitle } from '../ui/alert';
-import { useAppContext } from '@/hooks/use-app-context';
-import { useClientSecret } from '@/hooks/use-client-secret';
-import { handleError, useTRPC } from '@/integrations/trpc/react';
-
-export function VerifyFaq({
- project,
-}: {
- project: IServiceProjectWithClients;
-}) {
- const context = useAppContext();
- const trpc = useTRPC();
- const queryClient = useQueryClient();
- const [secret] = useClientSecret();
-
- const updateProject = useMutation(
- trpc.project.update.mutationOptions({
- onError: handleError,
- onSuccess: () => {
- queryClient.invalidateQueries(
- trpc.project.getProjectWithClients.queryFilter({
- projectId: project.id,
- })
- );
- toast.success('Allowed domains updated');
- },
- })
- );
-
- const client = project.clients[0];
- if (!client) {
- return null;
- }
-
- const handleCorsChange = (newValue: string[]) => {
- const normalized = newValue
- .map((item: string) => {
- const trimmed = item.trim();
- if (
- trimmed.startsWith('http://') ||
- trimmed.startsWith('https://') ||
- trimmed === '*'
- ) {
- return trimmed;
- }
- return trimmed ? `https://${trimmed}` : trimmed;
- })
- .filter(Boolean);
- updateProject.mutate({ id: project.id, cors: normalized });
- };
-
- const showSecret = secret && secret !== '[CLIENT_SECRET]';
-
- const payload: Record<string, any> = {
- type: 'track',
- payload: {
- name: 'screen_view',
- properties: {
- __title: `Testing OpenPanel - ${project.name}`,
- __path: `${project.domain}`,
- __referrer: `${context.dashboardUrl}`,
- },
- },
- };
-
- if (project.types.includes('app')) {
- payload.payload.properties.__path = '/';
- delete payload.payload.properties.__referrer;
- }
-
- if (project.types.includes('backend')) {
- payload.payload.name = 'test_event';
- payload.payload.properties = {};
- }
-
- const code = `curl -X POST ${context.apiUrl}/track \\
--H "Content-Type: application/json" \\
--H "openpanel-client-id: ${client.id}" \\
--H "openpanel-client-secret: ${secret}" \\
--H "User-Agent: ${typeof window !== 'undefined' ? window.navigator.userAgent : ''}" \\
--d '${JSON.stringify(payload)}'`;
-
- return (
- <div className="card">
- <Accordion collapsible type="single">
- <AccordionItem value="item-1">
- <AccordionTrigger className="px-6">
- No events received?
- </AccordionTrigger>
- <AccordionContent className="col gap-4 p-6 pt-2">
- <p>
- Don't worry, this happens to everyone. Here are a few things you
- can check:
- </p>
- <div className="col gap-2">
- <Alert>
- <UserIcon size={16} />
- <AlertTitle>Ensure client ID is correct</AlertTitle>
- <AlertDescription className="col gap-2">
- <span>
- For web tracking, the <code>clientId</code> in your snippet
- must match this project. Copy it here if needed:
- </span>
- <CopyInput className="" label="Client ID" value={client.id} />
- </AlertDescription>
- </Alert>
- <Alert>
- <GlobeIcon size={16} />
- <AlertTitle>Correct domain configured</AlertTitle>
- <AlertDescription className="col gap-2">
- <span>
- For websites it&apos;s important that the domain is
- correctly configured. We authenticate requests based on the
- domain. Update allowed domains below:
- </span>
- <WithLabel label="Allowed domains">
- <TagInput
- onChange={handleCorsChange}
- placeholder="Accept events from these domains"
- renderTag={(tag: string) =>
- tag === '*' ? 'Accept events from any domains' : tag
- }
- value={project.cors ?? []}
- />
- </WithLabel>
- </AlertDescription>
- </Alert>
- <Alert>
- <KeyIcon size={16} />
- <AlertTitle>Wrong client secret</AlertTitle>
- <AlertDescription className="col gap-2">
- <span>
- For app and backend events you need the correct{' '}
- <code>clientSecret</code>. Copy it here if needed. Never use
- the client secret in web or client-side code—it would expose
- your credentials.
- </span>
- {showSecret && (
- <CopyInput
- className=""
- label="Client secret"
- value={secret}
- />
- )}
- </AlertDescription>
- </Alert>
- </div>
- <p>
- Still have issues? Join our{' '}
- <a className="underline" href="https://go.openpanel.dev/discord">
- discord channel
- </a>{' '}
- give us an email at{' '}
- <a className="underline" href="mailto:[email protected]">
- </a>{' '}
- and we&apos;ll help you out.
- </p>
- </AccordionContent>
- </AccordionItem>
- <AccordionItem value="item-2">
- <AccordionTrigger className="px-6">
- Personal curl example
- </AccordionTrigger>
- <AccordionContent className="p-0">
- <Syntax code={code} language="bash" />
- </AccordionContent>
- </AccordionItem>
- </Accordion>
- </div>
- );
-}
diff --git a/apps/start/src/components/skeleton-dashboard.tsx b/apps/start/src/components/skeleton-dashboard.tsx
deleted file mode 100644
index 7e8e6330e..000000000
--- a/apps/start/src/components/skeleton-dashboard.tsx
+++ /dev/null
@@ -1,122 +0,0 @@
-export function SkeletonDashboard() {
- return (
- <div className="fixed inset-0 overflow-hidden bg-gradient-to-br from-def-100 to-def-200">
- <div className="fixed inset-0 z-10 bg-background/10 backdrop-blur-xs" />
- <div className="fixed top-0 left-0 h-full w-72 border-def-300/50 border-r bg-background/80 backdrop-blur-sm">
- <div className="flex h-16 items-center border-def-300/50 border-b px-4">
- <div className="h-8 w-8 rounded-lg bg-def-300/60" />
- <div className="ml-3 h-4 w-24 rounded bg-def-300/60" />
- </div>
-
- <div className="space-y-3 p-4">
- {[
- 'Dashboard',
- 'Analytics',
- 'Reports',
- 'Settings',
- 'Users',
- 'Projects',
- ].map((item, i) => (
- <div
- className="flex items-center space-x-3 rounded-lg p-2"
- key={`nav-${item.toLowerCase()}`}
- >
- <div className="h-5 w-5 rounded bg-def-300/60" />
- <div className="h-3 w-20 rounded bg-def-300/60" />
- </div>
- ))}
- </div>
-
- <div className="px-4 py-2">
- <div className="mb-3 h-3 w-16 rounded bg-def-300/60" />
- {['Project Alpha', 'Project Beta', 'Project Gamma'].map(
- (project, i) => (
- <div
- className="mb-2 flex items-center space-x-3 rounded-lg p-2"
- key={`project-${project.toLowerCase().replace(' ', '-')}`}
- >
- <div className="h-4 w-4 rounded bg-def-300/60" />
- <div className="h-3 w-24 rounded bg-def-300/60" />
- </div>
- )
- )}
- </div>
- </div>
-
- <div className="ml-72 p-8">
- <div className="mb-8">
- <div className="mb-4 flex items-center justify-between">
- <div className="h-6 w-48 rounded bg-def-300/60" />
- <div className="flex space-x-2">
- <div className="h-8 w-20 rounded bg-def-300/60" />
- <div className="h-8 w-20 rounded bg-def-300/60" />
- </div>
- </div>
- </div>
-
- <div className="mb-8 grid grid-cols-3 gap-6">
- {[
- 'Total Users',
- 'Active Sessions',
- 'Page Views',
- 'Bounce Rate',
- 'Conversion',
- 'Revenue',
- ].map((metric, i) => (
- <div
- className="rounded-xl border border-def-300/50 bg-card/60 p-6"
- key={`metric-${metric.toLowerCase().replace(' ', '-')}`}
- >
- <div className="mb-3 h-4 w-16 rounded bg-def-300/60" />
- <div className="mb-2 h-8 w-24 rounded bg-def-300/60" />
- <div className="h-3 w-32 rounded bg-def-300/60" />
- </div>
- ))}
- </div>
-
- <div className="grid grid-cols-2 gap-6">
- <div className="h-64 rounded-xl border border-def-300/50 bg-card/60 p-6">
- <div className="mb-4 h-4 w-20 rounded bg-def-300/60" />
- <div className="space-y-3">
- {['Desktop', 'Mobile', 'Tablet', 'Other'].map((device, i) => (
- <div
- className="flex items-center space-x-3"
- key={`chart-${device.toLowerCase()}`}
- >
- <div className="h-3 w-3 rounded-full bg-def-300/60" />
- <div className="h-2 flex-1 rounded bg-def-300/60" />
- <div className="h-3 w-8 rounded bg-def-300/60" />
- </div>
- ))}
- </div>
- </div>
-
- <div className="h-64 rounded-xl border border-def-300/50 bg-card/60 p-6">
- <div className="mb-4 h-4 w-20 rounded bg-def-300/60" />
- <div className="space-y-3">
- {[
- 'John Doe',
- 'Jane Smith',
- 'Bob Johnson',
- 'Alice Brown',
- 'Charlie Wilson',
- ].map((user, i) => (
- <div
- className="flex items-center space-x-3"
- key={`user-${user.toLowerCase().replace(' ', '-')}`}
- >
- <div className="h-8 w-8 rounded-full bg-def-300/60" />
- <div className="flex-1">
- <div className="mb-1 h-3 w-24 rounded bg-def-300/60" />
- <div className="h-2 w-16 rounded bg-def-300/60" />
- </div>
- <div className="h-3 w-12 rounded bg-def-300/60" />
- </div>
- ))}
- </div>
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/apps/start/src/components/syntax.tsx b/apps/start/src/components/syntax.tsx
index db904297f..ba733bcc9 100644
--- a/apps/start/src/components/syntax.tsx
+++ b/apps/start/src/components/syntax.tsx
@@ -19,6 +19,7 @@ interface SyntaxProps {
language?: 'typescript' | 'bash' | 'json' | 'markdown';
wrapLines?: boolean;
copyable?: boolean;
+ onCopy?: () => void;
}
export default function Syntax({
@@ -27,6 +28,7 @@ export default function Syntax({
language = 'typescript',
wrapLines = false,
copyable = true,
+ onCopy,
}: SyntaxProps) {
return (
<div className={cn('group relative rounded-lg', className)}>
@@ -35,6 +37,7 @@ export default function Syntax({
className="row absolute top-1 right-1 items-center gap-2 rounded bg-card p-2 opacity-0 transition-opacity group-hover:opacity-100"
onClick={() => {
clipboard(code, null);
+ onCopy?.();
}}
type="button"
>
diff --git a/apps/start/src/components/ui/button.tsx b/apps/start/src/components/ui/button.tsx
index 5e68fe3e9..9c4e37efe 100644
--- a/apps/start/src/components/ui/button.tsx
+++ b/apps/start/src/components/ui/button.tsx
@@ -28,6 +28,7 @@ const buttonVariants = cva(
default: 'h-9 px-3.5',
sm: 'h-8 rounded-md px-2.5',
lg: 'h-10 rounded-md px-6',
+ xl: 'h-11 rounded-lg px-6 text-base',
icon: 'h-8 w-8',
},
},
@@ -62,6 +63,8 @@ function fixHeight({
switch (size) {
case 'lg':
return 'h-auto min-h-10 py-2';
+ case 'xl':
+ return 'h-auto min-h-11 py-2';
case 'icon':
return 'h-auto min-h-8 py-1';
case 'sm':
@@ -98,7 +101,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
const Icon = loading ? null : (icon ?? null);
// Determine spinner size based on button size
- const spinnerSize = size === 'lg' ? 'md' : size === 'icon' ? 'sm' : 'sm';
+ const spinnerSize = size === 'lg' || size === 'xl' ? 'md' : 'sm';
// With `asChild`, Radix's <Slot> merges props onto a single child element
// and calls React.Children.only. Injecting a spinner/icon as extra siblings
@@ -198,7 +201,7 @@ const LinkButton = ({
const Icon = loading ? null : (icon ?? null);
// Determine spinner size based on button size
- const spinnerSize = size === 'lg' ? 'md' : size === 'icon' ? 'sm' : 'sm';
+ const spinnerSize = size === 'lg' || size === 'xl' ? 'md' : 'sm';
return (
<Link
diff --git a/apps/start/src/components/ui/input.tsx b/apps/start/src/components/ui/input.tsx
index e834a9e82..420964f64 100644
--- a/apps/start/src/components/ui/input.tsx
+++ b/apps/start/src/components/ui/input.tsx
@@ -18,6 +18,7 @@ const inputVariant = cva(
sm: 'h-8 rounded-md px-2.5',
default: 'h-9 px-3',
large: 'h-10 px-3.5',
+ xl: 'h-11 px-4 text-base',
},
},
defaultVariants: {
diff --git a/apps/start/src/hooks/use-client-secret.ts b/apps/start/src/hooks/use-client-secret.ts
index 8dc5facd2..ce43c117e 100644
--- a/apps/start/src/hooks/use-client-secret.ts
+++ b/apps/start/src/hooks/use-client-secret.ts
@@ -1,8 +1,14 @@
import { useEffect, useState } from 'react';
-export const ONBOARDING_SECRET_KEY = 'onboarding.clientSecret';
+const SECRET_KEY = 'onboarding.clientSecret';
+const MCP_TOKEN_KEY = 'onboarding.mcpToken';
const DEFAULT_SECRET = '[CLIENT_SECRET]';
+// Keyed per project: opening another project's install step must never show
+// it the credentials of the one created before.
+const secretKey = (projectId: string) => `${SECRET_KEY}:${projectId}`;
+const mcpTokenKey = (projectId: string) => `${MCP_TOKEN_KEY}:${projectId}`;
+
// The secret only exists client-side right after creation (we store a hash).
// Anything derived from it (MCP token, env snippets) must check this first —
// deriving from the placeholder produces valid-looking but broken values.
@@ -12,38 +18,70 @@ export const isRealClientSecret = (
// Storage can throw (blocked cookies/site data, some private modes); a missing
// secret must degrade to the placeholder flow, never crash the page.
-const safeRead = () => {
+const safeRead = (key: string) => {
try {
- return sessionStorage.getItem(ONBOARDING_SECRET_KEY);
+ return sessionStorage.getItem(key);
} catch {
return null;
}
};
-const safeWrite = (value: string) => {
+/** Drops every stored onboarding credential, e.g. when the account signs out. */
+export function forgetOnboardingKeys() {
try {
- sessionStorage.setItem(ONBOARDING_SECRET_KEY, value);
+ const stale = Object.keys(sessionStorage).filter(
+ (key) => key.startsWith(SECRET_KEY) || key.startsWith(MCP_TOKEN_KEY)
+ );
+ for (const key of stale) {
+ sessionStorage.removeItem(key);
+ }
+ } catch {
+ // Storage unavailable: nothing was stored either.
+ }
+}
+
+const safeWrite = (key: string, value: string) => {
+ try {
+ sessionStorage.setItem(key, value);
} catch {
// Unavailable — the connect page falls back to its secret-already-shown
// notice.
}
};
-export function useClientSecret() {
- const [clientSecret, setClientSecret] = useState<string>(DEFAULT_SECRET);
+/** Keeps a project's one-time credentials for the rest of the browser session. */
+export function rememberOnboardingKeys(
+ projectId: string,
+ keys: { clientSecret?: string | null; mcpToken?: string | null }
+) {
+ if (keys.clientSecret) {
+ safeWrite(secretKey(projectId), keys.clientSecret);
+ }
+ if (keys.mcpToken) {
+ safeWrite(mcpTokenKey(projectId), keys.mcpToken);
+ }
+}
- useEffect(() => {
- if (clientSecret && DEFAULT_SECRET !== clientSecret) {
- safeWrite(clientSecret);
- }
- }, [clientSecret]);
+function useSessionSecret(key: string, fallback: string) {
+ const [value, setValue] = useState<string>(fallback);
+ // False until storage has been read, so a first-render consumer does not
+ // mistake the fallback for "no secret".
+ const [ready, setReady] = useState(false);
useEffect(() => {
- const stored = safeRead();
- if (stored) {
- setClientSecret(stored);
- }
- }, []);
+ setValue(safeRead(key) ?? fallback);
+ setReady(true);
+ }, [key, fallback]);
+
+ return [value, ready] as const;
+}
+
+export function useClientSecret(projectId: string) {
+ return useSessionSecret(secretKey(projectId), DEFAULT_SECRET);
+}
- return [clientSecret, setClientSecret] as const;
+/** The read-only MCP client's token, known only in the session that created the project. */
+export function useMcpToken(projectId: string) {
+ const [token, ready] = useSessionSecret(mcpTokenKey(projectId), '');
+ return [token || null, ready] as const;
}
diff --git a/apps/start/src/hooks/use-logout.ts b/apps/start/src/hooks/use-logout.ts
index a9d6f6fb8..b47be1bba 100644
--- a/apps/start/src/hooks/use-logout.ts
+++ b/apps/start/src/hooks/use-logout.ts
@@ -1,4 +1,5 @@
import { useMutation } from '@tanstack/react-query';
+import { forgetOnboardingKeys } from '@/hooks/use-client-secret';
import { useTRPC } from '@/integrations/trpc/react';
export function useLogout() {
@@ -6,6 +7,8 @@ export function useLogout() {
const signOut = useMutation(
trpc.auth.signOut.mutationOptions({
onSuccess() {
+ // The one-time secrets must not outlive the session that minted them.
+ forgetOnboardingKeys();
window.location.href = '/';
},
})
diff --git a/apps/start/src/modals/Instructions.tsx b/apps/start/src/modals/Instructions.tsx
deleted file mode 100644
index 6e285ea6b..000000000
--- a/apps/start/src/modals/Instructions.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import type { IPublicClient } from '@openpanel/core';
-import type { frameworks } from '@openpanel/sdk-info';
-import { ExternalLinkIcon, XIcon } from 'lucide-react';
-import { popModal } from '.';
-import { Button, LinkButton } from '@/components/ui/button';
-import {
- SheetContent,
- SheetFooter,
- SheetHeader,
- SheetTitle,
-} from '@/components/ui/sheet';
-
-type Props = {
- client: IPublicClient | null;
- framework: (typeof frameworks)[number];
-};
-
-const Header = ({ framework }: Pick<Props, 'framework'>) => (
- <SheetHeader>
- <SheetTitle>Instructions for {framework.name}</SheetTitle>
- </SheetHeader>
-);
-
-const Footer = ({ framework }: Pick<Props, 'framework'>) => (
- <SheetFooter className="absolute right-0 bottom-0 left-0 mx-0 mb-0">
- <Button
- className="flex-1"
- icon={XIcon}
- onClick={() => popModal()}
- variant={'secondary'}
- >
- Close
- </Button>
- <LinkButton
- className="flex-1"
- href={framework.href}
- icon={ExternalLinkIcon}
- target="_blank"
- >
- More details
- </LinkButton>
- </SheetFooter>
-);
-
-const Instructions = ({ framework }: Props) => {
- return (
- <iframe
- className="h-full w-full"
- src={framework.href}
- title={framework.name}
- />
- );
-};
-
-export default function InstructionsWithModalContent(props: Props) {
- return (
- <SheetContent className="p-0">
- <Instructions {...props} />
- <Footer {...props} />
- </SheetContent>
- );
-}
diff --git a/apps/start/src/modals/add-project.tsx b/apps/start/src/modals/add-project.tsx
index fc743c7c4..82d750764 100644
--- a/apps/start/src/modals/add-project.tsx
+++ b/apps/start/src/modals/add-project.tsx
@@ -22,7 +22,7 @@ import TagInput from '@/components/forms/tag-input';
import { Button } from '@/components/ui/button';
import { DialogFooter } from '@/components/ui/dialog';
import { useAppParams } from '@/hooks/use-app-params';
-import { ONBOARDING_SECRET_KEY } from '@/hooks/use-client-secret';
+import { rememberOnboardingKeys } from '@/hooks/use-client-secret';
import { handleError, useTRPC } from '@/integrations/trpc/react';
const validator = zOnboardingProject;
@@ -119,17 +119,11 @@ export default function AddProject() {
<Button asChild className="flex-1">
<a
href={`/onboarding/${mutation.data.id}/connect`}
- onClick={() => {
- const secret = mutation.data.client?.secret;
- if (secret) {
- try {
- sessionStorage.setItem(ONBOARDING_SECRET_KEY, secret);
- } catch {
- // Storage unavailable — connect falls back to its
- // secret-already-shown notice.
- }
- }
- }}
+ onClick={() =>
+ rememberOnboardingKeys(mutation.data.id, {
+ clientSecret: mutation.data.client?.secret,
+ })
+ }
>
Set up tracking
</a>
diff --git a/apps/start/src/modals/index.tsx b/apps/start/src/modals/index.tsx
index 91771da97..6477ac91b 100644
--- a/apps/start/src/modals/index.tsx
+++ b/apps/start/src/modals/index.tsx
@@ -26,7 +26,6 @@ import EditGroup from './edit-group';
import EditMember from './edit-member';
import EditReference from './edit-reference';
import EditReport from './edit-report';
-import Instructions from './Instructions';
import InsightDetails from './insight-details';
import MoveReport from './move-report';
import OverviewChartDetails from './overview-chart-details';
@@ -77,7 +76,6 @@ const modals = {
ShareReportModal,
AddReference,
ViewChartUsers,
- Instructions,
DateRangerPicker,
DateTimePicker,
OverviewChartDetails,
diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.tracking.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.tracking.tsx
index 7e3f33ade..003df0766 100644
--- a/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.tracking.tsx
+++ b/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.tracking.tsx
@@ -1,17 +1,12 @@
import type { IPublicClient } from '@openpanel/core';
-import { frameworks } from '@openpanel/sdk-info';
import { useQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
-import { CopyIcon } from 'lucide-react';
-import { useEffect, useState } from 'react';
-import Syntax from '@/components/syntax';
-import { Button } from '@/components/ui/button';
+import { useState } from 'react';
+import { InstallGuide } from '@/components/onboarding/install-guide';
import { Combobox } from '@/components/ui/combobox';
import { useAppContext } from '@/hooks/use-app-context';
import { useAppParams } from '@/hooks/use-app-params';
import { useTRPC } from '@/integrations/trpc/react';
-import { pushModal } from '@/modals';
-import { clipboard } from '@/utils/clipboard';
export const Route = createFileRoute(
'/_app/$organizationId/$projectId/settings/_tabs/tracking'
@@ -22,95 +17,50 @@ export const Route = createFileRoute(
function Component() {
const { projectId } = useAppParams();
const trpc = useTRPC();
- const query = useQuery(trpc.client.list.queryOptions({ projectId }));
- return <ConnectWeb clients={query.data ?? []} />;
-}
+ const { apiUrl, isSelfHosted } = useAppContext();
+ const { data: project } = useQuery(
+ trpc.project.getProjectWithClients.queryOptions({ projectId })
+ );
+ const [selectedClientId, setSelectedClientId] = useState<string | null>(null);
+ // Read clients (MCP) cannot send events, so they never belong in a snippet.
+ const clients: IPublicClient[] = (project?.clients ?? []).filter(
+ (candidate) => candidate.type !== 'read'
+ );
+ const client =
+ clients.find((candidate) => candidate.id === selectedClientId) ??
+ clients[0];
-interface Props {
- clients: IPublicClient[];
-}
+ if (!(project && client)) {
+ return null;
+ }
-const ConnectWeb = ({ clients }: Props) => {
- const [client, setClient] = useState<IPublicClient | null>(null);
- useEffect(() => {
- if (!client && clients && clients.length > 0) {
- setClient(clients[0]);
- }
- }, [clients]);
- const context = useAppContext();
- const code = `<script>
- window.op=window.op||function(){var n=[];return new Proxy(function(){arguments.length&&n.push([].slice.call(arguments))},{get:function(t,r){return"q"===r?n:function(){n.push([r].concat([].slice.call(arguments)))}} ,has:function(t,r){return"q"===r}}) }();
- window.op('init', {${context.isSelfHosted ? `\n\tapiUrl: '${context.apiUrl}',` : ''}
- clientId: '${client?.id ?? 'YOUR_CLIENT_ID'}',
- trackScreenViews: true,
- trackOutgoingLinks: true,
- trackAttributes: true,
- // sessionReplay: {
- // enabled: true,
- // },
- });
-</script>
-<script src="https://openpanel.dev/op1.js" defer async></script>`;
return (
- <div className="col gap-4">
- <div className="col gap-2">
- <div className="row items-center justify-between gap-4">
- <Combobox
- items={clients.map((c) => ({
- value: c.id,
- label: c.name,
- }))}
- onChange={(id) =>
- setClient(clients.find((c) => c.id === id) ?? null)
- }
- placeholder="Select client"
- searchable
- value={client?.id ?? null}
- />
- <Button
- icon={CopyIcon}
- onClick={() => clipboard(code, null)}
- variant="outline"
- >
- Copy
- </Button>
- </div>
- <Syntax className="border" code={code} copyable={false} />
- </div>
- <div className="col gap-4">
- <p className="text-center text-muted-foreground text-sm">
- Or pick a framework below to get started.
- </p>
- <div className="grid gap-4 md:grid-cols-2">
- {frameworks.map((framework) => (
- <button
- className="flex items-center gap-4 rounded-md border p-2 text-left"
- key={framework.name}
- onClick={() =>
- pushModal('Instructions', {
- framework,
- client,
- })
- }
- type="button"
- >
- <div className="h-10 w-10 rounded-md bg-def-200 p-2">
- <framework.IconComponent className="h-full w-full" />
- </div>
- <div className="flex-1 font-semibold">{framework.name}</div>
- </button>
- ))}
- </div>
- <p className="text-center text-muted-foreground text-sm">
- Missing a framework?{' '}
- <a
- className="text-foreground underline"
- href="mailto:[email protected]"
- >
- Let us know!
- </a>
- </p>
- </div>
+ <div className="col gap-6">
+ {clients.length > 1 && (
+ <Combobox
+ items={clients.map((candidate) => ({
+ value: candidate.id,
+ label: candidate.name,
+ }))}
+ onChange={setSelectedClientId}
+ placeholder="Select client"
+ searchable
+ value={client.id}
+ />
+ )}
+ <InstallGuide
+ context={{
+ clientId: client.id,
+ // Secrets are stored hashed; after creation only the snippet
+ // placeholder remains.
+ clientSecret: null,
+ apiUrl: isSelfHosted ? apiUrl : null,
+ }}
+ defaultMethod="manual"
+ projectId={project.id}
+ projectName={project.name}
+ projectTypes={project.types}
+ />
</div>
);
-};
+}
diff --git a/apps/start/src/routes/_login.login.tsx b/apps/start/src/routes/_login.login.tsx
index 065fb01b1..2eba06139 100644
--- a/apps/start/src/routes/_login.login.tsx
+++ b/apps/start/src/routes/_login.login.tsx
@@ -1,15 +1,17 @@
import { useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import { AlertCircle } from 'lucide-react';
+import { useEffect } from 'react';
import { z } from 'zod';
+import { AuthHeading } from '@/components/auth/auth-shell';
import { Or } from '@/components/auth/or';
import { SignInDev } from '@/components/auth/sign-in-dev';
import { SignInEmailForm } from '@/components/auth/sign-in-email-form';
-import { SignInGithub } from '@/components/auth/sign-in-github';
-import { SignInGoogle } from '@/components/auth/sign-in-google';
+import { SignInOAuth } from '@/components/auth/sign-in-oauth';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { useCookieStore } from '@/hooks/use-cookie-store';
import { useTRPC } from '@/integrations/trpc/react';
+import { trackFunnel } from '@/utils/funnel-tracking';
import { createTitle, PAGE_TITLES } from '@/utils/title';
export const Route = createFileRoute('/_login/login')({
@@ -43,43 +45,45 @@ function LoginPage() {
'last-auth-provider',
null
);
+ useEffect(() => {
+ trackFunnel('auth_page_viewed', {
+ page: 'login',
+ hasInvite: Boolean(inviteId),
+ hadError: Boolean(error),
+ google: providers.google,
+ github: providers.github,
+ lastProvider,
+ });
+ }, [inviteId, error, providers.google, providers.github, lastProvider]);
+
+ const signUpHref = inviteId
+ ? `/onboarding?inviteId=${encodeURIComponent(inviteId)}`
+ : '/onboarding';
return (
- <div className="col w-full gap-8 text-left">
- <div>
- <h1 className="mb-2 font-bold text-3xl text-foreground">Sign in</h1>
- <p className="text-muted-foreground">
- Don't have an account?{' '}
- <a
- className="font-medium text-foreground underline"
- href="/onboarding"
- >
- Create one today
- </a>
- </p>
- </div>
+ <div className="col w-full gap-8">
+ <AuthHeading
+ description="Sign in to your OpenPanel account."
+ title="Welcome back"
+ />
+
{error && (
- <Alert
- className="mb-6 border-destructive/20 bg-destructive/10 text-left"
- variant="destructive"
- >
+ <Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
- <AlertTitle>Error</AlertTitle>
+ <AlertTitle>Could not sign you in</AlertTitle>
<AlertDescription>
<p>{error}</p>
{correlationId && (
- <>
- <p>Correlation ID: {correlationId}</p>
- <p className="mt-2">
- Contact us if you have any issues.{' '}
- <a
- className="font-medium underline"
- href={`mailto:[email protected]?subject=Login%20Issue%20-%20Correlation%20ID%3A%20${correlationId}`}
- >
- hello[at]openpanel.dev
- </a>
- </p>
- </>
+ <p className="mt-2">
+ Reference: {correlationId}.{' '}
+ <a
+ className="font-medium underline"
+ href={`mailto:[email protected]?subject=${encodeURIComponent(`Login Issue - Correlation ID: ${correlationId}`)}`}
+ >
+ Email us
+ </a>{' '}
+ and we will sort it out.
+ </p>
)}
</AlertDescription>
</Alert>
@@ -87,35 +91,46 @@ function LoginPage() {
{hasOAuthProviders && (
<>
- <div className="space-y-4">
+ <div className="col gap-3">
{providers.google && (
- <SignInGoogle
+ <SignInOAuth
inviteId={inviteId}
isLastUsed={lastProvider === 'google'}
+ provider="google"
type="sign-in"
/>
)}
{providers.github && (
- <SignInGithub
+ <SignInOAuth
inviteId={inviteId}
isLastUsed={lastProvider === 'github'}
+ provider="github"
type="sign-in"
/>
)}
</div>
- <Or />
+ <Or>or continue with email</Or>
</>
)}
+
<SignInEmailForm
inviteId={inviteId}
isLastUsed={lastProvider === 'email'}
/>
+
{providers.devLogin && (
<>
- <Or />
+ <Or>local development</Or>
<SignInDev inviteId={inviteId} />
</>
)}
+
+ <p className="text-center text-muted-foreground text-sm">
+ New to OpenPanel?{' '}
+ <a className="font-medium text-foreground underline" href={signUpHref}>
+ Create an account
+ </a>
+ </p>
</div>
);
}
diff --git a/apps/start/src/routes/_login.reset-password.tsx b/apps/start/src/routes/_login.reset-password.tsx
index e75b4e6e5..f3ffc1cc9 100644
--- a/apps/start/src/routes/_login.reset-password.tsx
+++ b/apps/start/src/routes/_login.reset-password.tsx
@@ -24,7 +24,7 @@ function Component() {
const { token } = Route.useSearch();
return (
- <div className="col w-full gap-8 text-left">
+ <div className="col w-full gap-8">
<ResetPasswordForm token={token} />
</div>
);
diff --git a/apps/start/src/routes/_login.tsx b/apps/start/src/routes/_login.tsx
index c288738dd..9972f4748 100644
--- a/apps/start/src/routes/_login.tsx
+++ b/apps/start/src/routes/_login.tsx
@@ -1,6 +1,5 @@
import { createFileRoute, Outlet, redirect } from '@tanstack/react-router';
-import { LoginNavbar } from '@/components/login-navbar';
-import { OnboardingLeftPanel } from '@/components/onboarding-left-panel';
+import { AuthShell } from '@/components/auth/auth-shell';
import { isSignedIn } from '@/utils/route-session';
export const Route = createFileRoute('/_login')({
@@ -14,14 +13,8 @@ export const Route = createFileRoute('/_login')({
function AuthLayout() {
return (
- <div className="relative flex min-h-screen flex-col md:grid md:grid-cols-2">
- <LoginNavbar className="relative top-auto left-auto p-4 md:absolute md:top-0 md:left-0 md:p-8" />
- <div className="hidden md:block">
- <OnboardingLeftPanel />
- </div>
- <div className="mx-auto w-full max-w-xl px-4 pt-8 pb-8 md:max-w-md md:px-8 md:pt-28">
- <Outlet />
- </div>
- </div>
+ <AuthShell>
+ <Outlet />
+ </AuthShell>
);
}
diff --git a/apps/start/src/routes/_login.verify.tsx b/apps/start/src/routes/_login.verify.tsx
index 8b04a156f..728e50231 100644
--- a/apps/start/src/routes/_login.verify.tsx
+++ b/apps/start/src/routes/_login.verify.tsx
@@ -2,6 +2,7 @@ import { useMutation } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import { useState } from 'react';
import { toast } from 'sonner';
+import { AuthHeading } from '@/components/auth/auth-shell';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
@@ -52,17 +53,15 @@ function VerifyPage() {
};
return (
- <form className="col w-full gap-8 text-left" onSubmit={handleSubmit}>
- <div>
- <h1 className="mb-2 font-bold text-3xl text-foreground">
- Two-factor authentication
- </h1>
- <p className="text-muted-foreground">
- {mode === 'totp'
+ <form className="col w-full gap-8" onSubmit={handleSubmit}>
+ <AuthHeading
+ description={
+ mode === 'totp'
? 'Enter the 6-digit code from your authenticator app.'
- : 'Enter one of your recovery codes. Each code can be used only once.'}
- </p>
- </div>
+ : 'Enter one of your recovery codes. Each code can be used only once.'
+ }
+ title="Two-factor authentication"
+ />
{mode === 'totp' ? (
<div className="col items-center gap-4">
@@ -90,11 +89,13 @@ function VerifyPage() {
</div>
) : (
<Input
+ aria-label="Recovery code"
autoCapitalize="characters"
autoFocus
disabled={mutation.isPending}
onChange={(e) => setCode(e.target.value)}
placeholder="ABCDE-FGHIJ"
+ size="xl"
value={code}
/>
)}
@@ -102,14 +103,14 @@ function VerifyPage() {
<Button
disabled={!canSubmit}
loading={mutation.isPending}
- size="lg"
+ size="xl"
type="submit"
>
Verify
</Button>
<button
- className="text-center text-muted-foreground text-sm transition-colors duration-200 hover:text-highlight hover:underline"
+ className="text-center text-muted-foreground text-sm transition-colors hover:text-foreground hover:underline"
onClick={() => {
setMode(mode === 'totp' ? 'recovery' : 'totp');
setCode('');
@@ -121,7 +122,7 @@ function VerifyPage() {
: 'Use authenticator app instead'}
</button>
<a
- className="text-center text-muted-foreground text-xs hover:underline"
+ className="text-center text-muted-foreground text-sm hover:text-foreground hover:underline"
href="/login"
>
Sign in with a different account
diff --git a/apps/start/src/routes/_public.onboarding.tsx b/apps/start/src/routes/_public.onboarding.tsx
index 2c4d2ab8a..3e2c4e19d 100644
--- a/apps/start/src/routes/_public.onboarding.tsx
+++ b/apps/start/src/routes/_public.onboarding.tsx
@@ -1,13 +1,16 @@
import { useQuery, useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute, redirect } from '@tanstack/react-router';
-import { MailIcon } from 'lucide-react';
+import { AlertCircleIcon, MailOpenIcon } from 'lucide-react';
+import { useEffect } from 'react';
import { z } from 'zod';
+import { AuthHeading } from '@/components/auth/auth-shell';
import { Or } from '@/components/auth/or';
-import { SignInGithub } from '@/components/auth/sign-in-github';
-import { SignInGoogle } from '@/components/auth/sign-in-google';
+import { SignInOAuth } from '@/components/auth/sign-in-oauth';
import { SignUpEmailForm } from '@/components/auth/sign-up-email-form';
import FullPageLoadingState from '@/components/full-page-loading-state';
+import { useAppContext } from '@/hooks/use-app-context';
import { useTRPC } from '@/integrations/trpc/react';
+import { trackFunnel } from '@/utils/funnel-tracking';
import { isSignedIn } from '@/utils/route-session';
import { createEntityTitle, PAGE_TITLES } from '@/utils/title';
@@ -46,12 +49,12 @@ export const Route = createFileRoute('/_public/onboarding')({
function Component() {
const { inviteId } = Route.useSearch();
+ const { isSelfHosted } = useAppContext();
const trpc = useTRPC();
const { data: providers } = useSuspenseQuery(
trpc.auth.providers.queryOptions()
);
const hasOAuthProviders = providers.google || providers.github;
- const hasBothOAuthProviders = providers.google && providers.github;
const { data: invite } = useQuery(
trpc.organization.getInvite.queryOptions(
{
@@ -62,102 +65,110 @@ function Component() {
}
)
);
+ useEffect(() => {
+ trackFunnel('auth_page_viewed', {
+ page: 'signup',
+ hasInvite: Boolean(inviteId),
+ inviteExpired: invite?.isExpired ?? null,
+ google: providers.google,
+ github: providers.github,
+ });
+ }, [inviteId, invite?.isExpired, providers.google, providers.github]);
+
+ const signInHref = inviteId
+ ? `/login?inviteId=${encodeURIComponent(inviteId)}`
+ : '/login';
+ const description = isSelfHosted
+ ? 'Set up your account on this OpenPanel instance.'
+ : 'Start your 30-day free trial. No credit card required.';
+
return (
- <div className="col w-full gap-8 py-4 text-left">
- <div>
- <h1 className="mb-2 font-bold text-3xl text-foreground">
- Start tracking in minutes
- </h1>
- <p className="text-muted-foreground">
- By creating an account you accept the{' '}
- <a
- className="underline transition-colors hover:text-foreground"
- href="https://openpanel.dev/terms"
- rel="noreferrer"
- target="_blank"
- >
- Terms of Service
- </a>{' '}
- and{' '}
- <a
- className="underline transition-colors hover:text-foreground"
- href="https://openpanel.dev/privacy"
- rel="noreferrer"
- target="_blank"
- >
- Privacy Policy
- </a>
- .
- </p>
- <p className="mt-3 text-muted-foreground">
- Already have an account?{' '}
- <a
- className="font-medium text-foreground underline"
- href={
- inviteId
- ? `/login?inviteId=${encodeURIComponent(inviteId)}`
- : '/login'
- }
- >
- Sign in
- </a>
- </p>
- </div>
+ <div className="col w-full gap-8">
+ <AuthHeading description={description} title="Create your account" />
{invite && !invite.isExpired && (
- <div className="mb-6 rounded-lg border border-border bg-card p-6">
- <h2 className="mb-2 font-semibold text-xl">
- Invitation to {invite.organization?.name}
- </h2>
- <p className="text-muted-foreground">
- After you have created your account, you will be added to the
- organization.
- </p>
+ <div className="row items-start gap-3 rounded-xl bg-def-200 p-4">
+ <MailOpenIcon className="mt-0.5 shrink-0 text-highlight" size={18} />
+ <div className="col gap-0.5">
+ <div className="font-medium">
+ You are invited to {invite.organization?.name}
+ </div>
+ <p className="text-muted-foreground text-sm">
+ Create your account and you will join the workspace right away.
+ </p>
+ </div>
</div>
)}
{invite?.isExpired && (
- <div className="mb-6 rounded-lg border border-destructive/20 bg-destructive/10 p-6">
- <h2 className="mb-2 font-semibold text-destructive text-xl">
- Invitation to {invite.organization?.name} has expired
- </h2>
- <p className="text-muted-foreground">
- The invitation has expired. Please contact the organization owner to
- get a new invitation.
- </p>
+ <div className="row items-start gap-3 rounded-xl bg-destructive/10 p-4">
+ <AlertCircleIcon
+ className="mt-0.5 shrink-0 text-destructive"
+ size={18}
+ />
+ <div className="col gap-0.5">
+ <div className="font-medium">
+ The invitation to {invite.organization?.name} has expired
+ </div>
+ <p className="text-muted-foreground text-sm">
+ Ask the workspace owner for a new one. You can still create an
+ account now and join later.
+ </p>
+ </div>
</div>
)}
- <div className="space-y-6">
- {hasOAuthProviders && (
- <>
- <div
- className={
- hasBothOAuthProviders
- ? 'grid grid-cols-1 gap-4 md:grid-cols-2'
- : 'grid grid-cols-1 gap-4'
- }
- >
- {providers.github && (
- <SignInGithub inviteId={inviteId} type="sign-up" />
- )}
- {providers.google && (
- <SignInGoogle inviteId={inviteId} type="sign-up" />
- )}
- </div>
- <p className="text-center text-muted-foreground text-xs">
- No credit card required · Free 30-day trial · Cancel anytime
- </p>
+ {hasOAuthProviders && (
+ <>
+ <div className="col gap-3">
+ {providers.google && (
+ <SignInOAuth
+ inviteId={inviteId}
+ provider="google"
+ type="sign-up"
+ />
+ )}
+ {providers.github && (
+ <SignInOAuth
+ inviteId={inviteId}
+ provider="github"
+ type="sign-up"
+ />
+ )}
+ </div>
+ <Or>or sign up with email</Or>
+ </>
+ )}
- <Or className="my-6" />
- </>
- )}
+ <SignUpEmailForm inviteId={inviteId} />
- <div className="mb-4 flex items-center gap-2 font-semibold text-lg">
- <MailIcon className="size-4" />
- Sign up with email
- </div>
- <SignUpEmailForm inviteId={inviteId} />
- </div>
+ <p className="text-center text-muted-foreground text-xs leading-relaxed">
+ By creating an account you agree to the{' '}
+ <a
+ className="underline hover:text-foreground"
+ href="https://openpanel.dev/terms"
+ rel="noreferrer"
+ target="_blank"
+ >
+ Terms of Service
+ </a>{' '}
+ and{' '}
+ <a
+ className="underline hover:text-foreground"
+ href="https://openpanel.dev/privacy"
+ rel="noreferrer"
+ target="_blank"
+ >
+ Privacy Policy
+ </a>
+ .
+ </p>
+
+ <p className="text-center text-muted-foreground text-sm">
+ Already have an account?{' '}
+ <a className="font-medium text-foreground underline" href={signInHref}>
+ Sign in
+ </a>
+ </p>
</div>
);
}
diff --git a/apps/start/src/routes/_public.tsx b/apps/start/src/routes/_public.tsx
index e84fc128c..ad0d8f681 100644
--- a/apps/start/src/routes/_public.tsx
+++ b/apps/start/src/routes/_public.tsx
@@ -1,21 +1,14 @@
import { createFileRoute, Outlet } from '@tanstack/react-router';
-import { LoginNavbar } from '@/components/login-navbar';
-import { OnboardingLeftPanel } from '@/components/onboarding-left-panel';
+import { AuthShell } from '@/components/auth/auth-shell';
export const Route = createFileRoute('/_public')({
- component: OnboardingLayout,
+ component: PublicLayout,
});
-function OnboardingLayout() {
+function PublicLayout() {
return (
- <div className="relative flex min-h-screen flex-col md:grid md:grid-cols-2">
- <LoginNavbar className="relative top-auto left-auto p-4 md:absolute md:top-0 md:left-0 md:p-8" />
- <div className="hidden md:block">
- <OnboardingLeftPanel />
- </div>
- <div className="mx-auto w-full max-w-xl px-4 pt-8 pb-8 md:max-w-md md:px-8 md:pt-28">
- <Outlet />
- </div>
- </div>
+ <AuthShell>
+ <Outlet />
+ </AuthShell>
);
}
diff --git a/apps/start/src/routes/_steps.onboarding.$projectId.connect.tsx b/apps/start/src/routes/_steps.onboarding.$projectId.connect.tsx
index 36d60e477..92aff3459 100644
--- a/apps/start/src/routes/_steps.onboarding.$projectId.connect.tsx
+++ b/apps/start/src/routes/_steps.onboarding.$projectId.connect.tsx
@@ -1,23 +1,34 @@
import { useQuery } from '@tanstack/react-query';
-import { createFileRoute, redirect } from '@tanstack/react-router';
-import { CopyIcon, DownloadIcon, LockIcon, XIcon } from 'lucide-react';
-import { ButtonContainer } from '@/components/button-container';
-import CopyInput from '@/components/forms/copy-input';
+import { createFileRoute, Link, redirect } from '@tanstack/react-router';
+import { XIcon } from 'lucide-react';
+import { useEffect, useRef } from 'react';
import { FullPageEmptyState } from '@/components/full-page-empty-state';
import FullPageLoadingState from '@/components/full-page-loading-state';
-import ConnectWeb from '@/components/onboarding/connect-web';
-import { Button, LinkButton } from '@/components/ui/button';
-import { isRealClientSecret, useClientSecret } from '@/hooks/use-client-secret';
+import { ClientCredentials } from '@/components/onboarding/client-credentials';
+import {
+ FirstEventStatus,
+ useFirstEvents,
+} from '@/components/onboarding/first-event-status';
+import { InstallGuide } from '@/components/onboarding/install-guide';
+import type { SnippetContext } from '@/components/onboarding/install-snippets';
+import { InstallTroubleshootingDialog } from '@/components/onboarding/install-troubleshooting';
+import { McpConnect } from '@/components/onboarding/mcp-connect';
+import { OnboardingHeading } from '@/components/onboarding/onboarding-heading';
+import { LinkButton } from '@/components/ui/button';
+import { useAppContext } from '@/hooks/use-app-context';
+import {
+ isRealClientSecret,
+ useClientSecret,
+ useMcpToken,
+} from '@/hooks/use-client-secret';
import { useTRPC } from '@/integrations/trpc/react';
-import { clipboard } from '@/utils/clipboard';
+import { trackFunnel, useSecondsOnStep } from '@/utils/funnel-tracking';
import { isSignedIn } from '@/utils/route-session';
import { createEntityTitle, PAGE_TITLES } from '@/utils/title';
export const Route = createFileRoute('/_steps/onboarding/$projectId/connect')({
head: () => ({
- meta: [
- { title: createEntityTitle('Connect data', PAGE_TITLES.ONBOARDING) },
- ],
+ meta: [{ title: createEntityTitle('Install', PAGE_TITLES.ONBOARDING) }],
}),
beforeLoad: async ({ context }) => {
if (!(await isSignedIn(context))) {
@@ -38,13 +49,45 @@ export const Route = createFileRoute('/_steps/onboarding/$projectId/connect')({
function Component() {
const { projectId } = Route.useParams();
const trpc = useTRPC();
+ const { apiUrl, isSelfHosted } = useAppContext();
const { data: project } = useQuery(
trpc.project.getProjectWithClients.queryOptions({ projectId })
);
- const client = project?.clients[0];
- const [secret] = useClientSecret();
+ const client = project?.clients.find(
+ (candidate) => candidate.type === 'write'
+ );
+ const [secret, secretReady] = useClientSecret(projectId);
+ const [mcpToken, mcpTokenReady] = useMcpToken(projectId);
+ const keysReady = secretReady && mcpTokenReady;
+ const secondsOnStep = useSecondsOnStep();
+ const { events, isVerified } = useFirstEvents(projectId, secondsOnStep);
+ const hasSecret = isRealClientSecret(secret);
+
+ // Once per visit, after session storage has been read so the key flags
+ // are real; the keys do not change while the page is open.
+ const viewedProjectId = useRef<string | null>(null);
+ useEffect(() => {
+ if (!keysReady || viewedProjectId.current === projectId) {
+ return;
+ }
+ viewedProjectId.current = projectId;
+ trackFunnel('onboarding_connect_viewed', {
+ projectId,
+ types: project?.types ?? [],
+ hasSecret,
+ hasMcpToken: Boolean(mcpToken),
+ });
+ }, [keysReady, projectId, project?.types, hasSecret, mcpToken]);
+
+ const openDashboard = (from: 'status' | 'footer') =>
+ trackFunnel('onboarding_dashboard_opened', {
+ projectId,
+ verified: isVerified,
+ from,
+ secondsOnStep: secondsOnStep(),
+ });
- if (!client) {
+ if (!(project && client)) {
return (
<FullPageEmptyState
description="The project you are looking for does not exist. Please reload the page."
@@ -54,90 +97,103 @@ function Component() {
);
}
- // The secret only exists in this browser session right after creation (we
- // store a hash server-side). Never derive the MCP token — or print secret
- // lines — from the placeholder: that produces valid-looking broken values.
- const hasSecret = isRealClientSecret(secret);
- const mcpToken = hasSecret ? btoa(`${client.id}:${secret}`) : null;
- const credentials = [
- `CLIENT_ID=${client.id}`,
- hasSecret && `CLIENT_SECRET=${secret}`,
- mcpToken && `MCP_TOKEN=${mcpToken}`,
- ]
- .filter(Boolean)
- .join('\n');
- const download = () => {
- const blob = new Blob([credentials], { type: 'text/plain' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = 'credentials.txt';
- a.click();
+ // Secrets only exist in the browser session right after creation (the
+ // server stores hashes). Snippets fall back to a placeholder without them.
+ const context: SnippetContext = {
+ clientId: client.id,
+ clientSecret: hasSecret ? secret : null,
+ apiUrl: isSelfHosted ? apiUrl : null,
};
+ const dashboard = {
+ to: '/$organizationId/$projectId',
+ params: { organizationId: project.organizationId, projectId: project.id },
+ } as const;
+
+ // One DOM copy of the sidebar: under the heading on small screens, the
+ // right column on large ones. The second grid row is 1fr so the sidebar's
+ // extra height lands below the left stack instead of between its blocks.
+ const sidebarPlacement =
+ 'col gap-5 lg:col-start-2 lg:row-span-2 lg:row-start-1';
return (
- <div className="flex min-h-0 flex-1 flex-col">
- <div className="scrollbar-thin flex-1 overflow-y-auto">
- <div className="col gap-4 p-4">
- <div className="col gap-2">
- <div className="row items-center justify-between gap-4">
- <div className="flex items-center gap-2 font-bold text-xl capitalize">
- <LockIcon className="size-4" />
- Client credentials
- </div>
- <div className="row gap-2">
- <Button
- icon={CopyIcon}
- onClick={() => clipboard(credentials)}
- variant="outline"
- >
- Copy all
- </Button>
- <Button
- icon={DownloadIcon}
- onClick={() => download()}
- variant="outline"
- >
- Save
- </Button>
- </div>
- </div>
- <div className="col gap-3">
- <CopyInput label="Client ID" value={client.id} />
- {hasSecret && <CopyInput label="Client secret" value={secret} />}
- {mcpToken && (
- <div className="w-full min-w-0">
- <CopyInput label="MCP token" value={mcpToken} />
- <p className="mt-1 text-muted-foreground text-sm">
- Authenticates the MCP server (base64-encoded client ID and
- secret).
- </p>
- </div>
- )}
- {!hasSecret && (
- <p className="text-muted-foreground text-sm">
- Your client secret (and the MCP token derived from it) is only
- shown once, right after the client is created. If you need it
- again, create a new client under Settings → Clients.
- </p>
- )}
- </div>
- </div>
- <div className="-mx-4 h-px bg-muted" />
- <ConnectWeb client={client} />
+ <div className="flex flex-col gap-10 lg:grid lg:grid-cols-[minmax(0,1fr)_21rem] lg:grid-rows-[auto_1fr] lg:items-start lg:gap-x-12">
+ <OnboardingHeading
+ className="lg:col-start-1"
+ description={
+ <>
+ Add the snippet to{' '}
+ <strong className="text-foreground">{project.name}</strong> and we
+ confirm the first event right here. Your keys stay on the side; you
+ can also do this later from the dashboard.
+ </>
+ }
+ title="Install OpenPanel"
+ />
+ <aside className={sidebarPlacement}>
+ <FirstEventStatus
+ events={events}
+ help={
+ <InstallTroubleshootingDialog context={context} project={project} />
+ }
+ >
+ {isVerified && (
+ <LinkButton
+ className="w-full"
+ onClick={() => openDashboard('status')}
+ size="lg"
+ {...dashboard}
+ >
+ Open dashboard
+ </LinkButton>
+ )}
+ </FirstEventStatus>
+ <ClientCredentials
+ clientId={client.id}
+ clientSecret={context.clientSecret}
+ mcpToken={mcpToken}
+ projectId={project.id}
+ />
+ <McpConnect
+ apiUrl={apiUrl}
+ mcpToken={mcpToken}
+ organizationId={project.organizationId}
+ projectId={project.id}
+ />
+ </aside>
+ <div className="col gap-10 lg:col-start-1">
+ <InstallGuide
+ context={context}
+ projectId={project.id}
+ projectName={project.name}
+ projectTypes={project.types}
+ />
+ <div className="row items-center justify-between gap-4 border-t pt-8">
+ {isVerified ? (
+ <span className="text-muted-foreground">You are all set.</span>
+ ) : (
+ <Link
+ className="text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
+ onClick={() =>
+ trackFunnel('onboarding_skipped', {
+ projectId,
+ secondsOnStep: secondsOnStep(),
+ })
+ }
+ {...dashboard}
+ >
+ Skip for now, I will install later
+ </Link>
+ )}
+ <LinkButton
+ onClick={() => openDashboard('footer')}
+ size="xl"
+ variant={isVerified ? 'default' : 'outline'}
+ {...dashboard}
+ >
+ Open dashboard
+ </LinkButton>
</div>
</div>
- <ButtonContainer className="mt-0 flex-shrink-0 border-t bg-background p-4">
- <div />
- <LinkButton
- className="min-w-28 self-start"
- href={'/onboarding/$projectId/verify'}
- params={{ projectId }}
- size="lg"
- >
- Next
- </LinkButton>
- </ButtonContainer>
</div>
);
}
diff --git a/apps/start/src/routes/_steps.onboarding.$projectId.verify.tsx b/apps/start/src/routes/_steps.onboarding.$projectId.verify.tsx
index c5368a5e8..e4d17b65b 100644
--- a/apps/start/src/routes/_steps.onboarding.$projectId.verify.tsx
+++ b/apps/start/src/routes/_steps.onboarding.$projectId.verify.tsx
@@ -1,134 +1,11 @@
-import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { createFileRoute, Link, redirect } from '@tanstack/react-router';
-import { BoxSelectIcon } from 'lucide-react';
-import { useEffect } from 'react';
-import { ButtonContainer } from '@/components/button-container';
-import { FullPageEmptyState } from '@/components/full-page-empty-state';
-import FullPageLoadingState from '@/components/full-page-loading-state';
-import VerifyListener from '@/components/onboarding/onboarding-verify-listener';
-import { VerifyFaq } from '@/components/onboarding/verify-faq';
-import { LinkButton } from '@/components/ui/button';
-import useWS from '@/hooks/use-ws';
-import { useTRPC } from '@/integrations/trpc/react';
-import { cn } from '@/lib/utils';
-import { op } from '@/utils/op';
-import { isSignedIn } from '@/utils/route-session';
-import { createEntityTitle, PAGE_TITLES } from '@/utils/title';
+import { createFileRoute, redirect } from '@tanstack/react-router';
+// The verify step merged into connect; old links and emails still land here.
export const Route = createFileRoute('/_steps/onboarding/$projectId/verify')({
- head: () => ({
- meta: [{ title: createEntityTitle('Verify', PAGE_TITLES.ONBOARDING) }],
- }),
- beforeLoad: async ({ context }) => {
- if (!(await isSignedIn(context))) {
- throw redirect({ to: '/onboarding' });
- }
+ beforeLoad: ({ params }) => {
+ throw redirect({
+ to: '/onboarding/$projectId/connect',
+ params: { projectId: params.projectId },
+ });
},
- component: Component,
- loader: async ({ context, params }) => {
- await context.queryClient.prefetchQuery(
- context.trpc.project.getProjectWithClients.queryOptions({
- projectId: params.projectId,
- })
- );
- },
- pendingComponent: FullPageLoadingState,
});
-
-function Component() {
- const { projectId } = Route.useParams();
- const trpc = useTRPC();
- const queryClient = useQueryClient();
- const { data: events } = useQuery(
- trpc.event.events.queryOptions(
- { projectId },
- {
- // The live websocket below flips the verifier instantly; this poll is
- // only a fallback for when the socket can't connect.
- refetchInterval: 10_000,
- }
- )
- );
- // Refetch the event list the moment an event arrives instead of waiting for
- // the next poll — same channel the in-app live event feed uses.
- useWS(`/live/events/${projectId}`, () => {
- queryClient.invalidateQueries(trpc.event.events.queryFilter({ projectId }));
- });
- const isVerified = events?.data && events.data.length > 0;
-
- useEffect(() => {
- op.track('onboarding_verify_viewed', { projectId });
- }, [projectId]);
-
- useEffect(() => {
- if (isVerified) {
- op.track('onboarding_first_event_verified', { projectId });
- }
- }, [isVerified, projectId]);
- const { data: project } = useQuery(
- trpc.project.getProjectWithClients.queryOptions({ projectId })
- );
-
- if (!project) {
- return (
- <FullPageEmptyState icon={BoxSelectIcon} title="Project not found" />
- );
- }
-
- const client = project.clients[0];
- if (!client) {
- return <FullPageEmptyState icon={BoxSelectIcon} title="Client not found" />;
- }
-
- return (
- <div className="flex min-h-0 flex-1 flex-col">
- <div className="scrollbar-thin flex-1 overflow-y-auto">
- <div className="col gap-8 p-4">
- <VerifyListener events={events?.data ?? []} />
-
- <VerifyFaq project={project} />
- </div>
- </div>
- <ButtonContainer className="mt-0 flex-shrink-0 border-t bg-background p-4">
- <LinkButton
- className="min-w-28 self-start"
- href={`/onboarding/${project.id}/connect`}
- size="lg"
- variant={'secondary'}
- >
- Back
- </LinkButton>
-
- <div className="flex items-center gap-8">
- {!isVerified && (
- <Link
- className="text-muted-foreground underline"
- params={{
- organizationId: project!.organizationId,
- projectId: project!.id,
- }}
- to={'/$organizationId/$projectId'}
- >
- Skip for now
- </Link>
- )}
-
- <LinkButton
- className={cn(
- 'min-w-28 self-start',
- !isVerified && 'pointer-events-none select-none opacity-20'
- )}
- params={{
- organizationId: project!.organizationId,
- projectId: project!.id,
- }}
- size="lg"
- to={'/$organizationId/$projectId'}
- >
- Your dashboard
- </LinkButton>
- </div>
- </ButtonContainer>
- </div>
- );
-}
diff --git a/apps/start/src/routes/_steps.onboarding.project.tsx b/apps/start/src/routes/_steps.onboarding.project.tsx
index 51975844e..67e2889ef 100644
--- a/apps/start/src/routes/_steps.onboarding.project.tsx
+++ b/apps/start/src/routes/_steps.onboarding.project.tsx
@@ -4,20 +4,22 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router';
import {
BuildingIcon,
+ CheckIcon,
+ type LucideIcon,
MonitorIcon,
ServerIcon,
SmartphoneIcon,
} from 'lucide-react';
-import { useEffect, useId, useState } from 'react';
+import { useEffect, useId, useRef, useState } from 'react';
import {
Controller,
+ type SubmitErrorHandler,
type SubmitHandler,
useForm,
useWatch,
} from 'react-hook-form';
import { z } from 'zod';
import AnimateHeight from '@/components/animate-height';
-import { ButtonContainer } from '@/components/button-container';
import {
fieldMessageId,
InputWithLabel,
@@ -25,13 +27,18 @@ import {
} from '@/components/forms/input-with-label';
import TagInput from '@/components/forms/tag-input';
import FullPageLoadingState from '@/components/full-page-loading-state';
+import { OnboardingHeading } from '@/components/onboarding/onboarding-heading';
import { Button } from '@/components/ui/button';
import { Combobox } from '@/components/ui/combobox';
import { Label } from '@/components/ui/label';
-import { useClientSecret } from '@/hooks/use-client-secret';
+import { rememberOnboardingKeys } from '@/hooks/use-client-secret';
import { handleError, useTRPC } from '@/integrations/trpc/react';
import { cn } from '@/utils/cn';
-import { op } from '@/utils/op';
+import {
+ failureReason,
+ trackFunnel,
+ useSecondsOnStep,
+} from '@/utils/funnel-tracking';
import { isSignedIn } from '@/utils/route-session';
const validateSearch = z.object({
@@ -67,23 +74,83 @@ export const Route = createFileRoute('/_steps/onboarding/project')({
});
type IForm = z.infer<typeof zOnboardingProject>;
+type ProjectType = 'website' | 'app' | 'backend';
+
+const PROJECT_TYPES: {
+ key: ProjectType;
+ label: string;
+ description: string;
+ Icon: LucideIcon;
+}[] = [
+ {
+ key: 'website',
+ label: 'Website',
+ description: 'Pages, traffic sources, funnels',
+ Icon: MonitorIcon,
+ },
+ {
+ key: 'app',
+ label: 'App',
+ description: 'iOS, Android, React Native',
+ Icon: SmartphoneIcon,
+ },
+ {
+ key: 'backend',
+ label: 'Backend / API',
+ description: 'Server-side events',
+ Icon: ServerIcon,
+ },
+];
+
+const TIMEZONES = ['UTC', ...Intl.supportedValuesOf('timeZone')].map(
+ (zone) => ({ value: zone, label: zone })
+);
+
+function toOrigin(value: string) {
+ const trimmed = value.trim();
+ if (!trimmed || trimmed === '*' || /^https?:\/\//.test(trimmed)) {
+ return trimmed;
+ }
+ return `https://${trimmed}`;
+}
function Component() {
- const workspaceId = useId();
+ const workspaceFieldId = useId();
const trpc = useTRPC();
const queryClient = useQueryClient();
const { data: organizations } = useQuery(
trpc.organization.list.queryOptions(undefined, { initialData: [] })
);
- const [, setSecret] = useClientSecret();
const navigate = useNavigate();
+ const secondsOnStep = useSecondsOnStep();
const mutation = useMutation(
trpc.onboarding.project.mutationOptions({
- onError: handleError,
- onSuccess(res) {
- op.track('onboarding_project_created', { projectId: res.projectId });
+ onError(error) {
+ trackFunnel('onboarding_project_create_failed', {
+ reason: failureReason(error),
+ });
+ handleError(error);
+ },
+ onSuccess(res, input) {
+ trackFunnel('onboarding_project_created', {
+ projectId: res.projectId,
+ types: [
+ input.website && 'website',
+ input.app && 'app',
+ input.backend && 'backend',
+ ].filter((type): type is string => Boolean(type)),
+ hasDomain: Boolean(input.domain),
+ extraDomains: Math.max(0, (input.cors ?? []).length - 1),
+ createdWorkspace: Boolean(input.organization),
+ secondsOnStep: secondsOnStep(),
+ });
queryClient.invalidateQueries(trpc.organization.list.queryFilter());
- setSecret(res.secret);
+ if (res.projectId) {
+ rememberOnboardingKeys(res.projectId, {
+ clientSecret: res.secret,
+ mcpToken: res.mcpToken,
+ });
+ }
navigate({
to: '/onboarding/$projectId/connect',
params: {
@@ -108,30 +175,37 @@ function Component() {
},
});
- const isWebsite = useWatch({
- name: 'website',
- control: form.control,
- });
-
- const isApp = useWatch({
- name: 'app',
- control: form.control,
- });
+ const [isWebsite, isApp, isBackend, projectName, domain, workspaceName] =
+ useWatch({
+ control: form.control,
+ name: ['website', 'app', 'backend', 'project', 'domain', 'organization'],
+ });
+ const selectedTypes: Record<ProjectType, boolean> = {
+ website: isWebsite,
+ app: isApp,
+ backend: isBackend,
+ };
- const isBackend = useWatch({
- name: 'backend',
- control: form.control,
- });
+ const hasWorkspaces = organizations.length > 0;
+ const [useExistingWorkspace, setUseExistingWorkspace] = useState(true);
+ const createsWorkspace = !(hasWorkspaces && useExistingWorkspace);
+ const [workspaceEdited, setWorkspaceEdited] = useState(false);
+ const [showWorkspaceSettings, setShowWorkspaceSettings] = useState(false);
+ const [showCorsInput, setShowCorsInput] = useState(false);
+ const autoOrigin = useRef<string | null>(null);
- const domain = useWatch({
- name: 'domain',
- control: form.control,
- });
+ useEffect(() => {
+ trackFunnel('onboarding_project_viewed', { hasWorkspaces });
+ }, [hasWorkspaces]);
- const [showCorsInput, setShowCorsInput] = useState(false);
- const [createNewOrg, setCreateNewOrg] = useState(false);
- const canUseExistingWorkspace = organizations.length > 0;
- const showCreateForm = createNewOrg || organizations.length === 0;
+ // The workspace is the billing unit, not something a new user should have
+ // to name before seeing a single chart: it follows the project name until
+ // they edit it themselves.
+ useEffect(() => {
+ if (!workspaceEdited) {
+ form.setValue('organization', projectName);
+ }
+ }, [projectName, workspaceEdited, form]);
useEffect(() => {
if (!isWebsite) {
@@ -141,272 +215,322 @@ function Component() {
}
}, [isWebsite, form]);
- const onSubmit: SubmitHandler<IForm> = (values) => {
- mutation.mutate(values);
- };
-
useEffect(() => {
form.clearErrors();
- }, [isWebsite, isApp, isBackend]);
+ }, [isWebsite, isApp, isBackend, form]);
+
+ // `enforceAccess` checks any organizationId key that is present, even an
+ // undefined one, so each branch sends only its own workspace field.
+ const onSubmit: SubmitHandler<IForm> = ({
+ organization,
+ organizationId,
+ ...values
+ }) => {
+ if (createsWorkspace) {
+ mutation.mutate({ ...values, organization });
+ return;
+ }
+ if (!organizationId) {
+ form.setError('organizationId', { message: 'Select a workspace' });
+ return;
+ }
+ mutation.mutate({ ...values, organizationId });
+ };
+ const onInvalid: SubmitErrorHandler<IForm> = (errors) => {
+ trackFunnel('onboarding_project_invalid', {
+ fields: Object.keys(errors),
+ });
+ };
+
+ const typeError =
+ form.formState.errors.website?.message ??
+ form.formState.errors.app?.message ??
+ form.formState.errors.backend?.message;
return (
- <form
- className="flex min-h-0 flex-1 flex-col"
- onSubmit={form.handleSubmit(onSubmit)}
- >
- <div className="scrollbar-thin flex-1 overflow-y-auto p-4">
- <div className="row mb-4 gap-2 rounded-lg bg-muted p-1">
- <button
- className={cn(
- 'rounded-md px-3 py-2 font-medium text-sm transition-colors',
- createNewOrg || !canUseExistingWorkspace
- ? 'bg-background text-foreground shadow-sm'
- : 'text-muted-foreground hover:text-foreground'
- )}
- onClick={() => setCreateNewOrg(true)}
- type="button"
- >
- Create new workspace
- </button>
- <button
- className={cn(
- 'rounded-md px-3 py-2 font-medium text-sm transition-colors',
- !createNewOrg && canUseExistingWorkspace
- ? 'bg-background text-foreground shadow-sm'
- : 'text-muted-foreground',
- canUseExistingWorkspace
- ? 'hover:text-foreground'
- : 'cursor-not-allowed opacity-60'
- )}
- disabled={!canUseExistingWorkspace}
- onClick={() => setCreateNewOrg(false)}
- type="button"
- >
- Use existing workspace
- </button>
+ <form className="col" onSubmit={form.handleSubmit(onSubmit, onInvalid)}>
+ <OnboardingHeading
+ className="mb-10"
+ description="A project is one website, app or service you want to track. You can add more later."
+ title={hasWorkspaces ? 'Create a project' : 'Create your first project'}
+ />
+
+ {hasWorkspaces && (
+ <div className="col mb-10 gap-3">
+ <Label className="mb-0 text-base">Workspace</Label>
+ <div className="grid grid-cols-2 gap-1 rounded-xl bg-def-200 p-1 dark:bg-def-300">
+ {[
+ { label: 'Use existing workspace', existing: true },
+ { label: 'Create new workspace', existing: false },
+ ].map((option) => (
+ <button
+ aria-pressed={useExistingWorkspace === option.existing}
+ className={cn(
+ 'rounded-lg px-4 py-2.5 font-medium transition-colors',
+ useExistingWorkspace === option.existing
+ ? 'bg-background shadow-sm'
+ : 'text-muted-foreground hover:text-foreground'
+ )}
+ key={option.label}
+ onClick={() => {
+ trackFunnel('onboarding_workspace_mode_changed', {
+ mode: option.existing ? 'existing' : 'new',
+ });
+ setUseExistingWorkspace(option.existing);
+ }}
+ type="button"
+ >
+ {option.label}
+ </button>
+ ))}
+ </div>
+ <AnimateHeight open={!createsWorkspace}>
+ <Controller
+ control={form.control}
+ name="organizationId"
+ render={({ field, formState }) => (
+ <WithLabel
+ error={formState.errors.organizationId?.message}
+ id={workspaceFieldId}
+ label="Which workspace?"
+ >
+ <Combobox
+ aria-describedby={
+ formState.errors.organizationId
+ ? fieldMessageId(workspaceFieldId)
+ : undefined
+ }
+ className="w-full"
+ error={formState.errors.organizationId?.message}
+ icon={BuildingIcon}
+ id={workspaceFieldId}
+ items={organizations.map((item) => ({
+ label: item.name,
+ value: item.id,
+ }))}
+ onChange={field.onChange}
+ placeholder="Select workspace"
+ size="xl"
+ value={field.value}
+ variant="input"
+ />
+ </WithLabel>
+ )}
+ />
+ </AnimateHeight>
</div>
- <div className="grid gap-4 md:grid-cols-2">
- {showCreateForm ? (
- <>
+ )}
+
+ <InputWithLabel
+ autoFocus
+ className="mb-10"
+ error={form.formState.errors.project?.message}
+ label="Project name"
+ placeholder="Acme"
+ size="xl"
+ {...form.register('project')}
+ />
+
+ <div className="col mb-10 gap-3">
+ <Label className="mb-0 text-base">What are you tracking?</Label>
+ <div className="grid gap-3 sm:grid-cols-3">
+ {PROJECT_TYPES.map(({ key, label, description, Icon }) => {
+ const active = selectedTypes[key];
+ return (
+ <button
+ aria-pressed={active}
+ className={cn(
+ 'col relative items-start gap-3 rounded-xl p-4 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
+ active
+ ? 'bg-foreground text-background'
+ : 'bg-def-200 hover:bg-def-300 dark:bg-def-300 dark:hover:bg-def-400/60'
+ )}
+ key={key}
+ onClick={() => {
+ trackFunnel('onboarding_project_type_toggled', {
+ type: key,
+ selected: !active,
+ });
+ form.setValue(key, !active, { shouldValidate: true });
+ }}
+ type="button"
+ >
+ <Icon size={22} strokeWidth={1.75} />
+ <span className="col gap-0.5">
+ <span className="font-medium">{label}</span>
+ <span
+ className={cn(
+ 'text-xs',
+ active ? 'text-background/70' : 'text-muted-foreground'
+ )}
+ >
+ {description}
+ </span>
+ </span>
+ {active && (
+ <CheckIcon className="absolute top-4 right-4" size={16} />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ <p className="text-muted-foreground text-sm">
+ Pick everything that applies. It only decides which install guides we
+ show first.
+ </p>
+ {typeError && (
+ <p className="text-destructive text-sm">
+ Pick at least one thing to track
+ </p>
+ )}
+ </div>
+
+ <AnimateHeight open={isWebsite}>
+ <div className="col gap-3 pb-10">
+ <InputWithLabel
+ error={form.formState.errors.domain?.message}
+ hint="Browser events are only accepted from this domain."
+ inputMode="url"
+ label="Website URL"
+ placeholder="acme.com"
+ size="xl"
+ {...form.register('domain')}
+ onBlur={(event) => {
+ const value = toOrigin(event.target.value);
+ if (!value) {
+ return;
+ }
+ form.setValue('domain', value, { shouldValidate: true });
+ // The origin added for the website follows the website; the
+ // ones the user added by hand stay.
+ const cors = form.getValues().cors;
+ const previous = autoOrigin.current;
+ autoOrigin.current = value;
+ if (previous && cors.includes(previous)) {
+ form.setValue(
+ 'cors',
+ cors.map((origin) => (origin === previous ? value : origin))
+ );
+ return;
+ }
+ if (cors.length === 0) {
+ form.setValue('cors', [value]);
+ }
+ }}
+ />
+ {domain && (
+ <button
+ className="self-start text-muted-foreground text-sm hover:text-foreground hover:underline"
+ onClick={() => {
+ trackFunnel('onboarding_extra_domains_toggled', {
+ open: !showCorsInput,
+ });
+ setShowCorsInput((open) => !open);
+ }}
+ type="button"
+ >
+ Also track other domains (staging, localhost…)
+ </button>
+ )}
+ <AnimateHeight open={showCorsInput}>
+ <Controller
+ control={form.control}
+ name="cors"
+ render={({ field }) => (
+ <WithLabel
+ error={form.formState.errors.cors?.message}
+ label="Allowed domains"
+ >
+ <TagInput
+ {...field}
+ error={form.formState.errors.cors?.message}
+ onChange={(values: string[]) =>
+ field.onChange(values.map(toOrigin))
+ }
+ placeholder="Add a domain and press Enter"
+ renderTag={(tag: string) =>
+ tag === '*' ? 'Any domain' : tag
+ }
+ value={field.value ?? []}
+ />
+ </WithLabel>
+ )}
+ />
+ </AnimateHeight>
+ </div>
+ </AnimateHeight>
+
+ <AnimateHeight open={createsWorkspace}>
+ <div className="col mb-10 gap-3 rounded-xl border p-5">
+ <div className="row items-center justify-between gap-4">
+ <div className="text-muted-foreground text-sm">
+ Workspace{' '}
+ <span className="font-medium text-foreground">
+ {workspaceName || 'named after the project'}
+ </span>{' '}
+ · {form.getValues('timezone')}
+ </div>
+ <button
+ className="shrink-0 text-sm underline-offset-4 hover:underline"
+ onClick={() => {
+ trackFunnel('onboarding_workspace_settings_toggled', {
+ open: !showWorkspaceSettings,
+ });
+ setShowWorkspaceSettings((open) => !open);
+ }}
+ type="button"
+ >
+ {showWorkspaceSettings ? 'Done' : 'Change'}
+ </button>
+ </div>
+ <AnimateHeight open={showWorkspaceSettings}>
+ <div className="grid gap-4 pt-3 sm:grid-cols-2">
<InputWithLabel
error={form.formState.errors.organization?.message}
- info="This is the name of your workspace. It can be anything you like."
+ hint="Your team and billing live here."
label="Workspace name"
- placeholder="Eg. The Music Company"
- {...form.register('organization')}
+ placeholder="Acme Inc"
+ size="xl"
+ {...form.register('organization', {
+ onChange: () => setWorkspaceEdited(true),
+ })}
/>
<Controller
control={form.control}
name="timezone"
render={({ field }) => (
- <WithLabel label="Timezone">
+ <WithLabel
+ hint="Used for daily and weekly reports."
+ label="Timezone"
+ >
<Combobox
className="w-full"
- items={['UTC', ...Intl.supportedValuesOf('timeZone')].map(
- (item) => ({
- value: item,
- label: item,
- })
- )}
+ items={TIMEZONES}
onChange={field.onChange}
placeholder="Select timezone"
searchable
+ size="xl"
value={field.value}
variant="input"
/>
</WithLabel>
)}
/>
- </>
- ) : (
- <div className="col-span-2">
- <Controller
- control={form.control}
- name="organizationId"
- render={({ field, formState }) => {
- return (
- <WithLabel
- error={formState.errors.organizationId?.message}
- id={workspaceId}
- label="Workspace"
- >
- <Combobox
- aria-describedby={
- formState.errors.organizationId
- ? fieldMessageId(workspaceId)
- : undefined
- }
- className="w-full"
- error={formState.errors.organizationId?.message}
- icon={BuildingIcon}
- id={workspaceId}
- items={
- organizations
- .filter((item) => item.id)
- .map((item) => ({
- label: item.name,
- value: item.id,
- })) ?? []
- }
- onChange={field.onChange}
- placeholder="Select workspace"
- value={field.value}
- variant="input"
- />
- </WithLabel>
- );
- }}
- />
- </div>
- )}
- <InputWithLabel
- error={form.formState.errors.project?.message}
- label="Your first project name"
- placeholder="Eg. The Music App"
- {...form.register('project')}
- className="col-span-2"
- />
- </div>
- <div className="mt-4">
- <Label className="mb-2">What are you tracking?</Label>
- <div className="grid grid-cols-3 gap-3">
- {[
- {
- key: 'website' as const,
- label: 'Website',
- Icon: MonitorIcon,
- active: isWebsite,
- },
- {
- key: 'app' as const,
- label: 'App',
- Icon: SmartphoneIcon,
- active: isApp,
- },
- {
- key: 'backend' as const,
- label: 'Backend / API',
- Icon: ServerIcon,
- active: isBackend,
- },
- ].map(({ key, label, Icon, active }) => (
- <button
- className={cn(
- 'flex flex-col items-center gap-2 rounded-lg border-2 p-4 transition-colors',
- active
- ? 'border-primary bg-primary/5 text-primary'
- : 'border-border text-muted-foreground hover:border-primary/40'
- )}
- key={key}
- onClick={() => {
- form.setValue(key, !active, { shouldValidate: true });
- }}
- type="button"
- >
- <Icon size={24} />
- <span className="font-medium text-sm">{label}</span>
- </button>
- ))}
- </div>
- {(form.formState.errors.website?.message ||
- form.formState.errors.app?.message ||
- form.formState.errors.backend?.message) && (
- <p className="mt-2 text-destructive text-sm">
- At least one type must be selected
- </p>
- )}
- <AnimateHeight open={isWebsite}>
- <div className="mt-4">
- <InputWithLabel
- label="Domain"
- placeholder="example.com"
- {...form.register('domain')}
- error={form.formState.errors.domain?.message}
- onBlur={(e) => {
- const raw = e.target.value.trim();
- if (!raw) {
- return;
- }
-
- const hasProtocol =
- raw.startsWith('http://') || raw.startsWith('https://');
- const value = hasProtocol ? raw : `https://${raw}`;
-
- form.setValue('domain', value, { shouldValidate: true });
- if (form.getValues().cors.length === 0) {
- form.setValue('cors', [value]);
- }
- }}
- />
- {domain && (
- <>
- <button
- className="mt-2 text-muted-foreground text-sm hover:text-foreground"
- onClick={() => setShowCorsInput((open) => !open)}
- type="button"
- >
- All events from{' '}
- <span className="font-medium text-foreground">
- {domain}
- </span>{' '}
- will be allowed. Do you want to allow any other?
- </button>
- <AnimateHeight open={showCorsInput}>
- <div className="mt-3">
- <Controller
- control={form.control}
- name="cors"
- render={({ field }) => (
- <WithLabel label="Allowed domains">
- <TagInput
- {...field}
- error={form.formState.errors.cors?.message}
- onChange={(newValue: string[]) => {
- field.onChange(
- newValue.map((item: string) => {
- const trimmed = item.trim();
- if (
- trimmed.startsWith('http://') ||
- trimmed.startsWith('https://') ||
- trimmed === '*'
- ) {
- return trimmed;
- }
- return `https://${trimmed}`;
- })
- );
- }}
- placeholder="Accept events from these domains"
- renderTag={(tag: string) =>
- tag === '*'
- ? 'Accept events from any domains'
- : tag
- }
- value={field.value ?? []}
- />
- </WithLabel>
- )}
- />
- </div>
- </AnimateHeight>
- </>
- )}
</div>
</AnimateHeight>
</div>
- </div>
+ </AnimateHeight>
- <ButtonContainer className="mt-0 flex-shrink-0 border-t bg-background p-4">
- <div />
+ <div className="row justify-end border-t pt-8">
<Button
- className="min-w-28 self-start"
+ className="min-w-44"
loading={mutation.isPending}
- size="lg"
+ size="xl"
type="submit"
>
- Next
+ Create project
</Button>
- </ButtonContainer>
+ </div>
</form>
);
}
diff --git a/apps/start/src/routes/_steps.tsx b/apps/start/src/routes/_steps.tsx
index 40d5e810a..975e18210 100644
--- a/apps/start/src/routes/_steps.tsx
+++ b/apps/start/src/routes/_steps.tsx
@@ -1,6 +1,14 @@
-import { createFileRoute, Outlet, useMatchRoute } from '@tanstack/react-router';
-import { SkeletonDashboard } from '@/components/skeleton-dashboard';
+import { createFileRoute, Outlet } from '@tanstack/react-router';
+import { LogOutIcon } from 'lucide-react';
+import { LogoSquare } from '@/components/logo';
+import {
+ STEP_NAMES,
+ useOnboardingShellConfig,
+} from '@/components/onboarding/onboarding-shell';
+import { Button } from '@/components/ui/button';
+import { useLogout } from '@/hooks/use-logout';
import { cn } from '@/utils/cn';
+import { trackFunnel } from '@/utils/funnel-tracking';
import { createEntityTitle, PAGE_TITLES } from '@/utils/title';
export const Route = createFileRoute('/_steps')({
@@ -11,63 +19,65 @@ export const Route = createFileRoute('/_steps')({
});
function OnboardingLayout() {
+ const logout = useLogout();
+ const { step, wide } = useOnboardingShellConfig();
+ const width = wide ? 'max-w-5xl' : 'max-w-2xl';
return (
- <div className="relative flex min-h-screen items-center justify-center p-4">
- <div className="fixed inset-0 hidden md:block">
- <SkeletonDashboard />
- <div className="fixed inset-0 z-10 bg-def-100/50" />
- </div>
- <div className="relative z-10 flex max-h-[calc(100vh-2rem)] w-full max-w-xl flex-col overflow-hidden rounded-lg border bg-background shadow-muted/50 shadow-xl">
- <div className="sticky top-0 z-10 flex-shrink-0 border-b bg-background">
- <Progress />
- </div>
- <div className="flex min-h-0 flex-1 flex-col">
- <Outlet />
- </div>
- </div>
+ <div className="min-h-screen bg-background">
+ <header
+ className={cn(
+ 'mx-auto flex w-full items-center justify-between px-6 py-6',
+ width
+ )}
+ >
+ <a className="row items-center gap-2.5 font-medium" href="/">
+ <LogoSquare className="size-8 shrink-0" />
+ <span>OpenPanel</span>
+ </a>
+ <Button
+ icon={LogOutIcon}
+ loading={logout.isPending}
+ onClick={() => {
+ trackFunnel('onboarding_signed_out', {
+ step: STEP_NAMES[step - 1] ?? String(step),
+ });
+ logout.mutate();
+ }}
+ size="sm"
+ variant="ghost"
+ >
+ Sign out
+ </Button>
+ </header>
+ <main className={cn('mx-auto w-full px-6 pt-8 pb-24', width)}>
+ <StepIndicator current={step} />
+ <Outlet />
+ </main>
</div>
);
}
-function Progress() {
- const steps = [
- {
- name: 'Create project',
- match: '/onboarding/project',
- },
- {
- name: 'Connect data',
- match: '/onboarding/$projectId/connect',
- },
- {
- name: 'Verify',
- match: '/onboarding/$projectId/verify',
- },
- ];
- const matchRoute = useMatchRoute();
-
- const currentStep = steps.find((step) =>
- matchRoute({
- // @ts-expect-error
- from: step.match,
- fuzzy: false,
- })
- );
-
+function StepIndicator({ current }: { current: number }) {
+ const currentIndex = current - 1;
return (
- <div className="row w-full flex-shrink-0 items-center justify-between gap-4 p-4">
- <div className="font-bold">{currentStep?.name ?? 'Onboarding'}</div>
- <div className="row gap-4">
- {steps.map((step) => (
- <div
+ <nav aria-label="Onboarding progress" className="col mb-8 gap-3">
+ <div className="text-muted-foreground text-sm tabular-nums">
+ Step {current} of {STEP_NAMES.length}
+ </div>
+ <ol className="row gap-2">
+ {STEP_NAMES.map((name, index) => (
+ <li
+ aria-current={index === currentIndex ? 'step' : undefined}
className={cn(
- 'h-2 w-10 rounded-full bg-muted',
- currentStep === step && 'w-20 bg-primary'
+ 'h-1 flex-1 rounded-full transition-colors',
+ index <= currentIndex ? 'bg-foreground' : 'bg-def-300'
)}
- key={step.match}
- />
+ key={name}
+ >
+ <span className="sr-only">{name}</span>
+ </li>
))}
- </div>
- </div>
+ </ol>
+ </nav>
);
}
diff --git a/apps/start/src/utils/funnel-tracking.ts b/apps/start/src/utils/funnel-tracking.ts
new file mode 100644
index 000000000..7a3bf134b
--- /dev/null
+++ b/apps/start/src/utils/funnel-tracking.ts
@@ -0,0 +1,76 @@
+import { useCallback, useRef } from 'react';
+import { op } from '@/utils/op';
+
+/**
+ * Everything the sign-up → first-event funnel reports about itself, so the
+ * flow can be judged on data later. One name per decision a visitor makes;
+ * properties say which option they picked and how long the step took.
+ *
+ * Funnel order: auth_page_viewed → auth_provider_clicked →
+ * auth_signup_succeeded | auth_signin_succeeded → onboarding_project_viewed →
+ * onboarding_project_created → onboarding_connect_viewed →
+ * onboarding_first_event_verified | onboarding_skipped →
+ * onboarding_dashboard_opened. Everything else explains the gaps.
+ */
+export type FunnelEvent =
+ | 'auth_page_viewed'
+ | 'auth_provider_clicked'
+ | 'auth_form_invalid'
+ | 'auth_signup_succeeded'
+ | 'auth_signup_failed'
+ | 'auth_signin_succeeded'
+ | 'auth_signin_failed'
+ | 'auth_forgot_password_clicked'
+ | 'onboarding_project_viewed'
+ | 'onboarding_workspace_mode_changed'
+ | 'onboarding_workspace_settings_toggled'
+ | 'onboarding_project_type_toggled'
+ | 'onboarding_extra_domains_toggled'
+ | 'onboarding_project_invalid'
+ | 'onboarding_project_created'
+ | 'onboarding_project_create_failed'
+ | 'onboarding_connect_viewed'
+ | 'onboarding_install_method_selected'
+ | 'onboarding_framework_selected'
+ | 'onboarding_framework_guide_clicked'
+ | 'onboarding_snippet_copied'
+ | 'onboarding_ai_framework_selected'
+ | 'onboarding_ai_prompt_copied'
+ | 'onboarding_ai_prompt_opened_in_cursor'
+ | 'onboarding_credentials_copied'
+ | 'onboarding_mcp_connect_toggled'
+ | 'onboarding_mcp_connect_clicked'
+ | 'onboarding_mcp_settings_clicked'
+ | 'onboarding_troubleshooting_toggled'
+ | 'onboarding_allowed_domains_updated'
+ | 'onboarding_test_curl_copied'
+ | 'onboarding_support_link_clicked'
+ | 'onboarding_assistant_opened'
+ | 'onboarding_first_event_verified'
+ | 'onboarding_skipped'
+ | 'onboarding_dashboard_opened'
+ | 'onboarding_signed_out';
+
+export type FunnelProperties = Record<
+ string,
+ string | number | boolean | null | undefined | string[]
+>;
+
+export function trackFunnel(name: FunnelEvent, properties?: FunnelProperties) {
+ op.track(name, properties);
+}
+
+/** Seconds since the step mounted, attached to the events that end a step. */
+export function useSecondsOnStep() {
+ const mountedAt = useRef(Date.now());
+ return useCallback(
+ () => Math.round((Date.now() - mountedAt.current) / 1000),
+ []
+ );
+}
+
+/** The error text when the API refused, trimmed so it groups in reports. */
+export function failureReason(error: unknown): string {
+ const message = error instanceof Error ? error.message : String(error);
+ return message.slice(0, 80);
+}
diff --git a/packages/core/src/modules/assistant/assistant.constants.ts b/packages/core/src/modules/assistant/assistant.constants.ts
index 1b320b568..82a73c1f4 100644
--- a/packages/core/src/modules/assistant/assistant.constants.ts
+++ b/packages/core/src/modules/assistant/assistant.constants.ts
@@ -135,6 +135,7 @@ export const CHAT_HINT_PAGES = [
'events',
'insights',
'realtime',
+ 'onboarding',
] as const;
const MAX_ID_LENGTH = 128;
diff --git a/packages/core/src/modules/assistant/src/prompt.ts b/packages/core/src/modules/assistant/src/prompt.ts
index e0cc0568c..a2715483c 100644
--- a/packages/core/src/modules/assistant/src/prompt.ts
+++ b/packages/core/src/modules/assistant/src/prompt.ts
@@ -96,7 +96,11 @@ function hintSection(hint?: ChatLaunchHint): string {
return '';
}
const lines: string[] = [];
- if (hint.page) {
+ if (hint.page === 'onboarding') {
+ lines.push(
+ 'The user came from the onboarding install step, right after creating this project, and probably has no events yet. If they ask why events are missing: for a project with a domain run diagnose_tracking on it; otherwise check what has reached the project with the data tools and walk through the client id, the secret for server and app SDKs, and allowed origins. Name the one or two findings that matter and what to change.'
+ );
+ } else if (hint.page) {
lines.push(`The user opened the chat from the ${hint.page} page.`);
}
if (hint.startDate && hint.endDate) {
diff --git a/packages/core/src/modules/auth/auth.constants.test.ts b/packages/core/src/modules/auth/auth.constants.test.ts
index 6e41b853f..f553ffc2d 100644
--- a/packages/core/src/modules/auth/auth.constants.test.ts
+++ b/packages/core/src/modules/auth/auth.constants.test.ts
@@ -43,7 +43,6 @@ describe('passwords are bounded before argon2 sees them', () => {
lastName: 'B',
password: huge,
- confirmPassword: huge,
}).success
).toBe(false);
expect(
@@ -88,7 +87,6 @@ describe('emails and names', () => {
const base = {
password: 'longenough',
- confirmPassword: 'longenough',
};
expect(
zSignUpEmail.safeParse({ ...base, firstName: ' ', lastName: 'B' })
diff --git a/packages/core/src/modules/auth/auth.constants.ts b/packages/core/src/modules/auth/auth.constants.ts
index 320bb0b1c..c80e7af81 100644
--- a/packages/core/src/modules/auth/auth.constants.ts
+++ b/packages/core/src/modules/auth/auth.constants.ts
@@ -15,7 +15,10 @@ export const zProvider = z.enum(['email', 'google', 'github']);
* a person types; anyone who set a longer one before this existed resets by
* email, which asks only for an address.
*/
-export const zPassword = z.string().min(8).max(MAX_PASSWORD);
+export const zPassword = z
+ .string()
+ .min(8, 'Use at least 8 characters')
+ .max(MAX_PASSWORD);
/** Length first, so a huge string fails before the address is parsed. */
const zEmail = z.string().max(MAX_EMAIL).email();
@@ -35,19 +38,13 @@ export type ISignInEmail = z.infer<typeof zSignInEmail>;
export const zSignInDev = z.object({ inviteId: zShortId.nullish() });
-export const zSignUpEmail = z
- .object({
- firstName: zPersonName,
- lastName: zPersonName,
- email: zEmail,
- password: zPassword,
- confirmPassword: zPassword,
- inviteId: zShortId.nullish(),
- })
- .refine((data) => data.password === data.confirmPassword, {
- path: ['confirmPassword'],
- message: 'Passwords do not match',
- });
+export const zSignUpEmail = z.object({
+ firstName: zPersonName,
+ lastName: zPersonName,
+ email: zEmail,
+ password: zPassword,
+ inviteId: zShortId.nullish(),
+});
export type ISignUpEmail = z.infer<typeof zSignUpEmail>;
export const zResetPassword = z.object({
diff --git a/packages/core/src/modules/client/client.service.ts b/packages/core/src/modules/client/client.service.ts
index 1cecd73f9..4f4da574a 100644
--- a/packages/core/src/modules/client/client.service.ts
+++ b/packages/core/src/modules/client/client.service.ts
@@ -2,11 +2,10 @@
// client rather than the scope: its L1 LRU has to survive across calls, and the
// ingest hot path passes the scope it holds on each call.
-import crypto from 'node:crypto';
import type { Client, Prisma } from '@openpanel/db/src/prisma-client';
import { cacheablePerDb, type DbScope } from '../../cacheable-per-deps';
import type { ServiceDeps, Services } from '../../services';
-import { hashClientSecret } from '../../shared/client-secret';
+import { hashClientSecret, newClientSecret } from '../../shared/client-secret';
export type IServiceClient = Client;
@@ -154,7 +153,7 @@ export function createClientService(
}
}
- const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
+ const secret = newClientSecret();
const client = await deps.db.client.create({
data: {
organizationId,
diff --git a/packages/core/src/modules/onboarding/onboarding.constants.ts b/packages/core/src/modules/onboarding/onboarding.constants.ts
index 4698793ad..93f9fc7b3 100644
--- a/packages/core/src/modules/onboarding/onboarding.constants.ts
+++ b/packages/core/src/modules/onboarding/onboarding.constants.ts
@@ -5,7 +5,7 @@ export const zOnboardingProject = z
.object({
organization: z.string().optional(),
organizationId: z.string().optional(),
- project: z.string().min(3),
+ project: z.string().min(3, 'Use at least 3 characters'),
domain: z.string().url().or(z.literal('').or(z.null())),
cors: z.array(z.string()).default([]),
website: z.boolean(),
diff --git a/packages/core/src/modules/onboarding/onboarding.service.create.test.ts b/packages/core/src/modules/onboarding/onboarding.service.create.test.ts
new file mode 100644
index 000000000..d9b359e91
--- /dev/null
+++ b/packages/core/src/modules/onboarding/onboarding.service.create.test.ts
@@ -0,0 +1,90 @@
+// Project creation: one write client for the SDKs and one read client for MCP,
+// whose token is the only thing the caller ever sees of it.
+
+import { afterAll, beforeAll, expect, mock, test } from 'bun:test';
+import { testCoreConfig } from '../../../test/config-fixture';
+
+interface CreateArgs {
+ data: Record<string, unknown>;
+}
+
+const clientCreate = mock(async ({ data }: CreateArgs) => ({
+ id: `client_${String(data.type)}`,
+ ...data,
+}));
+const dbMock = {
+ organization: {
+ create: mock(async ({ data }: CreateArgs) => ({ ...data })),
+ },
+ member: { create: mock(async () => ({})) },
+ project: { create: mock(async ({ data }: CreateArgs) => ({ ...data })) },
+ client: { create: clientCreate },
+ // Both Prisma forms: the array of operations the organization uses, and
+ // the callback the project and its clients run in.
+ $transaction: mock(
+ (operations: Promise<unknown>[] | ((tx: unknown) => Promise<unknown>)) =>
+ typeof operations === 'function'
+ ? operations(dbMock)
+ : Promise.all(operations)
+ ),
+};
+const deps = {
+ db: dbMock,
+ config: testCoreConfig(),
+} as unknown as import('../../services').ServiceDeps;
+
+const realSlugId = { ...(await import('../../slug-id')) };
+mock.module('../../slug-id', () => ({
+ ...realSlugId,
+ getId: mock(async (_deps: unknown, _table: string, name: string) =>
+ name.toLowerCase().replace(/\s+/g, '-')
+ ),
+}));
+const realUserService = { ...(await import('../user/user.service')) };
+mock.module('../user/user.service', () => ({
+ ...realUserService,
+ getUserById: mock(async () => ({ email: '[email protected]' })),
+}));
+
+afterAll(() => {
+ mock.module('../../slug-id', () => realSlugId);
+ mock.module('../user/user.service', () => realUserService);
+});
+
+let createOnboardingProject: typeof import('./onboarding.service').createOnboardingProject;
+
+beforeAll(async () => {
+ ({ createOnboardingProject } = await import('./onboarding.service'));
+});
+
+test('creates a write client for events and a read client whose token works for MCP', async () => {
+ const result = await createOnboardingProject(
+ deps,
+ {
+ organization: 'Acme',
+ project: 'Acme site',
+ domain: 'https://acme.com',
+ cors: [],
+ website: true,
+ app: false,
+ backend: false,
+ },
+ 'user_1'
+ );
+
+ expect(clientCreate).toHaveBeenCalledTimes(2);
+ const created = clientCreate.mock.calls.map(([call]) => call.data);
+ expect(created.map((data) => data.type)).toEqual(['write', 'read']);
+ expect(created.map((data) => data.name)).toEqual([
+ 'Acme site Client',
+ 'Acme site MCP client',
+ ]);
+ expect(created.every((data) => data.projectId === 'acme-site')).toBe(true);
+
+ expect(result.type).toBe('write');
+ expect(result.secret).toMatch(/^sec_[0-9a-f]{20}$/);
+ const decoded = Buffer.from(result.mcpToken, 'base64').toString();
+ expect(decoded).toMatch(/^client_read:sec_[0-9a-f]{20}$/);
+ // Its own secret, never the write client's.
+ expect(decoded.endsWith(result.secret)).toBe(false);
+});
diff --git a/packages/core/src/modules/onboarding/onboarding.service.ts b/packages/core/src/modules/onboarding/onboarding.service.ts
index 801800882..9183d52f8 100644
--- a/packages/core/src/modules/onboarding/onboarding.service.ts
+++ b/packages/core/src/modules/onboarding/onboarding.service.ts
@@ -1,10 +1,9 @@
-import crypto from 'node:crypto';
import { getRecommendedPlan } from '@openpanel/payments';
import { stripTrailingSlash } from '@openpanel/shared';
import { format } from 'date-fns';
import type { Logger } from '../../logger';
import type { ServiceDeps, Services } from '../../services';
-import { hashClientSecret } from '../../shared/client-secret';
+import { hashClientSecret, newClientSecret } from '../../shared/client-secret';
import { getId } from '../../slug-id';
import {
runSequence,
@@ -103,8 +102,13 @@ export interface CreateOnboardingProjectResult {
projectId: string | null;
type: string;
secret: string;
+ /** Token for the read-only MCP client created alongside; only ever returned here. */
+ mcpToken: string;
}
+const toMcpToken = (clientId: string, secret: string) =>
+ Buffer.from(`${clientId}:${secret}`).toString('base64');
+
export async function createOnboardingProject(
deps: ServiceDeps,
input: IOnboardingProject,
@@ -140,29 +144,52 @@ export async function createOnboardingProject(
const db = deps.db;
- const project = await db.project.create({
- data: {
- id: await getId(deps, 'project', input.project),
- name: input.project,
- organizationId: organization.id,
- types,
- domain: input.domain ? stripTrailingSlash(input.domain) : null,
- cors: cors.map((c) => stripTrailingSlash(c)),
- },
- });
+ const projectId = await getId(deps, 'project', input.project);
+ const secret = newClientSecret();
+ // MCP only accepts read and root clients, so the write client's token
+ // would never work. A read client scoped to this project is created up
+ // front; the dashboard shows its token once and never its id or secret.
+ const mcpSecret = newClientSecret();
+ const [hashedSecret, hashedMcpSecret] = await Promise.all([
+ hashClientSecret(secret),
+ hashClientSecret(mcpSecret),
+ ]);
- const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
- const client = await db.client.create({
- data: {
- name: `${project.name} Client`,
- organizationId: organization.id,
- projectId: project.id,
- type: 'write',
- secret: await hashClientSecret(secret),
- },
+ // One transaction: a project without its clients would leave the user
+ // with an error and no credentials to retry with.
+ const { client, mcpClient } = await db.$transaction(async (tx) => {
+ const project = await tx.project.create({
+ data: {
+ id: projectId,
+ name: input.project,
+ organizationId: organization.id,
+ types,
+ domain: input.domain ? stripTrailingSlash(input.domain) : null,
+ cors: cors.map((c) => stripTrailingSlash(c)),
+ },
+ });
+ const createdClient = await tx.client.create({
+ data: {
+ name: `${project.name} Client`,
+ organizationId: organization.id,
+ projectId: project.id,
+ type: 'write',
+ secret: hashedSecret,
+ },
+ });
+ const createdMcpClient = await tx.client.create({
+ data: {
+ name: `${project.name} MCP client`,
+ organizationId: organization.id,
+ projectId: project.id,
+ type: 'read',
+ secret: hashedMcpSecret,
+ },
+ });
+ return { client: createdClient, mcpClient: createdMcpClient };
});
- return { ...client, secret };
+ return { ...client, secret, mcpToken: toMcpToken(mcpClient.id, mcpSecret) };
}
// The onboarding email drip cron. The `organization.onboarding` column
diff --git a/packages/core/src/modules/project/project.service.ts b/packages/core/src/modules/project/project.service.ts
index 9e864ede9..35e97c096 100644
--- a/packages/core/src/modules/project/project.service.ts
+++ b/packages/core/src/modules/project/project.service.ts
@@ -1,4 +1,3 @@
-import crypto from 'node:crypto';
import { sql } from '@openpanel/db/src/clickhouse/sql';
import type {
Prisma,
@@ -13,7 +12,7 @@ import type { ServiceDeps, Services } from '../../services';
import { getMemberProjectGrants } from '../../shared/access-lookups';
import { convertClickhouseDateToJs } from '../../shared/ch-dates';
import { TABLE_NAMES } from '../../shared/ch-tables';
-import { hashClientSecret } from '../../shared/client-secret';
+import { hashClientSecret, newClientSecret } from '../../shared/client-secret';
import { getId } from '../../slug-id';
import { getClientByIdCached } from '../client/client.service';
import type { IProjectFilters } from './project.constants';
@@ -257,6 +256,8 @@ export async function getProjectActivationStatus(
export interface CreatedProjectClient {
id: string;
secret: string;
+ /** Always a write client: the dashboard shows an MCP token only for read and root. */
+ type: 'write';
}
export async function listProjectsForOrganization(
@@ -307,7 +308,7 @@ export function createProjectService(
project: IServiceProject;
client: CreatedProjectClient | null;
}> {
- const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
+ const secret = newClientSecret();
const project = await deps.db.project.create({
data: {
id: await getId(deps, 'project', input.name),
@@ -346,7 +347,9 @@ export function createProjectService(
return {
project,
- client: project.clients[0] ? { id: project.clients[0].id, secret } : null,
+ client: project.clients[0]
+ ? { id: project.clients[0].id, secret, type: 'write' }
+ : null,
};
}
diff --git a/packages/core/src/shared/client-secret.ts b/packages/core/src/shared/client-secret.ts
index 62280d506..298bfdf56 100644
--- a/packages/core/src/shared/client-secret.ts
+++ b/packages/core/src/shared/client-secret.ts
@@ -1,3 +1,4 @@
+import crypto from 'node:crypto';
import { verify as verifyArgon2 } from '@node-rs/argon2';
import {
hashPassword as hashScrypt,
@@ -29,3 +30,7 @@ export async function verifyClientSecret(
return false;
}
}
+
+/** A fresh client secret in the `sec_` format every service hands out. */
+export const newClientSecret = () =>
+ `sec_${crypto.randomBytes(10).toString('hex')}`;
diff --git a/packages/sdks/_info/frameworks.tsx b/packages/sdks/_info/frameworks.tsx
index 451be8a9a..98a0fb226 100644
--- a/packages/sdks/_info/frameworks.tsx
+++ b/packages/sdks/_info/frameworks.tsx
@@ -6,6 +6,8 @@ import { KotlinIcon } from './icons/kotlin-icon';
import { LaravelIcon } from './icons/laravel-icon';
import { NextjsIcon } from './icons/nextjs-icon';
import { NodeIcon } from './icons/node-icon';
+import { NuxtIcon } from './icons/nuxt-icon';
+import { PythonIcon } from './icons/python-icon';
import { ReactIcon } from './icons/react-icon';
import { RemixIcon } from './icons/remix-icon';
import { RestIcon } from './icons/rest-icon';
@@ -14,13 +16,13 @@ import { RustIcon } from './icons/rust-icon';
import { SwiftIcon } from './icons/swift-icon';
import { VueIcon } from './icons/vue-icon';
-export type Framework = {
+export interface Framework {
key: string;
IconComponent: React.ComponentType<React.SVGProps<SVGSVGElement>>;
name: string;
href: string;
type: ('website' | 'app' | 'backend')[];
-};
+}
export const frameworks: Framework[] = [
{
@@ -30,13 +32,6 @@ export const frameworks: Framework[] = [
href: 'https://openpanel.dev/docs/sdks/script',
type: ['website'],
},
- {
- key: 'react',
- IconComponent: ReactIcon,
- name: 'React',
- href: 'https://openpanel.dev/docs/sdks/react',
- type: ['website'],
- },
{
key: 'nextjs',
IconComponent: NextjsIcon,
@@ -45,10 +40,10 @@ export const frameworks: Framework[] = [
type: ['website'],
},
{
- key: 'remix',
- IconComponent: RemixIcon,
- name: 'Remix',
- href: 'https://openpanel.dev/docs/sdks/remix',
+ key: 'react',
+ IconComponent: ReactIcon,
+ name: 'React',
+ href: 'https://openpanel.dev/docs/sdks/react',
type: ['website'],
},
{
@@ -58,6 +53,13 @@ export const frameworks: Framework[] = [
href: 'https://openpanel.dev/docs/sdks/vue',
type: ['website'],
},
+ {
+ key: 'nuxt',
+ IconComponent: NuxtIcon,
+ name: 'Nuxt',
+ href: 'https://openpanel.dev/docs/sdks/nuxt',
+ type: ['website'],
+ },
{
key: 'astro',
IconComponent: AstroIcon,
@@ -65,6 +67,13 @@ export const frameworks: Framework[] = [
href: 'https://openpanel.dev/docs/sdks/astro',
type: ['website'],
},
+ {
+ key: 'remix',
+ IconComponent: RemixIcon,
+ name: 'Remix',
+ href: 'https://openpanel.dev/docs/sdks/remix',
+ type: ['website'],
+ },
{
key: 'rest',
IconComponent: RestIcon,
@@ -93,6 +102,13 @@ export const frameworks: Framework[] = [
href: 'https://openpanel.dev/docs/sdks/express',
type: ['backend'],
},
+ {
+ key: 'python',
+ IconComponent: PythonIcon,
+ name: 'Python',
+ href: 'https://openpanel.dev/docs/sdks/python',
+ type: ['backend'],
+ },
{
key: 'laravel',
IconComponent: LaravelIcon,
diff --git a/packages/sdks/_info/icons/nuxt-icon.tsx b/packages/sdks/_info/icons/nuxt-icon.tsx
new file mode 100644
index 000000000..ea4332b6f
--- /dev/null
+++ b/packages/sdks/_info/icons/nuxt-icon.tsx
@@ -0,0 +1,19 @@
+import type { IconProps } from './types';
+
+export function NuxtIcon({ className }: IconProps) {
+ return (
+ <svg
+ className={className}
+ fill="none"
+ height="512"
+ viewBox="0 0 512 512"
+ width="512"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M286.4 416h190.1c6 0 12-1.6 17.2-4.6 5.2-3 9.6-7.4 12.6-12.6s4.6-11.1 4.6-17.2-1.6-12-4.6-17.2L378.6 143.3c-3-5.2-7.4-9.6-12.6-12.6s-11.1-4.6-17.2-4.6-12 1.6-17.2 4.6c-5.2 3-9.6 7.4-12.6 12.6l-32.6 56.5-63.8-110.6c-3-5.2-7.4-9.6-12.6-12.6-5.2-3-11.1-4.6-17.2-4.6s-12 1.6-17.2 4.6c-5.2 3-9.6 7.4-12.6 12.6L4.6 364.4C1.6 369.6 0 375.5 0 381.6s1.6 12 4.6 17.2c3 5.2 7.4 9.6 12.6 12.6 5.2 3 11.1 4.6 17.2 4.6h119.3c47.3 0 82.1-20.8 106.1-61.3l58.2-100.9 31.2-54 93.6 162.1H286.4V416zM151.8 361.9H68.6L193.3 145.8l62.2 108-41.7 72.3c-15.9 26.2-34 35.8-62 35.8z"
+ fill="currentColor"
+ />
+ </svg>
+ );
+}