Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(analytics): log signup receipts and Console onboarding (#3282)

zombee04dc6d02cefa1
diff --git a/apps/api/README.md b/apps/api/README.md
index 1f3d9ada7..7bb097509 100644
--- a/apps/api/README.md
+++ b/apps/api/README.md
@@ -1252,6 +1252,20 @@ to report truncation. Include requested/exception outcomes plus successes for `o
`user.login` and `user.registration`; ordinary success records confirm requests already listed.
Only requested outcomes contribute to operation totals. Preview presence remains anonymous and sampled.
+### Console onboarding analytics
+
+Filter `console_onboarding_step` by `action` for Welcome and Quickstart interactions. Use `selection` to
+break down the saved Use Case, deployment mode, SDK tab or template. Welcome Starter subscription
+confirmation records `starter_sub_click`. The Quickstart template picker records
+`quickstart_template_create_click` when the user clicks Create Box.
+
+Welcome form clicks record `org_name_submit_click` or `use_case_submit_click`. A successful Use Case
+save separately records `use_case_selected` with the saved option. Use Case and Credits record separate
+Back actions. Check card status, Explore with BoxLite and Start quickstart also have distinct actions.
+
+The organization ID is the `organization` group. These events use the existing Console consent checks,
+and entries before an active grant are not replayed.
+
### Signup attribution
The Console keeps the first eligible source in the current tab for up to 24 hours. At a signup entry it checks `utm_source`, `ref`, the hostname forwarded by the website, then the browser’s external HTTP(S) referrer. An untagged link from X can produce `x.com` or `t.co`, depending on the hostname the browser supplies.
@@ -1264,6 +1278,13 @@ Signup attribution uses the same **Product analytics** choice as Console page vi
The API accepts one eligible claim per account, including across UTC midnight and concurrent tabs. It marks the claim in the existing consent row and submits `signup_attributed` with `signup.source` and `signup.source_type` for best-effort delivery. A delivery failure after the claim can therefore leave the signup unattributed.
+Filter the API's info logs by `event.name = signup.attribution`. The `received` outcome lists the
+validated source and source type, plus medium and campaign when present. It is emitted before eligibility
+checks, so a receipt can be followed by a skip or no PostHog delivery.
+
+The `skipped` outcome includes a `reason`, `sending` marks the HTTP request start, and `delivered`
+includes the observed PostHog 2xx `http_status`. Visibility in PostHog queries depends on subsequent ingestion.
+
A refusal, account switch or expiry discards the pending source. Earlier page visits and clicks are never replayed.
### Who asked: the operation context
diff --git a/apps/api/src/analytics/console-analytics.controller.spec.ts b/apps/api/src/analytics/console-analytics.controller.spec.ts
index d66193b19..e37a142e1 100644
--- a/apps/api/src/analytics/console-analytics.controller.spec.ts
+++ b/apps/api/src/analytics/console-analytics.controller.spec.ts
@@ -1,17 +1,33 @@
/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
import { createServer } from 'node:http'
import { AddressInfo } from 'node:net'
+import { Writable } from 'node:stream'
import { ForbiddenException, INestApplication, ValidationPipe } from '@nestjs/common'
import { Test } from '@nestjs/testing'
+import { logs as otelLogs } from '@opentelemetry/api-logs'
+import { InMemoryLogRecordExporter, LoggerProvider, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs'
import { generateKeyPair, exportJWK, SignJWT } from 'jose'
+import { Logger as PinoLogger, LoggerModule } from 'nestjs-pino'
import { JwtStrategy } from '../auth/jwt.strategy'
+import { swapMessageAndObject } from '../common/utils/pino.util'
import { ConsoleAnalyticsController } from './console-analytics.controller'
import { AnalyticsConsentService } from './services/analytics-consent.service'
import { AnalyticsService } from './services/analytics.service'
+// Exercise the same Pino instrumentation used by the API bootstrap.
+jest.mock('pino', () => {
+ const { PinoInstrumentation } = jest.requireActual('@opentelemetry/instrumentation-pino')
+ const [definition] = new PinoInstrumentation().getModuleDefinitions()
+ return definition.patch(jest.requireActual('pino'), jest.requireActual('pino/package.json').version)
+})
+
describe('Console analytics HTTP boundary', () => {
const org = 'a98b01ab-0a84-4b06-955a-2cfacf733f09'
const capture = jest.fn()
+ const analytics = { capture, enabled: true }
+ const logs: string[] = []
+ const exporter = new InMemoryLogRecordExporter()
+ const provider = new LoggerProvider({ processors: [new SimpleLogRecordProcessor(exporter)] })
const decide = jest.fn(async (_id: string, allowed: boolean) => ({ allowed }))
const consent = {
claimSignupOrganization: jest.fn(async (): Promise<string | undefined> => undefined),
@@ -34,6 +50,7 @@ describe('Console analytics HTTP boundary', () => {
})
beforeAll(async () => {
+ otelLogs.setGlobalLoggerProvider(provider)
const keys = await generateKeyPair('RS256')
const jwk = { ...(await exportJWK(keys.publicKey)), kid: 'test', alg: 'RS256', use: 'sig' }
jwks.on('request', (_req, res) =>
@@ -55,31 +72,109 @@ describe('Console analytics HTTP boundary', () => {
.setExpirationTime('5m')
.sign(keys.privateKey)
const module = await Test.createTestingModule({
+ imports: [
+ LoggerModule.forRoot({
+ pinoHttp: [
+ {
+ autoLogging: false,
+ quietReqLogger: true,
+ hooks: { logMethod: swapMessageAndObject },
+ },
+ new Writable({
+ write: (chunk, _encoding, done) => {
+ logs.push(chunk.toString())
+ done()
+ },
+ }),
+ ],
+ }),
+ ],
controllers: [ConsoleAnalyticsController],
providers: [
{ provide: JwtStrategy, useValue: strategy },
{ provide: AnalyticsConsentService, useValue: consent },
- { provide: AnalyticsService, useValue: { capture, enabled: true } },
+ { provide: AnalyticsService, useValue: analytics },
],
}).compile()
app = module.createNestApplication()
+ app.useLogger(app.get(PinoLogger))
app.useGlobalPipes(new ValidationPipe({ transform: true }))
await app.listen(0, '127.0.0.1')
base = await app.getUrl()
})
afterAll(async () => {
await app?.close()
+ await provider.shutdown()
+ otelLogs.disable()
await new Promise<void>((r) => jwks.close(() => r()))
})
it('attributes an eligible signup once by identity and rejects incomplete or expired evidence', async () => {
const path = '/analytics/signup-source'
- const input = { source: 't.co', kind: 'referrer', enteredAt: new Date(Date.now() - 60_000).toISOString() }
+ const input = {
+ source: 'www.linkedin.com',
+ kind: 'referrer',
+ enteredAt: new Date(Date.now() - 60_000).toISOString(),
+ }
expect((await request(path, 'POST', undefined, input)).status).toBe(401)
- expect((await request(path, 'POST', bearer, { ...input, source: 'https://t.co/private' })).status).toBe(400)
- expect((await request(path, 'POST', bearer, { ...input, enteredAt: '2000-01-01T00:00:00Z' })).status).toBe(204)
+ expect(
+ (await request(path, 'POST', bearer, { ...input, source: 'https://www.linkedin.com/private-path' })).status,
+ ).toBe(400)
+ expect(
+ (await request(path, 'POST', bearer, { ...input, enteredAt: new Date(Date.now() + 60_000).toISOString() }))
+ .status,
+ ).toBe(204)
+ expect((await request(path, 'POST', bearer, { ...input, medium: 'bad label' })).status).toBe(400)
+ const utm = {
+ ...input,
+ source: 'LinkedIn',
+ kind: 'utm',
+ medium: 'social',
+ campaign: 'winter_26',
+ content: 'private-content',
+ }
+ analytics.enabled = false
+ try {
+ expect((await request(path, 'POST', bearer, { ...input, enteredAt: '2000-01-01T00:00:00Z' })).status).toBe(204)
+ expect((await request(path, 'POST', bearer, utm)).status).toBe(204)
+ } finally {
+ analytics.enabled = true
+ }
expect(consent.claimSignupOrganization).not.toHaveBeenCalled()
+ expect(capture).not.toHaveBeenCalled()
expect((await request(path, 'POST', bearer, input)).status).toBe(204)
expect(capture).not.toHaveBeenCalled()
+ const signupLogs = logs
+ .flatMap((line) => line.trim().split('\n'))
+ .map((line) => JSON.parse(line))
+ .filter((entry) => entry['event.name'] === 'signup.attribution')
+ const hostReceipt = { outcome: 'received', 'signup.source_type': 'referrer', 'signup.source': 'www.linkedin.com' }
+ expect(signupLogs).toMatchObject([
+ { outcome: 'skipped', reason: 'invalid_source' },
+ hostReceipt,
+ { outcome: 'skipped', reason: 'invalid_entry_time' },
+ hostReceipt,
+ { outcome: 'skipped', reason: 'expired_entry_time' },
+ {
+ outcome: 'received',
+ 'signup.source': 'linkedin',
+ 'signup.source_type': 'utm',
+ 'signup.medium': 'social',
+ 'signup.campaign': 'winter_26',
+ },
+ { outcome: 'skipped', reason: 'analytics_disabled' },
+ hostReceipt,
+ { outcome: 'skipped', reason: 'claim_not_accepted' },
+ ])
+ const otlp = exporter
+ .getFinishedLogRecords()
+ .map((entry) => entry.attributes)
+ .filter((fields) => fields['event.name'] === 'signup.attribution')
+ const receiptFields = (rows: Record<string, unknown>[]) =>
+ rows
+ .filter((row) => row.outcome === 'received')
+ .map((row) => Object.fromEntries(Object.entries(row).filter(([key]) => key.startsWith('signup.'))))
+ expect(receiptFields(otlp)).toEqual(receiptFields(signupLogs))
+ expect(JSON.stringify([...signupLogs, ...otlp])).not.toMatch(/private-content|private-path/)
consent.claimSignupOrganization.mockResolvedValueOnce(org)
const midnight = new Date().setUTCHours(0, 0, 0, 0)
const source = { ...input, enteredAt: new Date(midnight - 60_000).toISOString() }
@@ -92,6 +187,9 @@ describe('Console analytics HTTP boundary', () => {
} finally {
clock.mockRestore()
}
+ expect(
+ exporter.getFinishedLogRecords().filter((entry) => entry.body === 'signup.attribution received'),
+ ).toHaveLength(6)
expect(consent.claimSignupOrganization).toHaveBeenCalledTimes(3)
const entries = capture.mock.calls.splice(0)
expect(entries).toHaveLength(1)
@@ -101,7 +199,7 @@ describe('Console analytics HTTP boundary', () => {
distinctId: 'member',
groups: { organization: org },
uuid: expect.any(String),
- properties: { 'signup.source': 't.co', 'signup.source_type': 'referrer' },
+ properties: { 'signup.source': 'www.linkedin.com', 'signup.source_type': 'referrer' },
})
expect(entries[0][1]).toEqual({ users: ['member'], organizations: [org] })
})
@@ -140,4 +238,75 @@ describe('Console analytics HTTP boundary', () => {
{ users: ['member'], organizations: [org] },
)
})
+
+ it('admits only scoped onboarding actions, controls, and selections', async () => {
+ const path = '/analytics/organizations/' + org + '/console-events'
+ const base = { event: 'console_onboarding_step', occurredAt: new Date().toISOString() }
+ const welcome = { ...base, page: '/dashboard/welcome', action: 'org_create_started' }
+ const quickstart = { ...base, page: '/dashboard/quickstart' }
+ const starter = { ...base, page: '/dashboard/billing/plan/:planId', action: 'starter_sub_click', control: 'button' }
+ const selections = [
+ { ...quickstart, action: 'quickstart_deploy_mode_selected', control: 'button', selection: 'sdk_cli' },
+ { ...quickstart, action: 'quickstart_sdk_tab_selected', control: 'tab', selection: 'typescript' },
+ { ...quickstart, action: 'quickstart_template_selected', control: 'button', selection: 'pgvector' },
+ { ...welcome, action: 'use_case_selected', selection: 'browser-agent' },
+ ]
+ const legacy = { ...quickstart, event: 'console_control_click', action: 'create_box', control: 'button' }
+ capture.mockClear()
+ for (const input of [
+ welcome,
+ starter,
+ { ...welcome, action: 'org_name_submit_click', control: 'button' },
+ { ...welcome, action: 'use_case_submit_click', control: 'button' },
+ ...[
+ 'welcome_back_to_org_click',
+ 'welcome_back_to_use_case_click',
+ 'check_card_status_click',
+ 'explore_boxlite_click',
+ 'start_quickstart_click',
+ ].map((action) => ({ ...welcome, action, control: 'button' })),
+ { ...quickstart, action: 'quickstart_template_create_click', control: 'button' },
+ ...selections,
+ ]) {
+ expect((await request(path, 'POST', bearer, input)).status).toBe(204)
+ const { page, event, occurredAt, ...properties } = input
+ expect(capture).toHaveBeenLastCalledWith(
+ {
+ event,
+ distinctId: 'member',
+ groups: { organization: org },
+ timestamp: new Date(occurredAt),
+ properties: { $pathname: page, ...properties },
+ },
+ { users: ['member'], organizations: [org] },
+ )
+ }
+ expect(capture).toHaveBeenCalledTimes(14)
+ capture.mockClear()
+ for (const input of [
+ ...[legacy, selections[0]].flatMap((value) => [
+ { ...value, page: undefined },
+ { ...value, page: '/dashboard/private' },
+ { ...value, occurredAt: undefined },
+ { ...value, occurredAt: 'now' },
+ ]),
+ ...selections.map((value) => ({ ...value, selection: undefined })),
+ { ...selections[0], selection: 'unlisted' },
+ { ...welcome, action: 'use_case_selected', selection: 'console' },
+ { ...starter, action: 'start_sub_click' },
+ { ...selections[0], selection: null },
+ { ...selections[1], control: 'button' },
+ { ...welcome, action: undefined },
+ { ...welcome, page: '/dashboard/boxes' },
+ { ...welcome, control: 'button' },
+ { ...welcome, destination: '/dashboard/boxes' },
+ { ...welcome, billingTab: 'plans' },
+ { ...welcome, selection: 'console' },
+ { ...legacy, selection: 'console' },
+ { ...welcome, event: '$pageview', action: undefined, selection: 'console' },
+ ]) {
+ expect((await request(path, 'POST', bearer, input)).status).toBe(400)
+ }
+ expect(capture).not.toHaveBeenCalled()
+ })
})
diff --git a/apps/api/src/analytics/console-analytics.controller.ts b/apps/api/src/analytics/console-analytics.controller.ts
index aaca5ec61..2ea533d0c 100644
--- a/apps/api/src/analytics/console-analytics.controller.ts
+++ b/apps/api/src/analytics/console-analytics.controller.ts
@@ -13,13 +13,17 @@ import {
} from '@nestjs/common'
import { ApiExcludeController } from '@nestjs/swagger'
import { AuthGuard } from '@nestjs/passport'
-import { IsBoolean, IsIn, IsISO8601, IsOptional, IsString, Matches, MaxLength } from 'class-validator'
+import { IsBoolean, IsIn, IsISO8601, IsOptional, IsString, Matches, MaxLength, ValidateIf } from 'class-validator'
import {
analyticsNoticeVersion,
billingTabs,
consoleActions,
consoleControls,
+ consoleEventNames,
consolePages,
+ onboardingActions,
+ validOnboardingInteraction,
+ type ConsoleInteraction,
} from '../../../shared/console-analytics'
import { v5 } from 'uuid'
import {
@@ -33,6 +37,7 @@ import { AuthContext } from '../common/decorators/auth-context.decorator'
import type { AuthContext as Principal } from '../common/interfaces/auth-context.interface'
import { AnalyticsService } from './services/analytics.service'
import { AnalyticsConsentService } from './services/analytics-consent.service'
+import { logSignupAttribution, logSignupAttributionSkip, signupAttributionEvent } from './signup-attribution-log'
class ConsentChoice {
@IsBoolean() allowed: boolean
@@ -49,12 +54,13 @@ class SignupSourceInput implements SignupSource {
}
class ConsoleEvent {
- @IsIn(['$pageview', 'console_control_click']) event: '$pageview' | 'console_control_click'
+ @IsIn(consoleEventNames) event: ConsoleInteraction['event']
@IsIn(consolePages) page: RoutePath
@IsISO8601({ strict: true }) occurredAt: string
@IsOptional() @IsIn(consoleControls) control?: string
@IsOptional() @IsIn(consolePages) destination?: RoutePath
- @IsOptional() @IsIn(consoleActions) action?: string
+ @IsOptional() @IsIn([...consoleActions, ...onboardingActions]) action?: string
+ @ValidateIf((_input, value) => value !== undefined) @IsString() selection?: string
@IsOptional() @IsIn(billingTabs) billingTab?: string
}
@@ -88,23 +94,32 @@ export class ConsoleAnalyticsController {
@Post('signup-source')
@HttpCode(204)
async attributeSignup(@AuthContext() actor: Principal, @Body() input: SignupSourceInput) {
- if (!validSource(input.source, input.kind)) throw new BadRequestException('Invalid signup source')
+ if (!validSource(input.source, input.kind)) {
+ logSignupAttributionSkip('invalid_source')
+ throw new BadRequestException('Invalid signup source')
+ }
+ const sourceFields = {
+ 'signup.source': input.source.toLowerCase(),
+ 'signup.source_type': input.kind,
+ ...(input.medium && { 'signup.medium': input.medium }),
+ ...(input.campaign && { 'signup.campaign': input.campaign }),
+ }
+ logSignupAttribution({ outcome: 'received', ...sourceFields })
const enteredAt = new Date(input.enteredAt)
const age = Date.now() - enteredAt.getTime()
- if (!Number.isFinite(age) || age < 0 || age >= signupSourceLifetimeMs || !this.analytics.enabled) return
+ if (!Number.isFinite(age) || age < 0) return logSignupAttributionSkip('invalid_entry_time')
+ if (age >= signupSourceLifetimeMs) return logSignupAttributionSkip('expired_entry_time')
+ if (!this.analytics.enabled) return logSignupAttributionSkip('analytics_disabled')
const organizationId = await this.consent.claimSignupOrganization(actor.userId, enteredAt)
- if (!organizationId) return
+ if (!organizationId) return logSignupAttributionSkip('claim_not_accepted')
this.analytics.capture(
{
- event: 'signup_attributed',
+ event: signupAttributionEvent,
distinctId: actor.userId,
uuid: v5('boxlite:signup-attributed:' + actor.userId, v5.URL),
groups: { organization: organizationId },
properties: {
- 'signup.source': input.source.toLowerCase(),
- 'signup.source_type': input.kind,
- ...(input.medium && { 'signup.medium': input.medium }),
- ...(input.campaign && { 'signup.campaign': input.campaign }),
+ ...sourceFields,
...(input.content && { 'signup.content': input.content }),
},
},
@@ -120,7 +135,16 @@ export class ConsoleAnalyticsController {
@Body() input: ConsoleEvent,
) {
await this.consent.requireMember(actor.userId, organizationId)
- if (input.event === 'console_control_click' && !input.control) throw new BadRequestException('Missing control')
+ if (input.event === 'console_onboarding_step') {
+ if (input.destination !== undefined || input.billingTab !== undefined || !validOnboardingInteraction(input)) {
+ throw new BadRequestException('Invalid onboarding interaction')
+ }
+ } else {
+ if (input.selection !== undefined || (input.action && onboardingActions.includes(input.action))) {
+ throw new BadRequestException('Invalid Console interaction')
+ }
+ if (input.event === 'console_control_click' && !input.control) throw new BadRequestException('Missing control')
+ }
this.analytics.capture(
{
event: input.event,
@@ -135,6 +159,11 @@ export class ConsoleAnalyticsController {
action: input.action,
destination: input.destination,
}),
+ ...(input.event === 'console_onboarding_step' && {
+ action: input.action,
+ ...(input.control && { control: input.control }),
+ ...(input.selection && { selection: input.selection }),
+ }),
},
},
{ users: [actor.userId], organizations: [organizationId] },
diff --git a/apps/api/src/analytics/services/analytics-consent.integration.spec.ts b/apps/api/src/analytics/services/analytics-consent.integration.spec.ts
index 46f8fa8ac..a191d196c 100644
--- a/apps/api/src/analytics/services/analytics-consent.integration.spec.ts
+++ b/apps/api/src/analytics/services/analytics-consent.integration.spec.ts
@@ -3,6 +3,8 @@ import { createServer } from 'node:http'
import type { AddressInfo } from 'node:net'
import { recordBusinessEvent } from '../../common/utils/business-event.util'
import { AnalyticsService } from './analytics.service'
+import { ConsoleAnalyticsController } from '../console-analytics.controller'
+import { RoutePath } from '../../../../shared/console-routes'
import { ConfigService } from '@nestjs/config'
import { configuration } from '../../config/configuration'
import { TypedConfigService } from '../../config/typed-config.service'
@@ -195,6 +197,56 @@ databaseSuite('Product analytics consent in PostgreSQL', () => {
reads.mockRestore()
}
})
+ it.each([
+ [true, true, 1],
+ [false, true, 0],
+ [true, false, 0],
+ ])('delivers onboarding with viewer grant %s and creator grant %s (%i requests)', async (viewer, creator, count) => {
+ await consent.decide('member', viewer)
+ await consent.decide('creator', creator)
+ await delay(3)
+ const received: unknown[] = []
+ const server = createServer(async (req, res) => {
+ let body = ''
+ for await (const chunk of req) body += chunk
+ received.push(JSON.parse(body))
+ res.writeHead(200).end('{"status":1}')
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ const config: Record<string, string> = {
+ 'posthog.apiKey': 'phc_test',
+ 'posthog.host': 'http://127.0.0.1:' + (server.address() as AddressInfo).port,
+ }
+ const analytics = new AnalyticsService({ get: (key: string) => config[key] } as TypedConfigService, consent)
+ const console = new ConsoleAnalyticsController(consent, analytics)
+ try {
+ const occurredAt = new Date().toISOString()
+ await console.record({ userId: 'member' } as Parameters<typeof console.record>[0], org, {
+ event: 'console_onboarding_step',
+ page: RoutePath.QUICKSTART,
+ occurredAt,
+ action: 'quickstart_template_selected',
+ control: 'button',
+ selection: 'node',
+ })
+ await analytics.onApplicationShutdown()
+ expect(received).toHaveLength(count)
+ if (count) {
+ expect(received[0]).toMatchObject({
+ batch: [
+ {
+ event: 'console_onboarding_step',
+ timestamp: occurredAt,
+ properties: { $groups: { organization: org }, action: 'quickstart_template_selected', selection: 'node' },
+ },
+ ],
+ })
+ }
+ } finally {
+ await analytics.onApplicationShutdown()
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ }
+ })
it('sends CI webhook usage only when the creator consented before job creation', async () => {
const received: string[] = []
const server = createServer((req, res) => {
diff --git a/apps/api/src/analytics/services/analytics-consent.service.ts b/apps/api/src/analytics/services/analytics-consent.service.ts
index d92d49935..652005960 100644
--- a/apps/api/src/analytics/services/analytics-consent.service.ts
+++ b/apps/api/src/analytics/services/analytics-consent.service.ts
@@ -160,9 +160,19 @@ export class AnalyticsConsentService {
return value
}
- async dispatch(subjects: AnalyticsSubjects, occurredAt: Date, send: () => Promise<void>): Promise<boolean> {
+ async dispatch(
+ subjects: AnalyticsSubjects,
+ occurredAt: Date,
+ send: () => Promise<void>,
+ onSkip?: (reason: string) => void,
+ ): Promise<boolean> {
+ const skip = (reason: string): false => {
+ onSkip?.(reason)
+ return false
+ }
const at = occurredAt.getTime()
- if (!Number.isFinite(at) || at > Date.now() || this.redis.status !== 'ready') return false
+ if (!Number.isFinite(at) || at > Date.now()) return skip('invalid_event_time')
+ if (this.redis.status !== 'ready') return skip('redis_unavailable')
let cold = false
const admitCold = () => {
if (cold) return true
@@ -178,13 +188,14 @@ export class AnalyticsConsentService {
const users = new Set(subjects.users)
for (const org of new Set(subjects.organizations)) {
const creator = await this.subject('creator', org, admitCold)
- if (!creator) return false
+ if (!creator) return skip('organization_creator_unavailable')
users.add(creator)
}
- if (!users.size) return false
+ if (!users.size) return skip('no_subjects')
for (const user of users) {
const grant = await this.subject('grant', user, admitCold)
- if (!/^\d+$/.test(grant) || Number(grant) > at) return false
+ if (!/^\d+$/.test(grant)) return skip('consent_grant_unavailable')
+ if (Number(grant) > at) return skip('consent_after_event')
}
} finally {
if (cold) this.coldEvents--
diff --git a/apps/api/src/analytics/services/analytics.service.ts b/apps/api/src/analytics/services/analytics.service.ts
index 7a73a0813..186152d5a 100644
--- a/apps/api/src/analytics/services/analytics.service.ts
+++ b/apps/api/src/analytics/services/analytics.service.ts
@@ -22,6 +22,7 @@ import { Organization } from '../../organization/entities/organization.entity'
import { OrganizationEvents } from '../../organization/constants/organization-events.constant'
import { TypedConfigService } from '../../config/typed-config.service'
import { subscribeBusinessEvents } from '../../common/utils/business-event.util'
+import { logSignupAttributionSkip, signupAttributionEvent } from '../signup-attribution-log'
@Injectable()
export class AnalyticsService implements OnApplicationShutdown {
@@ -82,15 +83,22 @@ export class AnalyticsService implements OnApplicationShutdown {
capture(event: Parameters<PostHog['capture']>[0], subjects: AnalyticsSubjects, consentSince?: Date): void {
const client = this.posthog
- if (!client || this.closing || (!subjects.users.length && !subjects.organizations.length)) return
+ const onSkip = event.event === signupAttributionEvent ? logSignupAttributionSkip : undefined
+ if (!client) return onSkip?.('analytics_disabled')
+ if (this.closing) return onSkip?.('shutdown_in_progress')
+ if (!subjects.users.length && !subjects.organizations.length) return onSkip?.('no_subjects')
const occurredAt = event.timestamp ?? new Date()
const delivery = this.consent
- .dispatch(subjects, consentSince ?? occurredAt, () =>
- client.deliver({
- ...event,
- timestamp: occurredAt,
- properties: { ...event.properties, environment: this.configService.get('posthog.environment') },
- }),
+ .dispatch(
+ subjects,
+ consentSince ?? occurredAt,
+ () =>
+ client.deliver({
+ ...event,
+ timestamp: occurredAt,
+ properties: { ...event.properties, environment: this.configService.get('posthog.environment') },
+ }),
+ onSkip,
)
.catch(() => this.logger.warn('PostHog analytics capture failed'))
this.pending.add(delivery)
diff --git a/apps/api/src/analytics/services/consent-bound-posthog.ts b/apps/api/src/analytics/services/consent-bound-posthog.ts
index 315c80335..fb027f345 100644
--- a/apps/api/src/analytics/services/consent-bound-posthog.ts
+++ b/apps/api/src/analytics/services/consent-bound-posthog.ts
@@ -1,7 +1,11 @@
/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { AsyncLocalStorage } from 'node:async_hooks'
import { PostHog } from 'posthog-node'
+import { logSignupAttribution, signupAttributionEvent } from '../signup-attribution-log'
export class ConsentBoundPostHog extends PostHog {
+ private readonly signupDelivery = new AsyncLocalStorage<boolean>()
+
// The public captureImmediate in posthog-node 4.18 resolves before its HTTP request.
// Track the HTTP attempt through shutdown and report transport failures.
deliver({
@@ -12,6 +16,21 @@ export class ConsentBoundPostHog extends PostHog {
timestamp,
uuid,
}: Parameters<PostHog['capture']>[0]): Promise<void> {
- return this.captureStatelessImmediate(distinctId, event, { ...properties, $groups: groups }, { timestamp, uuid })
+ const capture = () =>
+ this.captureStatelessImmediate(distinctId, event, { ...properties, $groups: groups }, { timestamp, uuid })
+ return event === signupAttributionEvent ? this.signupDelivery.run(true, capture) : capture()
+ }
+
+ override fetch(...args: Parameters<PostHog['fetch']>): ReturnType<PostHog['fetch']> {
+ if (!this.signupDelivery.getStore()) return super.fetch(...args)
+
+ // sendImmediate catches HTTP errors, so its completion alone does not prove delivery.
+ logSignupAttribution({ outcome: 'sending' })
+ return super.fetch(...args).then((response) => {
+ if (response.status >= 200 && response.status < 300) {
+ logSignupAttribution({ outcome: 'delivered', http_status: response.status })
+ }
+ return response
+ })
}
}
diff --git a/apps/api/src/analytics/services/signup-attribution.logging.spec.ts b/apps/api/src/analytics/services/signup-attribution.logging.spec.ts
new file mode 100644
index 000000000..7b7aef58c
--- /dev/null
+++ b/apps/api/src/analytics/services/signup-attribution.logging.spec.ts
@@ -0,0 +1,174 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { AsyncLocalStorage } from 'node:async_hooks'
+import { createServer, ServerResponse } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { Logger } from '@nestjs/common'
+import type Redis from 'ioredis'
+import type { DataSource } from 'typeorm'
+import type { TypedConfigService } from '../../config/typed-config.service'
+import { signupAttributionEvent } from '../signup-attribution-log'
+import { AnalyticsConsentService } from './analytics-consent.service'
+import { AnalyticsService } from './analytics.service'
+
+function consentWithCache(status: string, get: (key: string) => Promise<string>) {
+ return new AnalyticsConsentService(
+ { options: {} } as DataSource,
+ { status, get } as Redis,
+ { getOrThrow: () => 10 } as unknown as TypedConfigService,
+ )
+}
+
+describe('Signup attribution logging', () => {
+ const eventTime = new Date('2025-01-01T00:00:00Z')
+ const users = { users: ['user'], organizations: [] }
+ const nobody = { users: [], organizations: [] }
+
+ it.each([
+ ['invalid_event_time', new Date(NaN), 'ready', users, ''],
+ ['invalid_event_time', new Date('2999-01-01T00:00:00Z'), 'ready', users, ''],
+ ['redis_unavailable', eventTime, 'end', users, ''],
+ ['organization_creator_unavailable', eventTime, 'ready', { ...users, organizations: ['org'] }, ''],
+ ['no_subjects', eventTime, 'ready', nobody, ''],
+ ['consent_grant_unavailable', eventTime, 'ready', users, ''],
+ ['consent_after_event', eventTime, 'ready', users, String(eventTime.getTime() + 1)],
+ ])('reports %s from consent dispatch without sending', async (reason, time, status, subjects, cached) => {
+ const consent = consentWithCache(status, async () => cached)
+ const send = jest.fn(async () => {})
+ const onSkip = jest.fn()
+
+ await expect(consent.dispatch(subjects, time, send, onSkip)).resolves.toBe(false)
+ expect(send).not.toHaveBeenCalled()
+ expect(onSkip.mock.calls).toEqual([[reason]])
+ })
+
+ it('logs signup attempts before the response and acknowledges only the matching 2xx', async () => {
+ const context = new AsyncLocalStorage<string>()
+ const logged: Array<{ scope?: string; fields: object }> = []
+ const warnings: Array<{ scope?: string; message: unknown }> = []
+ const requests: Array<{ distinct_id: string; event: string }> = []
+ let observeHeld!: () => void
+ let observeRejection!: () => void
+ let heldResponse: ServerResponse | undefined
+ const held = new Promise<void>((resolve) => (observeHeld = resolve))
+ const rejected = new Promise<void>((resolve) => (observeRejection = resolve))
+ const info = jest.spyOn(Logger.prototype, 'log').mockImplementation((message, fields) => {
+ if (typeof message === 'string' && message.startsWith('signup.attribution ')) {
+ logged.push({ scope: context.getStore(), fields })
+ }
+ })
+ const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation((message) => {
+ const scope = context.getStore()
+ warnings.push({ scope, message })
+ if (scope === 'rejected') observeRejection()
+ })
+ const server = createServer((request, response) => {
+ const chunks: Buffer[] = []
+ request.on('data', (chunk: Buffer) => chunks.push(chunk))
+ request.on('end', () => {
+ const [event] = JSON.parse(Buffer.concat(chunks).toString()).batch
+ requests.push(event)
+ if (event.distinct_id === 'accepted') {
+ heldResponse = response
+ observeHeld()
+ } else if (event.distinct_id === 'disconnected') {
+ request.socket.destroy()
+ } else {
+ response.writeHead(event.distinct_id === 'rejected' ? 429 : 200).end('{"status":1}')
+ }
+ })
+ })
+
+ let analytics: AnalyticsService | undefined
+ let shutdown: Promise<void> | undefined
+ try {
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ const consent = consentWithCache('ready', async (key) => {
+ if (key.endsWith(':lookup-failed')) throw new Error('Redis lookup failed')
+ return key.endsWith(':denied') ? '' : '0'
+ })
+ const config = {
+ 'posthog.apiKey': 'phc_test',
+ 'posthog.host': 'http://127.0.0.1:' + (server.address() as AddressInfo).port,
+ 'posthog.environment': 'test',
+ }
+ analytics = new AnalyticsService(
+ { get: (key: keyof typeof config) => config[key] } as TypedConfigService,
+ consent,
+ )
+ const disabled = new AnalyticsService({ get: () => undefined } as unknown as TypedConfigService, consent)
+ const event = {
+ event: signupAttributionEvent,
+ uuid: '2dfd7b11-7b07-4efb-ad36-16afd0db4cd1',
+ properties: { 'signup.source': 'example.com' },
+ groups: { organization: 'org' },
+ }
+ const capture = (scope: string, name = signupAttributionEvent) =>
+ context.run(scope, () => {
+ analytics!.capture({ ...event, event: name, distinctId: scope }, { users: [scope], organizations: [] })
+ })
+ context.run('disabled', () => disabled.capture({ ...event, distinctId: 'disabled' }, users))
+ context.run('empty', () => analytics!.capture({ ...event, distinctId: 'empty' }, nobody))
+ capture('accepted')
+ await held
+ capture('rejected')
+ capture('disconnected')
+ capture('other', 'user.login')
+ capture('denied')
+ capture('lookup-failed')
+
+ let drained = false
+ shutdown = analytics.onApplicationShutdown().then(() => {
+ drained = true
+ })
+ capture('closing')
+ await rejected
+ expect(drained).toBe(false)
+ const outcomes = (scope: string) =>
+ logged.filter((record) => record.scope === scope).map((record) => record.fields)
+ const fields = { 'event.name': 'signup.attribution' }
+ const sending = { ...fields, outcome: 'sending' }
+ expect(outcomes('accepted')).toEqual([sending])
+ heldResponse!.writeHead(202).end('{"status":1}')
+ await shutdown
+
+ expect(requests.map((request) => request.distinct_id).sort()).toEqual([
+ 'accepted',
+ 'disconnected',
+ 'other',
+ 'rejected',
+ ])
+ expect(requests.find((request) => request.distinct_id === 'accepted')).toMatchObject({
+ event: signupAttributionEvent,
+ uuid: event.uuid,
+ properties: { 'signup.source': 'example.com', $groups: { organization: 'org' }, environment: 'test' },
+ })
+ expect(outcomes('accepted')).toEqual([sending, { ...fields, outcome: 'delivered', http_status: 202 }])
+ expect(outcomes('rejected')).toEqual([sending])
+ expect(outcomes('disconnected')).toEqual([sending])
+ expect(outcomes('other')).toEqual([])
+ expect(outcomes('lookup-failed')).toEqual([])
+ for (const [scope, reason] of [
+ ['disabled', 'analytics_disabled'],
+ ['empty', 'no_subjects'],
+ ['closing', 'shutdown_in_progress'],
+ ['denied', 'consent_grant_unavailable'],
+ ]) {
+ expect(outcomes(scope)).toEqual([{ ...fields, outcome: 'skipped', reason }])
+ }
+ expect(warnings).toHaveLength(3)
+ expect(warnings).toEqual(
+ expect.arrayContaining([
+ { scope: 'rejected', message: 'PostHog analytics delivery failed' },
+ { scope: 'disconnected', message: 'PostHog analytics delivery failed' },
+ { scope: 'lookup-failed', message: 'PostHog analytics capture failed' },
+ ]),
+ )
+ } finally {
+ heldResponse?.end()
+ await (shutdown ?? analytics?.onApplicationShutdown())
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ warn.mockRestore()
+ info.mockRestore()
+ }
+ })
+})
diff --git a/apps/api/src/analytics/signup-attribution-log.ts b/apps/api/src/analytics/signup-attribution-log.ts
new file mode 100644
index 000000000..574aa82af
--- /dev/null
+++ b/apps/api/src/analytics/signup-attribution-log.ts
@@ -0,0 +1,27 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import { Logger } from '@nestjs/common'
+import type { SignupSource } from '../../../shared/signup-attribution'
+
+export const signupAttributionEvent = 'signup_attributed'
+const eventName = 'signup.attribution'
+const logger = new Logger('SignupAttribution')
+
+type Outcome =
+ | {
+ outcome: 'received'
+ 'signup.source': string
+ 'signup.source_type': SignupSource['kind']
+ 'signup.medium'?: string
+ 'signup.campaign'?: string
+ }
+ | { outcome: 'skipped'; reason: string }
+ | { outcome: 'sending' }
+ | { outcome: 'delivered'; http_status: number }
+
+export function logSignupAttribution(result: Outcome): void {
+ logger.log(eventName + ' ' + result.outcome, { 'event.name': eventName, ...result })
+}
+
+export function logSignupAttributionSkip(reason: string): void {
+ logSignupAttribution({ outcome: 'skipped', reason })
+}
diff --git a/apps/api/src/organization/dto/onboarding.dto.ts b/apps/api/src/organization/dto/onboarding.dto.ts
index 9c3ee4498..ad6db50b4 100644
--- a/apps/api/src/organization/dto/onboarding.dto.ts
+++ b/apps/api/src/organization/dto/onboarding.dto.ts
@@ -1,16 +1,7 @@
/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
import { ApiProperty } from '@nestjs/swagger'
import { IsIn, IsInt, IsString, IsUUID, Matches, Max, MaxLength, Min } from 'class-validator'
-
-export const ONBOARDING_USE_CASES = [
- 'coding-agent',
- 'code-execution',
- 'browser-agent',
- 'long-running-agent',
- 'application-deployments',
- 'reinforcement-learning',
- 'exploring',
-] as const
+import { ONBOARDING_USE_CASES } from '../../../../shared/onboarding-use-cases'
export class SaveOnboardingDto {
@ApiProperty({ enum: ONBOARDING_USE_CASES })
diff --git a/apps/dashboard/README.md b/apps/dashboard/README.md
index 8027ef94e..cb29105c7 100644
--- a/apps/dashboard/README.md
+++ b/apps/dashboard/README.md
@@ -189,15 +189,15 @@ contract and is not inferred from a saved use case.
### Product analytics preferences
-Registration offers Terms of Service and Privacy Policy links. On first entering the Console, a person can allow product analytics, choose **No thanks**, or continue without answering. Collection starts after an explicit grant. Earlier visits and interactions are discarded. An existing refusal suppresses the card on future visits.
+The Welcome organization form offers an optional PostHog analytics checkbox next to the Terms of Service and Privacy Policy acknowledgment. A user without an existing grant can leave it unchecked and continue. Checking it saves the account's grant and locks the Welcome checkbox. To withdraw consent, use Privacy Preferences in Settings. Collection starts after an explicit grant. Earlier visits and interactions are discarded.
Open **Org → Management → Settings → Privacy Preferences** at `/dashboard/settings?tab=settings` to change **Product analytics**. Each choice covers the signed-in account and organizations it created. A member’s interaction also requires the organization creator’s grant. The Console submits route templates and recognized control actions to the Cloud API. Raw URLs, referral parameters, terminal contents and control text are excluded. Functional feature flags remain available for every choice.
Console analytics sends up to two requests at once and holds up to 16 additional events in memory during rapid interaction. Each queued event keeps its original page and occurrence time. A full queue drops new events. A consent change, an account or organization switch, or leaving the Console clears unsent events.
-The Dashboard uses the last confirmed consent while a preference is saving. If the save fails, Settings shows an error and offers a retry. Once the API confirms a withdrawal, collection stops across the account’s organizations in the Console.
+The Dashboard uses the last confirmed consent while a preference is saving. If the save fails, the preference control shows an error. Once the API confirms a withdrawal, collection stops across the account’s organizations in the Console.
-See the [first-visit card](review-assets/product-analytics/first-console-visit.png) and [Settings switch](review-assets/product-analytics/settings.png).
+See the [Settings switch](review-assets/product-analytics/settings.png).
## Managed checkpoints
diff --git a/apps/dashboard/src/components/OnboardingGuideDialog.render.test.tsx b/apps/dashboard/src/components/OnboardingGuideDialog.render.test.tsx
index 70773cf81..d0839cd33 100644
--- a/apps/dashboard/src/components/OnboardingGuideDialog.render.test.tsx
+++ b/apps/dashboard/src/components/OnboardingGuideDialog.render.test.tsx
@@ -5,6 +5,8 @@
*/
import { act } from 'react'
+import { MemoryRouter } from 'react-router-dom'
+import { ConsoleTrackerFixture } from './tests/ConsoleTrackerFixture'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { OnboardingGuideDialog } from './OnboardingGuideDialog'
@@ -12,6 +14,7 @@ import { quickstartRecipeFor } from '@/lib/quickstart/recipes'
const mocks = vi.hoisted(() => ({
orgId: 'org-1',
+ post: vi.fn(async () => ({})),
saveDraft: vi.fn(async (_org, text, revision) => ({ text, revision: revision + 1 })),
handoff: vi.fn(async () => ({})),
markCopied: vi.fn(async () => ({})),
@@ -26,6 +29,7 @@ vi.mock('@/lib/copy-text', () => ({ copyToClipboard: mocks.copy }))
vi.mock('@/hooks/useApi', () => ({
useApi: () => ({
+ axiosInstance: { post: mocks.post },
savePromptDraft: mocks.saveDraft,
preparePromptHandoff: mocks.handoff,
markPromptCopied: mocks.markCopied,
@@ -103,20 +107,24 @@ describe('OnboardingGuideDialog tabs', () => {
await act(async () => {
root ??= createRoot(host)
root.render(
- <OnboardingGuideDialog
- inline
- open
- onOpenChange={() => {}}
- onProgressChange={progress}
- progress={{ boxCreated: false, sdkConnected: false }}
- preview={{
- inline: true,
- recipe: quickstartRecipeFor(method === 'sdk' ? 'code-execution' : 'application-deployments'),
- onRecipeChange: () => {},
- onConsole: () => {},
- creditCents: 10000,
- }}
- />,
+ <MemoryRouter initialEntries={['/dashboard/quickstart']}>
+ <ConsoleTrackerFixture>
+ <OnboardingGuideDialog
+ inline
+ open
+ onOpenChange={() => {}}
+ onProgressChange={progress}
+ progress={{ boxCreated: false, sdkConnected: false }}
+ preview={{
+ inline: true,
+ recipe: quickstartRecipeFor(method === 'sdk' ? 'code-execution' : 'application-deployments'),
+ onRecipeChange: () => {},
+ onConsole: () => {},
+ creditCents: 10000,
+ }}
+ />
+ </ConsoleTrackerFixture>
+ </MemoryRouter>,
)
})
await flush()
@@ -131,6 +139,11 @@ describe('OnboardingGuideDialog tabs', () => {
.closest('section')!
await click([...installSection.querySelectorAll('button')].find((item) => item.textContent === 'Copy'))
expect(mocks.copy).toHaveBeenCalledWith('pip install --upgrade boxlite')
+ expect(mocks.post).toHaveBeenLastCalledWith(
+ '/analytics/organizations/org-1/console-events',
+ expect.objectContaining({ event: 'console_onboarding_step', action: 'quickstart_code_copied' }),
+ expect.any(Object),
+ )
expect(document.body.textContent).toContain('Hello from BoxLite')
expect([...document.querySelectorAll('h2')].map((item) => item.textContent)).toEqual([
'1. Get an API key',
@@ -149,6 +162,31 @@ describe('OnboardingGuideDialog tabs', () => {
expect(document.body.textContent).toContain('boxlite create --name')
expect(document.body.textContent).toContain('boxlite exec "$box_name"')
expect(document.body.textContent).not.toContain('Next →')
+ const analyticsPath = '/analytics/organizations/org-1/console-events'
+ expect(mocks.post).toHaveBeenLastCalledWith(
+ analyticsPath,
+ expect.objectContaining({
+ event: 'console_onboarding_step',
+ action: 'quickstart_sdk_tab_selected',
+ selection: 'cli',
+ }),
+ expect.any(Object),
+ )
+ mocks.post.mockClear()
+ await act(async () => {
+ cliButton.focus()
+ cliButton.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }))
+ await vi.advanceTimersByTimeAsync(1)
+ })
+ expect(mocks.post).toHaveBeenCalledExactlyOnceWith(
+ analyticsPath,
+ expect.objectContaining({
+ event: 'console_onboarding_step',
+ action: 'quickstart_sdk_tab_selected',
+ selection: 'rest',
+ }),
+ expect.any(Object),
+ )
await renderMethod('prompt')
expect(document.querySelector('[role="dialog"]')).toBeNull()
const request = document.querySelector<HTMLTextAreaElement>('[aria-label="Application request"]')!
@@ -183,6 +221,18 @@ describe('OnboardingGuideDialog tabs', () => {
)
expect(copyButton).toBeDefined()
await click(copyButton)
+ expect(mocks.post.mock.calls.slice(-2)).toEqual([
+ [
+ analyticsPath,
+ expect.objectContaining({ event: 'console_onboarding_step', action: 'quickstart_prompt_prepared' }),
+ expect.any(Object),
+ ],
+ [
+ analyticsPath,
+ expect.objectContaining({ event: 'console_onboarding_step', action: 'quickstart_prompt_copied' }),
+ expect.any(Object),
+ ],
+ ])
expect(mocks.copy).toHaveBeenCalledWith(
expect.stringContaining('Application request: Build an inventory dashboard.'),
)
diff --git a/apps/dashboard/src/components/OnboardingGuideDialog.tsx b/apps/dashboard/src/components/OnboardingGuideDialog.tsx
index 577b89e1f..2873e3561 100644
--- a/apps/dashboard/src/components/OnboardingGuideDialog.tsx
+++ b/apps/dashboard/src/components/OnboardingGuideDialog.tsx
@@ -8,6 +8,7 @@ import { AsciiButton } from '@/components/ascii'
import { QuickstartAgentHandoff } from '@/components/QuickstartAgentHandoff'
import { QuickstartRecipeHeader, type QuickstartPreview } from '@/components/first-run/QuickstartRecipeHeader'
import { CODING_AGENT_MARKS } from '@/assets/AgentLogos'
+import { recordConsoleTabSelection } from '@/hooks/useConsoleAnalytics'
import { QuickstartCopyButton } from '@/components/QuickstartCopyButton'
import {
Dialog,
@@ -328,9 +329,21 @@ function InterfacePicker({
}) {
if (quiet) {
return (
- <Tabs value={selected} onValueChange={onSelect} className="min-w-0 max-w-full">
+ <Tabs
+ value={selected}
+ onValueChange={(id) => {
+ onSelect(id)
+ recordConsoleTabSelection('quickstart_sdk_tab_selected', id)
+ }}
+ className="min-w-0 max-w-full"
+ >
<div className="-mx-1 -my-1 overflow-x-auto p-1">
- <TabsList variant="underline" aria-label="SDK or CLI" className="w-max min-w-full">
+ <TabsList
+ variant="underline"
+ aria-label="SDK or CLI"
+ className="w-max min-w-full"
+ data-console-tab-selections
+ >
{QUICKSTART_INTERFACES.map((item) => (
<TabsTrigger key={item.id} value={item.id}>
<QuickstartInterfaceIcon icon={item.icon} />
@@ -461,6 +474,7 @@ function InlineCodeSteps({
</span>
<QuickstartCopyButton
quiet
+ consoleAction="quickstart_code_copied"
copied={copiedTarget === part.id}
onClick={() => void onCopy(part.code, part.id)}
/>
@@ -616,6 +630,7 @@ function OnboardingGuideContent({
<code className="quickstart-code min-w-0 flex-1 break-all">{createdKey.value}</code>
<QuickstartCopyButton
quiet
+ consoleAction="quickstart_code_copied"
copied={copiedTarget === 'api-key'}
onClick={() => void copyText(createdKey.value ?? '', 'api-key')}
/>
@@ -662,6 +677,7 @@ function OnboardingGuideContent({
<span className="font-sans text-meta tracking-normal text-muted-foreground">Local terminal</span>
<QuickstartCopyButton
quiet
+ consoleAction="quickstart_code_copied"
copied={copiedTarget === 'install'}
onClick={() => void copyText(activeExample.install, 'install')}
/>
@@ -690,6 +706,7 @@ function OnboardingGuideContent({
</pre>
<QuickstartCopyButton
quiet
+ consoleAction="quickstart_code_copied"
label="Copy full example"
copied={copiedTarget === 'code'}
onClick={() =>
diff --git a/apps/dashboard/src/components/ProductAnalyticsPreferences.tsx b/apps/dashboard/src/components/ProductAnalyticsPreferences.tsx
index 4fd7308c6..bd90dc971 100644
--- a/apps/dashboard/src/components/ProductAnalyticsPreferences.tsx
+++ b/apps/dashboard/src/components/ProductAnalyticsPreferences.tsx
@@ -112,40 +112,31 @@ function AccountPreference({
)
}
-export function AnalyticsConsentCard() {
+export function WelcomeAnalyticsConsent() {
const choice = useContext(Preferences)
- if (!choice || choice.allowed !== null) return null
+ if (!choice || choice.allowed === undefined) return null
+ const optedIn = choice.allowed === true
return (
- <section
- data-analytics-preferences
- aria-labelledby="analytics-card-title"
- className="mx-4 my-3 max-w-xl border border-border bg-background p-4 sm:mx-5"
- >
- <h2 id="analytics-card-title" className="text-body font-semibold">
- Share usage analytics?
- </h2>
- <p className="mt-1 text-body text-muted-foreground">
- Allow BoxLite to send Console page visits and feature interactions to PostHog to help improve the product. You
- can turn this off anytime in Settings.
- </p>
- <details className="mt-2 text-meta text-muted-foreground">
- <summary className="cursor-pointer">What this choice covers</summary>Your choice covers your account activity
- and Cloud activity in organizations you created. Activity linked to another member also needs their permission.
- </details>
- <div className="mt-3 flex flex-wrap gap-2">
- <Button variant="outline" disabled={choice.saving} onClick={() => choice.save(true)}>
- Allow analytics
- </Button>
- <Button variant="outline" disabled={choice.saving} onClick={() => choice.save(false)}>
- No thanks
- </Button>
+ <div data-analytics-preferences className="mt-3 flex items-start gap-2.5 text-muted-foreground">
+ <input
+ id="welcome-product-analytics"
+ type="checkbox"
+ checked={optedIn}
+ disabled={choice.saving || optedIn}
+ onChange={() => choice.save(true)}
+ className="mt-1 size-4 shrink-0 cursor-pointer accent-foreground"
+ />
+ <div>
+ <label htmlFor="welcome-product-analytics" className="cursor-pointer text-body leading-6">
+ Share Console/Feature usage with PostHog to help improve BoxLite.
+ </label>
+ {choice.error && (
+ <p role="alert" className="mt-2 text-meta text-destructive">
+ {choice.error}
+ </p>
+ )}
</div>
- {choice.error && (
- <p role="alert" className="mt-2 text-meta text-destructive">
- {choice.error}
- </p>
- )}
- </section>
+ </div>
)
}
diff --git a/apps/dashboard/src/components/QuickstartAgentHandoff.tsx b/apps/dashboard/src/components/QuickstartAgentHandoff.tsx
index 292e6a462..a5e402814 100644
--- a/apps/dashboard/src/components/QuickstartAgentHandoff.tsx
+++ b/apps/dashboard/src/components/QuickstartAgentHandoff.tsx
@@ -465,6 +465,9 @@ Verify that the credentials are valid and authorized for this task before execut
<button
type="button"
disabled={!handoff || !draft.ready || !request.trim() || copying}
+ data-console-action={
+ preparedRequest === request ? 'quickstart_prompt_copied' : 'quickstart_prompt_prepared'
+ }
onClick={() => void (preparedRequest === request ? copy() : prepare())}
className="rounded-none bg-foreground px-5 py-2.5 text-body font-medium text-background transition-opacity hover:opacity-85 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand disabled:cursor-not-allowed disabled:opacity-35"
>
diff --git a/apps/dashboard/src/components/QuickstartCopyButton.tsx b/apps/dashboard/src/components/QuickstartCopyButton.tsx
index e0db0544a..c48075cba 100644
--- a/apps/dashboard/src/components/QuickstartCopyButton.tsx
+++ b/apps/dashboard/src/components/QuickstartCopyButton.tsx
@@ -14,6 +14,7 @@ export function QuickstartCopyButton({
className,
quiet = false,
label = 'Copy',
+ consoleAction,
}: {
copied: boolean
/** A denied clipboard permission used to look exactly like an unclicked
@@ -23,12 +24,14 @@ export function QuickstartCopyButton({
className?: string
quiet?: boolean
label?: string
+ consoleAction?: string
}) {
const accent = failed ? 'destructive' : 'success'
return (
<button
type="button"
onClick={onClick}
+ data-console-action={consoleAction}
style={
quiet
? undefined
diff --git a/apps/dashboard/src/components/first-run/ConsoleTemplatePicker.test.tsx b/apps/dashboard/src/components/first-run/ConsoleTemplatePicker.test.tsx
index 837daf5fc..16d59e69b 100644
--- a/apps/dashboard/src/components/first-run/ConsoleTemplatePicker.test.tsx
+++ b/apps/dashboard/src/components/first-run/ConsoleTemplatePicker.test.tsx
@@ -2,10 +2,12 @@
import React, { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { MemoryRouter } from 'react-router-dom'
+import { ConsoleTrackerFixture } from '../tests/ConsoleTrackerFixture'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { ConsoleTemplatePicker } from './ConsoleTemplatePicker'
const state = vi.hoisted(() => ({
create: vi.fn(),
+ post: vi.fn(),
navigate: vi.fn(),
isError: false,
canCreate: true,
@@ -15,6 +17,8 @@ const state = vi.hoisted(() => ({
vi.mock('@/hooks/mutations/useCreateBoxMutation', () => ({
useCreateBoxMutation: () => ({ mutateAsync: state.create, reset: vi.fn(), isPending: false, isError: state.isError }),
}))
+vi.mock('@/hooks/useApi', () => ({ useApi: () => ({ axiosInstance: { post: state.post } }) }))
+vi.mock('@/hooks/useConfig', () => ({ useConfig: () => ({}) }))
vi.mock('react-router-dom', async () => ({
...(await vi.importActual('react-router-dom')),
useNavigate: () => state.navigate,
@@ -29,6 +33,7 @@ let host: HTMLDivElement, root: Root
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
vi.clearAllMocks()
+ state.post.mockResolvedValue({})
state.isError = false
state.canCreate = true
state.memberLoaded = true
@@ -42,11 +47,13 @@ afterEach(async () => {
host.remove()
vi.unstubAllGlobals()
})
-async function mount(url = '/') {
+async function mount(url = '/dashboard/quickstart') {
await act(async () =>
root.render(
<MemoryRouter initialEntries={[url]}>
- <ConsoleTemplatePicker />
+ <ConsoleTrackerFixture>
+ <ConsoleTemplatePicker />
+ </ConsoleTrackerFixture>
</MemoryRouter>,
),
)
@@ -78,6 +85,22 @@ it('creates the chosen public image with its startup settings and navigates to t
}),
)
expect(state.navigate).toHaveBeenCalledWith(expect.stringContaining('box-1'))
+ expect(state.post.mock.calls.slice(1)).toEqual([
+ [
+ '/analytics/organizations/org-1/console-events',
+ expect.objectContaining({
+ event: 'console_onboarding_step',
+ action: 'quickstart_template_selected',
+ selection: 'node',
+ }),
+ expect.any(Object),
+ ],
+ [
+ '/analytics/organizations/org-1/console-events',
+ expect.objectContaining({ event: 'console_onboarding_step', action: 'quickstart_template_create_click' }),
+ expect.any(Object),
+ ],
+ ])
})
it('filters templates, shows empty searches, and blocks invalid names', async () => {
await mount()
diff --git a/apps/dashboard/src/components/first-run/ConsoleTemplatePicker.tsx b/apps/dashboard/src/components/first-run/ConsoleTemplatePicker.tsx
index f943c66c0..aba685668 100644
--- a/apps/dashboard/src/components/first-run/ConsoleTemplatePicker.tsx
+++ b/apps/dashboard/src/components/first-run/ConsoleTemplatePicker.tsx
@@ -121,6 +121,8 @@ export function ConsoleTemplatePicker() {
type="button"
aria-label={`Select ${item.name}`}
aria-pressed={activeId === item.id}
+ data-console-action="quickstart_template_selected"
+ data-console-selection={item.id}
disabled={busy}
onClick={() => {
setSelection(item.id)
@@ -188,6 +190,7 @@ export function ConsoleTemplatePicker() {
variant="primary"
className="w-full justify-center py-2.5"
disabled={!canCreate || busy || !validTemplateImage(image) || !/^[a-z0-9][a-z0-9-]{0,39}$/.test(name)}
+ data-console-action="quickstart_template_create_click"
onClick={() => void deploy()}
>
{busy ? 'Creating Box…' : 'Create Box'}
diff --git a/apps/dashboard/src/components/first-run/FirstBoxOnboarding.test.tsx b/apps/dashboard/src/components/first-run/FirstBoxOnboarding.test.tsx
index 2b1955deb..4ef107451 100644
--- a/apps/dashboard/src/components/first-run/FirstBoxOnboarding.test.tsx
+++ b/apps/dashboard/src/components/first-run/FirstBoxOnboarding.test.tsx
@@ -2,9 +2,12 @@
import React, { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { MemoryRouter } from 'react-router-dom'
+import { ConsoleTrackerFixture } from '../tests/ConsoleTrackerFixture'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { FirstBoxQuickstart } from './FirstBoxOnboarding'
-const state = vi.hoisted(() => ({ navigate: vi.fn() }))
+const state = vi.hoisted(() => ({ navigate: vi.fn(), post: vi.fn() }))
+vi.mock('@/hooks/useApi', () => ({ useApi: () => ({ axiosInstance: { post: state.post } }) }))
+vi.mock('@/hooks/useConfig', () => ({ useConfig: () => ({}) }))
vi.mock('react-router-dom', async () => ({
...(await vi.importActual('react-router-dom')),
useNavigate: () => state.navigate,
@@ -26,16 +29,19 @@ beforeEach(() => {
document.body.append(host)
root = createRoot(host)
vi.clearAllMocks()
+ state.post.mockResolvedValue({})
})
afterEach(async () => {
await act(async () => root.unmount())
host.remove()
})
-async function mount(url = '/') {
+async function mount(url = '/dashboard/quickstart') {
await act(async () =>
root.render(
<MemoryRouter initialEntries={[url]}>
- <FirstBoxQuickstart />
+ <ConsoleTrackerFixture>
+ <FirstBoxQuickstart />
+ </ConsoleTrackerFixture>
</MemoryRouter>,
),
)
@@ -61,6 +67,18 @@ it('switches between SDK, console and agent prompt without reopening the old mod
await click('Deploy from SDK / CLI')
await click('Close guide')
expect(state.navigate).toHaveBeenCalledWith('/dashboard/boxes')
+ const deployments = state.post.mock.calls.filter(([, body]) => body.event === 'console_onboarding_step')
+ expect(deployments).toEqual(
+ ['console', 'prompt', 'sdk_cli'].map((selection) => [
+ '/analytics/organizations/org-1/console-events',
+ expect.objectContaining({
+ event: 'console_onboarding_step',
+ action: 'quickstart_deploy_mode_selected',
+ selection,
+ }),
+ expect.any(Object),
+ ]),
+ )
})
it('opens the console directly from an image catalog deep link', async () => {
await mount('/?method=console&template=python')
diff --git a/apps/dashboard/src/components/first-run/FirstBoxOnboarding.tsx b/apps/dashboard/src/components/first-run/FirstBoxOnboarding.tsx
index 0c1a59c32..e2f63373a 100644
--- a/apps/dashboard/src/components/first-run/FirstBoxOnboarding.tsx
+++ b/apps/dashboard/src/components/first-run/FirstBoxOnboarding.tsx
@@ -46,6 +46,8 @@ export function FirstBoxQuickstart() {
type="button"
aria-label={title}
aria-pressed={method === id}
+ data-console-action="quickstart_deploy_mode_selected"
+ data-console-selection={id === 'sdk' ? 'sdk_cli' : id}
onClick={() => setMethod(id)}
className={`group flex items-center gap-3 rounded-none px-4 py-3.5 text-left transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-brand ${method === id ? 'bg-accent' : 'bg-card hover:bg-accent'}`}
>
diff --git a/apps/dashboard/src/components/first-run/FirstBoxWelcome.test.tsx b/apps/dashboard/src/components/first-run/FirstBoxWelcome.test.tsx
index 9b92984fa..1e5785371 100644
--- a/apps/dashboard/src/components/first-run/FirstBoxWelcome.test.tsx
+++ b/apps/dashboard/src/components/first-run/FirstBoxWelcome.test.tsx
@@ -5,8 +5,18 @@ import { MemoryRouter, Routes, Route } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import FirstBoxWelcome from './FirstBoxWelcome'
+import { recordConsoleOnboardingStep } from '@/hooks/useConsoleAnalytics'
+import { ProductAnalyticsProvider } from '../ProductAnalyticsPreferences'
+import { ConsoleTrackerFixture } from '../tests/ConsoleTrackerFixture'
+vi.mock('@/hooks/useConsoleAnalytics', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/hooks/useConsoleAnalytics')>()
+ return { ...actual, recordConsoleOnboardingStep: vi.fn(actual.recordConsoleOnboardingStep) }
+})
const api = vi.hoisted(() => ({
profile: vi.fn(),
+ post: vi.fn(),
+ getConsent: vi.fn(),
+ saveConsent: vi.fn(),
rename: vi.fn(),
save: vi.fn(),
credits: vi.fn(),
@@ -19,6 +29,7 @@ const api = vi.hoisted(() => ({
}))
vi.mock('@/hooks/useApi', () => ({
useApi: () => ({
+ axiosInstance: { post: api.post, get: api.getConsent, put: api.saveConsent },
getOrganizationOnboarding: api.profile,
saveOrganizationOnboarding: api.save,
organizationsApi: { updateOrganizationName: api.rename },
@@ -36,8 +47,15 @@ vi.mock('@/hooks/useSelectedOrganization', () => ({
}),
}))
vi.mock('@/hooks/useOrganizations', () => ({ useOrganizations: () => ({ refreshOrganizations: api.refresh }) }))
-vi.mock('@/hooks/useConfig', () => ({ useConfig: () => ({ billingApiUrl: api.billingApiUrl }) }))
-vi.mock('react-oidc-context', () => ({ useAuth: () => ({ user: { profile: { sub: api.userId } } }) }))
+vi.mock('@/hooks/useConfig', () => ({
+ useConfig: () => ({
+ billingApiUrl: api.billingApiUrl,
+ posthog: { host: 'https://example.invalid', apiKey: 'phc_test' },
+ }),
+}))
+vi.mock('react-oidc-context', () => ({
+ useAuth: () => ({ isAuthenticated: true, user: { profile: { sub: api.userId } } }),
+}))
vi.mock('./FirstBoxAtmosphere', () => ({
default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}))
@@ -45,6 +63,8 @@ let host: HTMLDivElement, root: Root, client: QueryClient
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
vi.resetAllMocks()
+ api.post.mockResolvedValue({})
+ api.getConsent.mockResolvedValue({ data: { allowed: null, enabledFrom: null } })
api.billingApiUrl = 'https://billing.example.test'
localStorage.clear()
api.organizationId = 'org-1'
@@ -69,15 +89,22 @@ async function settle() {
await new Promise((r) => setTimeout(r, 20))
})
}
-async function mount() {
+async function mount(withConsent = false) {
+ const routes = (
+ <Routes>
+ <Route path="/dashboard/welcome" element={<FirstBoxWelcome />} />
+ <Route path="/dashboard/quickstart" element={<p>Quickstart destination</p>} />
+ </Routes>
+ )
await act(async () =>
root.render(
<QueryClientProvider client={client}>
- <MemoryRouter initialEntries={['/welcome']}>
- <Routes>
- <Route path="/welcome" element={<FirstBoxWelcome />} />
- <Route path="/dashboard/quickstart" element={<p>Quickstart destination</p>} />
- </Routes>
+ <MemoryRouter initialEntries={['/dashboard/welcome']}>
+ {withConsent ? (
+ <ProductAnalyticsProvider>{routes}</ProductAnalyticsProvider>
+ ) : (
+ <ConsoleTrackerFixture organizationId={api.organizationId}>{routes}</ConsoleTrackerFixture>
+ )}
</MemoryRouter>
</QueryClientProvider>,
),
@@ -99,9 +126,46 @@ async function input(id: string, value: string) {
e.dispatchEvent(new Event('input', { bubbles: true }))
})
}
+it('continues through Welcome with the analytics checkbox unchecked', async () => {
+ await mount(true)
+ expect(host.querySelector<HTMLInputElement>('#welcome-product-analytics')?.checked).toBe(false)
+ await input('welcome-organization', 'New team')
+ await act(async () => host.querySelector<HTMLInputElement>('#welcome-terms')!.click())
+ await click('Continue')
+ expect(api.rename).toHaveBeenCalledWith('org-1', { name: 'New team' })
+ expect(api.saveConsent).not.toHaveBeenCalled()
+ expect(host.textContent).toContain('What are you building?')
+ expect(host.querySelector('#welcome-product-analytics')).toBeNull()
+})
+it('locks the Welcome analytics opt-in without making Continue wait for it', async () => {
+ await mount(true)
+ await input('welcome-organization', 'New team')
+ const analytics = host.querySelector<HTMLInputElement>('#welcome-product-analytics')!
+ const terms = host.querySelector<HTMLInputElement>('#welcome-terms')!
+ const submit = host.querySelector<HTMLButtonElement>('button[type="submit"]')!
+ const grant = Promise.withResolvers<{ data: { allowed: boolean } }>()
+ api.getConsent.mockResolvedValue({ data: { allowed: true, enabledFrom: new Date().toISOString() } })
+ api.saveConsent.mockReturnValueOnce(grant.promise)
+ await act(async () => analytics.click())
+ expect(analytics.disabled).toBe(true)
+ expect(terms.checked).toBe(false)
+ expect(submit.disabled).toBe(true)
+ await act(async () => terms.click())
+ expect(submit.disabled).toBe(false)
+ await act(async () => grant.resolve({ data: { allowed: true } }))
+ await settle()
+ expect(analytics.checked).toBe(true)
+ expect(analytics.disabled).toBe(true)
+ await act(async () => analytics.click())
+ expect(analytics.checked).toBe(true)
+ expect(api.saveConsent).toHaveBeenCalledExactlyOnceWith('/analytics/consent', { allowed: true, version: 1 })
+ await click('Continue')
+ expect(host.textContent).toContain('What are you building?')
+})
it('saves the name and selected intent before offering optional credits', async () => {
await mount()
expect(host.textContent).toContain('Name your organization')
+ expect(recordConsoleOnboardingStep).toHaveBeenCalledExactlyOnceWith('org_create_started', 'org-1')
await input('welcome-organization', 'New team')
expect(host.querySelector<HTMLButtonElement>('button[type="submit"]')!.disabled).toBe(true)
await act(async () => host.querySelector<HTMLInputElement>('#welcome-terms')!.click())
@@ -112,6 +176,20 @@ it('saves the name and selected intent before offering optional credits', async
await input('welcome-note', 'Run an agent overnight')
await click('Continue')
expect(api.save).toHaveBeenCalledWith('org-1', { useCase: 'long-running-agent', note: 'Run an agent overnight' })
+ expect(recordConsoleOnboardingStep).toHaveBeenLastCalledWith('use_case_selected', 'org-1', 'long-running-agent')
+ const steps = api.post.mock.calls.filter(([, body]) => body.event !== '$pageview')
+ expect(steps).toEqual(
+ [
+ { action: 'org_create_started' },
+ { action: 'org_name_submit_click', control: 'button' },
+ { action: 'use_case_submit_click', control: 'button' },
+ { action: 'use_case_selected', selection: 'long-running-agent' },
+ ].map((properties) => [
+ '/analytics/organizations/org-1/console-events',
+ expect.objectContaining({ event: 'console_onboarding_step', ...properties }),
+ expect.any(Object),
+ ]),
+ )
expect(host.textContent).toContain('3 Get credits')
expect(host.textContent).toContain('Verify card')
expect(api.credits).not.toHaveBeenCalled()
@@ -127,6 +205,12 @@ it('restores saved intent, supports going back, and keeps failed submissions ret
expect(host.querySelector<HTMLTextAreaElement>('#welcome-note')!.value).toBe('Saved note')
await click('Back')
expect(host.querySelector<HTMLInputElement>('#welcome-organization')!.value).toBe('Existing workspace')
+ const interactions = api.post.mock.calls.filter(([, body]) => body.event !== '$pageview')
+ expect(interactions.map(([, body]) => [body.event, body.action, body.control])).toEqual([
+ ['console_onboarding_step', 'welcome_back_to_use_case_click', 'button'],
+ ['console_onboarding_step', 'welcome_back_to_org_click', 'button'],
+ ['console_onboarding_step', 'org_create_started', undefined],
+ ])
await act(async () => host.querySelector<HTMLInputElement>('#welcome-terms')!.click())
await click('Continue')
await act(async () => host.querySelector<HTMLInputElement>('input[value="exploring"]')!.click())
@@ -212,3 +296,18 @@ it('keeps another organization on its own unfinished credits step', async () =>
completedAt: expect.any(Number),
})
})
+
+it('continues to Quickstart when reporting a successful Welcome save throws', async () => {
+ api.billingApiUrl = ''
+ localStorage.setItem('boxlite:welcome:user-1:org-1', JSON.stringify({ organizationName: 'Existing workspace' }))
+ api.save.mockResolvedValue({})
+ vi.mocked(recordConsoleOnboardingStep).mockImplementation(() => {
+ throw Error('analytics unavailable')
+ })
+ await mount()
+ await act(async () => host.querySelector<HTMLInputElement>('input[value="exploring"]')!.click())
+ await click('Start quickstart')
+ expect(recordConsoleOnboardingStep).toHaveBeenCalledExactlyOnceWith('use_case_selected', 'org-1', 'exploring')
+ expect(client.getQueryData(['organization-onboarding', 'org-1'])).toMatchObject({ useCase: 'exploring' })
+ expect(host.textContent).toContain('Quickstart destination')
+})
diff --git a/apps/dashboard/src/components/first-run/FirstBoxWelcome.tsx b/apps/dashboard/src/components/first-run/FirstBoxWelcome.tsx
index 527a7b9da..a398bef04 100644
--- a/apps/dashboard/src/components/first-run/FirstBoxWelcome.tsx
+++ b/apps/dashboard/src/components/first-run/FirstBoxWelcome.tsx
@@ -1,6 +1,7 @@
/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
import { Button } from '@/components/ui/button'
-import { lazy, Suspense, useState } from 'react'
+import { WelcomeAnalyticsConsent } from '@/components/ProductAnalyticsPreferences'
+import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { Navigate } from 'react-router-dom'
import { AsciiButton } from '@/components/ascii'
import { Check, ChevronRight, Code2, Terminal, Globe, Bot, Container, SparklesIcon } from '@/components/ui/icon'
@@ -8,6 +9,7 @@ import { useApi } from '@/hooks/useApi'
import { useQuery } from '@tanstack/react-query'
import { useAuth } from 'react-oidc-context'
import { useSelectedOrganization } from '@/hooks/useSelectedOrganization'
+import { recordConsoleOnboardingStep } from '@/hooks/useConsoleAnalytics'
import { useWelcomeOnboarding } from '@/hooks/useWelcomeOnboarding'
import { RoutePath } from '@/enums/RoutePath'
import { FIRST_RUN_USE_CASES, type FirstRunWelcome, type FirstRunUseCase } from '@/lib/first-run'
@@ -76,6 +78,7 @@ export default function FirstBoxWelcome() {
return (
<WelcomeForm
key={`trial:${user?.profile.sub}:${orgId}`}
+ organizationId={selectedOrganization.id}
initial={
new URLSearchParams(window.location.search).get('step') === 'plans'
? { organizationName: selectedOrganization.name, useCase: 'exploring', note: '', completedAt: null }
@@ -83,14 +86,36 @@ export default function FirstBoxWelcome() {
}
/>
)
- return <WelcomeForm key={`${user?.profile.sub}:${orgId}`} initial={initial} />
+ return (
+ <WelcomeForm key={`${user?.profile.sub}:${orgId}`} initial={initial} organizationId={selectedOrganization.id} />
+ )
}
-function WelcomeForm({ initial }: { initial: FirstRunWelcome }) {
- const { welcome, action, complete, billingEnabled } = useWelcomeOnboarding(initial)
+function WelcomeForm({ initial, organizationId }: { initial: FirstRunWelcome; organizationId: string }) {
+ const active = useRef(false)
+ useLayoutEffect(() => {
+ active.current = true
+ return () => {
+ active.current = false
+ }
+ }, [])
+ const { welcome, action, complete, billingEnabled } = useWelcomeOnboarding(
+ initial,
+ (savedOrganizationId, useCase) => {
+ if (!trialPreviewEnabled && active.current)
+ recordConsoleOnboardingStep('use_case_selected', savedOrganizationId, useCase)
+ },
+ )
const [step, setStep] = useState<'organization' | 'intent' | 'credits'>(
billingEnabled && welcome.useCase ? 'credits' : welcome.organizationName ? 'intent' : 'organization',
)
+ const lastStep = useRef<typeof step | null>(null)
+ useEffect(() => {
+ if (!trialPreviewEnabled && welcome.completedAt == null && step === 'organization' && lastStep.current !== step) {
+ recordConsoleOnboardingStep('org_create_started', organizationId)
+ }
+ lastStep.current = step
+ }, [organizationId, step, welcome.completedAt])
const [termsAccepted, setTermsAccepted] = useState(false)
const [name, setName] = useState(welcome.organizationName)
const [useCase, setUseCase] = useState<FirstRunUseCase | null>(welcome.useCase)
@@ -201,10 +226,12 @@ function WelcomeForm({ initial }: { initial: FirstRunWelcome }) {
.
</span>
</div>
+ <WelcomeAnalyticsConsent />
<AsciiButton
type="submit"
variant="primary"
className="mt-8 h-11 w-full font-display"
+ data-console-action="org_name_submit_click"
disabled={!name.trim() || !termsAccepted || action.isPending}
>
{action.isPending ? 'Saving…' : 'Continue'}
@@ -294,6 +321,7 @@ function WelcomeForm({ initial }: { initial: FirstRunWelcome }) {
<div className="mt-5 flex items-center justify-between">
<button
type="button"
+ data-console-action={trialPreviewEnabled ? undefined : 'welcome_back_to_org_click'}
disabled={action.isPending}
className="py-2 text-body text-muted-foreground underline-offset-4 hover:text-foreground focus-visible:underline"
onClick={() => {
@@ -307,6 +335,7 @@ function WelcomeForm({ initial }: { initial: FirstRunWelcome }) {
type="submit"
variant="primary"
className="h-10 min-w-[120px] border border-transparent px-6 font-display text-body focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:border-border disabled:bg-card disabled:text-muted-foreground disabled:opacity-100"
+ data-console-action="use_case_submit_click"
disabled={!useCase || action.isPending}
>
{action.isPending
diff --git a/apps/dashboard/src/components/first-run/WelcomeCreditsStep.test.tsx b/apps/dashboard/src/components/first-run/WelcomeCreditsStep.test.tsx
index a1790201c..dedb01e92 100644
--- a/apps/dashboard/src/components/first-run/WelcomeCreditsStep.test.tsx
+++ b/apps/dashboard/src/components/first-run/WelcomeCreditsStep.test.tsx
@@ -3,6 +3,8 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
+import { MemoryRouter } from 'react-router-dom'
+import { ConsoleTrackerFixture } from '../tests/ConsoleTrackerFixture'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import WelcomeCreditsStep from './WelcomeCreditsStep'
@@ -12,8 +14,8 @@ const billingApi = vi.hoisted(() => ({
getOrganizationCheckoutUrl: vi.fn(),
redeemCoupon: vi.fn(),
}))
-const membership = vi.hoisted(() => ({ role: 'owner' }))
-vi.mock('@/hooks/useApi', () => ({ useApi: () => ({ billingApi }) }))
+const membership = vi.hoisted(() => ({ role: 'owner', post: vi.fn() }))
+vi.mock('@/hooks/useApi', () => ({ useApi: () => ({ billingApi, axiosInstance: { post: membership.post } }) }))
vi.mock('@/hooks/useSelectedOrganization', () => ({
useSelectedOrganization: () => ({
selectedOrganization: { id: 'org-1', name: 'Acme', isDefaultForAuthenticatedUser: true },
@@ -46,6 +48,7 @@ beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
vi.resetAllMocks()
membership.role = 'owner'
+ membership.post.mockResolvedValue({})
billingApi.getOrganizationWallet.mockResolvedValue(wallet)
billingApi.listAllPaymentMethods.mockResolvedValue([])
billingApi.getOrganizationCheckoutUrl.mockResolvedValue(checkoutUrl)
@@ -90,7 +93,11 @@ async function renderStep() {
await act(async () => {
root.render(
<QueryClientProvider client={client}>
- <WelcomeCreditsStep onBack={onBack} onContinue={onContinue} useCase="coding-agent" />
+ <MemoryRouter initialEntries={['/dashboard/welcome']}>
+ <ConsoleTrackerFixture>
+ <WelcomeCreditsStep onBack={onBack} onContinue={onContinue} useCase="coding-agent" />
+ </ConsoleTrackerFixture>
+ </MemoryRouter>
</QueryClientProvider>,
)
})
@@ -128,6 +135,11 @@ it('shows the card offer, promo input and an Explore exit before any payment act
expect(billingApi.getOrganizationCheckoutUrl).not.toHaveBeenCalled()
expect(billingApi.redeemCoupon).not.toHaveBeenCalled()
await click('Explore with BoxLite')
+ expect(membership.post).toHaveBeenLastCalledWith(
+ '/analytics/organizations/org-1/console-events',
+ expect.objectContaining({ event: 'console_onboarding_step', action: 'explore_boxlite_click', control: 'button' }),
+ expect.any(Object),
+ )
expect(onContinue).toHaveBeenCalledTimes(1)
})
@@ -210,6 +222,11 @@ it('uses hosted checkout and confirms a connected card from a fresh wallet read
expect(host.textContent).not.toContain('Save your card')
expect(host.textContent).not.toContain('Card connected')
expect(billingApi.getOrganizationCheckoutUrl).toHaveBeenCalledWith('org-1')
+ expect(membership.post).toHaveBeenLastCalledWith(
+ '/analytics/organizations/org-1/console-events',
+ expect.objectContaining({ event: 'console_onboarding_step', action: 'verify_card_click' }),
+ expect.any(Object),
+ )
await act(async () => resolveCheckout(checkoutUrl))
await eventually(() => expect(checkoutWindow.location.href).toBe(checkoutUrl))
@@ -230,6 +247,11 @@ it('uses hosted checkout and confirms a connected card from a fresh wallet read
expect(host.textContent).not.toContain('Your credits are ready.')
expect(onContinue).not.toHaveBeenCalled()
await click('Start quickstart')
+ expect(membership.post).toHaveBeenLastCalledWith(
+ '/analytics/organizations/org-1/console-events',
+ expect.objectContaining({ event: 'console_onboarding_step', action: 'start_quickstart_click', control: 'button' }),
+ expect.any(Object),
+ )
expect(onContinue).toHaveBeenCalledTimes(1)
})
@@ -244,6 +266,11 @@ it('offers a card-status retry after a failed return read without treating check
expect(onContinue).not.toHaveBeenCalled()
billingApi.getOrganizationWallet.mockResolvedValue({ ...wallet, creditCardConnected: true })
await click('Check card status')
+ expect(membership.post).toHaveBeenLastCalledWith(
+ '/analytics/organizations/org-1/console-events',
+ expect.objectContaining({ event: 'console_onboarding_step', action: 'check_card_status_click', control: 'button' }),
+ expect.any(Object),
+ )
await eventually(() => expect(host.textContent).toContain('Card connected'))
})
@@ -307,6 +334,12 @@ it('redeems the entered code and shows the server message without declaring a cr
await click('Redeem')
await eventually(() => expect(host.textContent).toContain(message))
expect(billingApi.redeemCoupon).toHaveBeenCalledWith('org-1', 'BoXlite20')
+ expect(membership.post).toHaveBeenLastCalledWith(
+ '/analytics/organizations/org-1/console-events',
+ expect.objectContaining({ event: 'console_onboarding_step', action: 'redeem_click' }),
+ expect.any(Object),
+ )
+ expect(JSON.stringify(membership.post.mock.calls)).not.toContain('BoXlite20')
expect(billingApi.getOrganizationWallet.mock.calls.length).toBeGreaterThan(1)
expect(host.textContent).not.toContain('$20')
expect(host.textContent).not.toContain('Your credits are ready.')
diff --git a/apps/dashboard/src/components/first-run/WelcomeCreditsStep.tsx b/apps/dashboard/src/components/first-run/WelcomeCreditsStep.tsx
index ca87c258b..6f9342697 100644
--- a/apps/dashboard/src/components/first-run/WelcomeCreditsStep.tsx
+++ b/apps/dashboard/src/components/first-run/WelcomeCreditsStep.tsx
@@ -159,6 +159,7 @@ export default function WelcomeCreditsStep({
<AsciiButton
variant="primary"
className="flex h-12 items-center justify-between px-5 font-display text-body"
+ data-console-action="start_quickstart_click"
onClick={onContinue}
>
Start quickstart <ArrowRightIcon aria-hidden className="size-4" />
@@ -168,6 +169,7 @@ export default function WelcomeCreditsStep({
variant="primary"
disabled={busy}
className="flex h-12 items-center justify-between px-5 font-display text-body"
+ data-console-action="verify_card_click"
onClick={() => {
setCheckoutStarted(true)
void connectCard()
@@ -193,6 +195,7 @@ export default function WelcomeCreditsStep({
{(checkoutStarted || wallet.isError) && (
<button
type="button"
+ data-console-action="check_card_status_click"
onClick={refreshCard}
disabled={wallet.isFetching || paymentMethods.isFetching}
className="mt-3 text-meta text-muted-foreground underline-offset-4 hover:underline disabled:opacity-40"
@@ -245,7 +248,12 @@ export default function WelcomeCreditsStep({
aria-describedby={couponError ? 'welcome-promo-error' : undefined}
className="h-11 min-w-0 flex-1 border border-border bg-background px-3 font-mono text-body outline-none focus:border-foreground disabled:opacity-50"
/>
- <AsciiButton type="submit" disabled={busy} className="h-11 px-4 font-display text-body">
+ <AsciiButton
+ type="submit"
+ disabled={busy}
+ className="h-11 px-4 font-display text-body"
+ data-console-action="redeem_click"
+ >
Redeem
</AsciiButton>
</div>
@@ -264,6 +272,7 @@ export default function WelcomeCreditsStep({
<button
type="button"
disabled={busy}
+ data-console-action="welcome_back_to_use_case_click"
onClick={onBack}
className="py-2 text-body text-muted-foreground underline-offset-4 hover:text-foreground hover:underline disabled:opacity-40"
>
@@ -271,6 +280,7 @@ export default function WelcomeCreditsStep({
</button>
<button
type="button"
+ data-console-action="explore_boxlite_click"
onClick={onContinue}
className="flex items-center gap-2 py-2 text-body underline-offset-4 hover:underline"
>
diff --git a/apps/dashboard/src/components/first-run/WelcomePlanOptions.tsx b/apps/dashboard/src/components/first-run/WelcomePlanOptions.tsx
index 461c1d800..72ba655fa 100644
--- a/apps/dashboard/src/components/first-run/WelcomePlanOptions.tsx
+++ b/apps/dashboard/src/components/first-run/WelcomePlanOptions.tsx
@@ -1,5 +1,6 @@
/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
import { AsciiButton } from '@/components/ascii'
+import { planTierIndex } from '@/components/billing/planBenefits'
import { RoutePath } from '@/enums/RoutePath'
import { useOwnerPlanQuery, useOwnerTrialEligibilityQuery } from '@/hooks/queries/billingQueries'
import { usePlansQuery } from '@/hooks/queries/usePlansQuery'
@@ -39,6 +40,7 @@ export default function WelcomePlanOptions() {
</h2>
<ul className="mt-4 space-y-2">
{plans.map((plan) => {
+ const tier = planTierIndex(plan.name)
const duration = trialDuration(offers?.find((offer) => offer.name === plan.name))
return (
<li
@@ -54,6 +56,7 @@ export default function WelcomePlanOptions() {
</div>
<AsciiButton
size="sm"
+ data-console-action={tier === 1 ? 'choose_starter_click' : tier === 2 ? 'choose_team_click' : undefined}
onClick={() =>
navigate(generatePath(RoutePath.BILLING_PLAN_CHANGE, { planId: plan.id }), {
state: { welcomeSubscription },
diff --git a/apps/dashboard/src/components/tests/ConsoleTrackerFixture.tsx b/apps/dashboard/src/components/tests/ConsoleTrackerFixture.tsx
new file mode 100644
index 000000000..f13d99d7a
--- /dev/null
+++ b/apps/dashboard/src/components/tests/ConsoleTrackerFixture.tsx
@@ -0,0 +1,14 @@
+/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
+import type { ReactNode } from 'react'
+import { useConsoleAnalytics } from '@/hooks/useConsoleAnalytics'
+
+export function ConsoleTrackerFixture({
+ children,
+ organizationId = 'org-1',
+}: {
+ children: ReactNode
+ organizationId?: string
+}) {
+ useConsoleAnalytics(organizationId, new Date(0).toISOString())
+ return children
+}
diff --git a/apps/dashboard/src/components/tests/ProductAnalyticsPreferences.test.tsx b/apps/dashboard/src/components/tests/ProductAnalyticsPreferences.test.tsx
index c70396507..3779683ba 100644
--- a/apps/dashboard/src/components/tests/ProductAnalyticsPreferences.test.tsx
+++ b/apps/dashboard/src/components/tests/ProductAnalyticsPreferences.test.tsx
@@ -6,13 +6,13 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, Link } from 'react-router-dom'
import { getByRole, queryByRole } from '@testing-library/dom'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
-import {
- AnalyticsConsentCard,
- ProductAnalyticsProvider,
- ProductAnalyticsSettings,
-} from '../ProductAnalyticsPreferences'
+import { ProductAnalyticsProvider, ProductAnalyticsSettings } from '../ProductAnalyticsPreferences'
import { captureSignupEntry } from '@/lib/signup-attribution'
-import { recordConsoleTabSelection } from '@/hooks/useConsoleAnalytics'
+import { recordConsoleOnboardingStep, recordConsoleTabSelection } from '@/hooks/useConsoleAnalytics'
+import { BOX_TEMPLATES } from '@/lib/quickstart/box-templates'
+import { getOnboardingInterfaces } from '@/lib/onboarding-code-examples'
+import { validOnboardingInteraction } from '../../../../shared/console-analytics'
+import { RoutePath } from '@/enums/RoutePath'
const http = vi.hoisted(() => ({ get: vi.fn(), put: vi.fn(), post: vi.fn() }))
vi.mock('@/hooks/useApi', () => ({ useApi: () => ({ axiosInstance: http }) }))
@@ -33,15 +33,21 @@ let organizationId: string
let allowed: boolean | null
const pause = () => new Promise<void>((r) => setTimeout(r, 5))
-async function mount() {
+async function mount(path = '/dashboard/boxes?secret=raw-query') {
await act(async () => {
root.render(
<QueryClientProvider client={client}>
- <MemoryRouter initialEntries={['/dashboard/boxes?secret=raw-query']}>
+ <MemoryRouter initialEntries={[path]}>
<ProductAnalyticsProvider>
- <AnalyticsConsentCard />
<ProductAnalyticsSettings />
<button data-console-action="new_box">Private project name</button>
+ <button data-console-action="quickstart_template_selected" data-console-selection="pgvector">
+ Select pgvector
+ </button>
+ <button data-console-action="quickstart_template_create_click">Create Box</button>
+ <div data-console-tab-selections>
+ <button role="tab">Raw SDK click</button>
+ </div>
<Link to="/dashboard/boxes/private-box-id?utm_source=private-referrer">Open private box</Link>
<div className="xterm">
<button>terminal content</button>
@@ -87,9 +93,9 @@ afterEach(async () => {
it('starts off, ignores the old browser choice, and sends only subsequent sanitized activity', async () => {
localStorage.setItem('privacy_consent_person', JSON.stringify({ analytics: true }))
await mount()
- expect(getByRole(host, 'heading', { name: 'Share usage analytics?' })).toBeTruthy()
+ expect(getByRole(host, 'switch', { name: 'Product analytics' }).getAttribute('aria-checked')).toBe('false')
await click('Private project name')
- await click('Allow analytics')
+ await click('Product analytics', 'switch')
expect(http.put).toHaveBeenCalledWith('/analytics/consent', { allowed: true, version: 1 })
expect(http.post).not.toHaveBeenCalled()
await click('terminal content')
@@ -116,12 +122,11 @@ it('starts off, ignores the old browser choice, and sends only subsequent saniti
await click('Private project name')
expect(http.post).toHaveBeenCalledTimes(4)
})
-it('saves No thanks, hides the prompt, and leaves product interactions available', async () => {
+it('keeps analytics off if a user continues without granting consent', async () => {
await mount()
- await click('No thanks')
- expect(queryByRole(host, 'heading', { name: 'Share usage analytics?' })).toBeNull()
expect(getByRole(host, 'switch', { name: 'Product analytics' }).getAttribute('aria-checked')).toBe('false')
await click('Open private box', 'link')
+ expect(http.put).not.toHaveBeenCalled()
expect(http.post).not.toHaveBeenCalled()
})
it('honors an existing grant on the first admitted view and skips failed preference reads', async () => {
@@ -205,7 +210,6 @@ it('can retry after a failed preference read and keeps a saved refusal off', asy
expect(getByRole(host, 'switch', { name: 'Product analytics' }).hasAttribute('disabled')).toBe(true)
await click('Refresh')
expect(queryByRole(host, 'alert')).toBeNull()
- expect(queryByRole(host, 'heading', { name: 'Share usage analytics?' })).toBeNull()
expect(getByRole(host, 'switch', { name: 'Product analytics' }).getAttribute('aria-checked')).toBe('false')
expect(http.post).not.toHaveBeenCalled()
})
@@ -281,3 +285,43 @@ it('sends a pending signup source only after the Settings grant is saved', async
expect(claims()).toHaveLength(1)
expect(claims()[0][1]).toMatchObject({ source: 't.co', kind: 'referrer' })
})
+
+it('sends one onboarding event per tagged Quickstart interaction', async () => {
+ allowed = true
+ await mount('/dashboard/quickstart')
+ expect(http.post.mock.calls.map(([, event]) => event.event)).toEqual(['$pageview'])
+ http.post.mockClear()
+ await click('Select pgvector')
+ await click('Select pgvector')
+ await click('Create Box')
+ await click('Raw SDK click', 'tab')
+ await act(async () => recordConsoleTabSelection('quickstart_sdk_tab_selected', 'python'))
+ expect(http.post.mock.calls.map(([, event]) => [event.event, event.action, event.selection])).toEqual([
+ ['console_onboarding_step', 'quickstart_template_selected', 'pgvector'],
+ ['console_onboarding_step', 'quickstart_template_selected', 'pgvector'],
+ ['console_onboarding_step', 'quickstart_template_create_click', undefined],
+ ['console_onboarding_step', 'quickstart_sdk_tab_selected', 'python'],
+ ])
+})
+
+it('drops Welcome steps before grant and from a different organization', async () => {
+ await mount('/dashboard/welcome')
+ await act(async () => recordConsoleOnboardingStep('org_create_started', organizationId))
+ await click('Product analytics', 'switch')
+ expect(http.post).not.toHaveBeenCalled()
+ await act(async () => recordConsoleOnboardingStep('use_case_selected', 'old-org', 'browser-agent'))
+ await act(async () => recordConsoleOnboardingStep('org_create_started', organizationId))
+ expect(http.post).toHaveBeenCalledTimes(1)
+ expect(http.post.mock.calls[0][1]).toMatchObject({ event: 'console_onboarding_step', action: 'org_create_started' })
+})
+
+it('admits every public Quickstart interface and template ID', () => {
+ for (const [action, control, entries] of [
+ ['quickstart_sdk_tab_selected', 'tab', getOnboardingInterfaces()],
+ ['quickstart_template_selected', 'button', BOX_TEMPLATES],
+ ] as const) {
+ for (const { id } of entries) {
+ expect(validOnboardingInteraction({ page: RoutePath.QUICKSTART, action, control, selection: id })).toBe(true)
+ }
+ }
+})
diff --git a/apps/dashboard/src/hooks/useConsoleAnalytics.ts b/apps/dashboard/src/hooks/useConsoleAnalytics.ts
index f02257d2b..eb3b05bd6 100644
--- a/apps/dashboard/src/hooks/useConsoleAnalytics.ts
+++ b/apps/dashboard/src/hooks/useConsoleAnalytics.ts
@@ -4,22 +4,39 @@ import {
consoleActions,
consoleControls,
consolePages,
+ validOnboardingInteraction,
type ConsoleInteraction,
} from '../../../shared/console-analytics'
import { billingTab } from '@/lib/billing-tab'
+import type { FirstRunUseCase } from '@/lib/first-run'
import { RoutePath } from '@/enums/RoutePath'
import { useConfig } from './useConfig'
import { useApi } from './useApi'
-const tabSelections = new EventTarget()
+const explicitInteractions = new EventTarget()
+type ExplicitInteraction =
+ | { action: string; selection?: string; control: 'tab' }
+ | { action: 'org_create_started' | 'use_case_selected'; organizationId: string; selection?: FirstRunUseCase }
const routes = [
...consolePages.filter((route) => !route.includes(':')),
...consolePages.filter((route) => route.includes(':')),
]
const consolePage = (path: string) => routes.find((route) => matchPath(route, path))
-export function recordConsoleTabSelection(action: string) {
- tabSelections.dispatchEvent(new CustomEvent('select', { detail: action }))
+function recordExplicitInteraction(detail: ExplicitInteraction) {
+ explicitInteractions.dispatchEvent(new CustomEvent('interaction', { detail }))
+}
+
+export function recordConsoleTabSelection(action: string, selection?: string) {
+ recordExplicitInteraction({ action, selection, control: 'tab' })
+}
+
+export function recordConsoleOnboardingStep(
+ action: 'org_create_started' | 'use_case_selected',
+ organizationId: string,
+ selection?: FirstRunUseCase,
+) {
+ recordExplicitInteraction({ action, organizationId, selection })
}
/** Record only transitions and interactions that occur during an active grant. */
@@ -73,6 +90,11 @@ export function useConsoleAnalytics(organizationId: string, enabledFrom: string
view.sent = true
send('$pageview', view.at)
}
+ const sendOnboarding = (action: string | undefined, control?: string, selection?: string) => {
+ if (!validOnboardingInteraction({ page, action, control, selection })) return false
+ send('console_onboarding_step', new Date(), { action, control, selection })
+ return true
+ }
const click = (event: MouseEvent) => {
if (
!(event.target instanceof Element) ||
@@ -84,7 +106,9 @@ export function useConsoleAnalytics(organizationId: string, enabledFrom: string
const control = target.getAttribute('role') ?? target.tagName.toLowerCase()
if (!consoleControls.includes(control) || (control === 'tab' && target.closest('[data-console-tab-selections]')))
return
- const action = target.getAttribute('data-console-action')
+ const action = target.getAttribute('data-console-action') ?? undefined
+ const selection = target.getAttribute('data-console-selection') ?? undefined
+ if (sendOnboarding(action, control, selection)) return
const destination =
target instanceof HTMLAnchorElement && target.origin === window.location.origin
? consolePage(target.pathname)
@@ -95,14 +119,21 @@ export function useConsoleAnalytics(organizationId: string, enabledFrom: string
destination,
})
}
- const select = (event: Event) => {
- const action = (event as CustomEvent<string>).detail
- if (consoleActions.includes(action)) send('console_control_click', new Date(), { control: 'tab', action })
+ const record = (event: Event) => {
+ const { detail } = event as CustomEvent<ExplicitInteraction>
+ if ('organizationId' in detail) {
+ if (detail.organizationId === organizationId) sendOnboarding(detail.action, undefined, detail.selection)
+ return
+ }
+ const { action, control, selection } = detail
+ if (!sendOnboarding(action, control, selection) && consoleActions.includes(action)) {
+ send('console_control_click', new Date(), { control, action })
+ }
}
- tabSelections.addEventListener('select', select)
+ explicitInteractions.addEventListener('interaction', record)
document.addEventListener('click', click, true)
return () => {
- tabSelections.removeEventListener('select', select)
+ explicitInteractions.removeEventListener('interaction', record)
document.removeEventListener('click', click, true)
}
}, [api, enabledFrom, billingApiUrl, key, organizationId, pathname, search])
diff --git a/apps/dashboard/src/hooks/useWelcomeOnboarding.ts b/apps/dashboard/src/hooks/useWelcomeOnboarding.ts
index 5b09775a5..3321270e4 100644
--- a/apps/dashboard/src/hooks/useWelcomeOnboarding.ts
+++ b/apps/dashboard/src/hooks/useWelcomeOnboarding.ts
@@ -10,7 +10,10 @@ import { recordWelcomeCompletion, type FirstRunWelcome, type FirstRunUseCase } f
import { LocalStorageKey } from '@/enums/LocalStorageKey'
import { setLocalStorageItem } from '@/lib/local-storage'
-export function useWelcomeOnboarding(initial: FirstRunWelcome) {
+export function useWelcomeOnboarding(
+ initial: FirstRunWelcome,
+ onUseCaseSaved?: (organizationId: string, useCase: FirstRunUseCase) => void,
+) {
const api = useApi()
const { selectedOrganization } = useSelectedOrganization()
const { refreshOrganizations } = useOrganizations()
@@ -50,6 +53,11 @@ export function useWelcomeOnboarding(initial: FirstRunWelcome) {
}
await api.saveOrganizationOnboarding(organizationId, { useCase: payload.useCase, note: payload.note.trim() })
active.signal.throwIfAborted()
+ try {
+ onUseCaseSaved?.(organizationId, payload.useCase)
+ } catch {
+ // The completed save continues even if reporting fails.
+ }
client.setQueryData(['organization-onboarding', organizationId], {
useCase: payload.useCase,
note: payload.note.trim(),
diff --git a/apps/dashboard/src/pages/BillingPlanChange.tsx b/apps/dashboard/src/pages/BillingPlanChange.tsx
index 9c6a429a3..fdf2b72dd 100644
--- a/apps/dashboard/src/pages/BillingPlanChange.tsx
+++ b/apps/dashboard/src/pages/BillingPlanChange.tsx
@@ -5,6 +5,7 @@
import { AsciiButton, Panel, PanelNote, SectionTitle } from '@/components/ascii'
import { PlanChangeNote, PlanComparison, planChangeSummary } from '@/components/billing/planChange'
+import { planTierIndex } from '@/components/billing/planBenefits'
import { ArrowLeft, RefreshCcw } from '@/components/ui/icon'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
@@ -156,6 +157,8 @@ function BillingPlanChange() {
? summary.target
: null
+ const welcomeTier = welcomePlan ? planTierIndex(welcomePlan.name) : -1
+
// An unknown plan id, or one the viewer already has, has no confirmation to
// show. `replace` keeps Back from bouncing straight back into the redirect.
if (summary.blocked?.redirect || (welcomeSubscription && !welcomePlan)) {
@@ -295,7 +298,9 @@ function BillingPlanChange() {
<AsciiButton
variant="primary"
disabled={pending}
- data-console-action="confirm_plan_change"
+ data-console-action={
+ welcomeTier === 1 ? 'starter_sub_click' : welcomeTier === 2 ? 'team_sub_click' : 'confirm_plan_change'
+ }
onClick={handleConfirm}
className="inline-flex items-center gap-2"
>
diff --git a/apps/dashboard/src/pages/Dashboard.tsx b/apps/dashboard/src/pages/Dashboard.tsx
index 4dbce63e4..0bd38628d 100644
--- a/apps/dashboard/src/pages/Dashboard.tsx
+++ b/apps/dashboard/src/pages/Dashboard.tsx
@@ -6,7 +6,7 @@
import React, { Suspense, useEffect, useMemo, useState } from 'react'
import { matchPath, Outlet, useLocation } from 'react-router-dom'
-import { ProductAnalyticsProvider, AnalyticsConsentCard } from '@/components/ProductAnalyticsPreferences'
+import { ProductAnalyticsProvider } from '@/components/ProductAnalyticsPreferences'
import { SetupHeader } from '@/components/SetupLayout'
import { OnboardingEntryGate } from '@/components/OnboardingEntryGate'
import { RoutePath } from '@/enums/RoutePath'
@@ -80,7 +80,6 @@ const Dashboard: React.FC = () => {
{/* Lazy route components (Admin/Billing/Settings/box-details) suspend
here so only the content area shows a fallback — the sidebar/shell
stays mounted across navigation. */}
- <AnalyticsConsentCard />
<Suspense
fallback={
<div className="space-y-3 p-4 sm:p-5">
diff --git a/apps/dashboard/src/pages/tests/BillingUpgradeReturn.test.tsx b/apps/dashboard/src/pages/tests/BillingUpgradeReturn.test.tsx
index acf24ea56..3197f33ec 100644
--- a/apps/dashboard/src/pages/tests/BillingUpgradeReturn.test.tsx
+++ b/apps/dashboard/src/pages/tests/BillingUpgradeReturn.test.tsx
@@ -8,6 +8,7 @@ import { toast } from 'sonner'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { BoxliteError } from '@/api/errors'
import FirstBoxWelcome from '@/components/first-run/FirstBoxWelcome'
+import { ConsoleTrackerFixture } from '@/components/tests/ConsoleTrackerFixture'
import { RoutePath } from '@/enums/RoutePath'
import Billing from '../Billing'
import BillingPlanChange from '../BillingPlanChange'
@@ -21,12 +22,17 @@ const api = vi.hoisted(() => ({
getUsagePrices: vi.fn(),
listAllPaymentMethods: vi.fn(),
listPlans: vi.fn(),
+ post: vi.fn(),
upgradePlan: vi.fn(),
}))
const viewer = vi.hoisted(() => ({ organizationId: 'org-1', userId: 'user-1', role: 'owner' }))
vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn(), info: vi.fn() } }))
vi.mock('@/hooks/useApi', () => ({
- useApi: () => ({ billingApi: api, getOrganizationOnboarding: api.getOrganizationOnboarding }),
+ useApi: () => ({
+ billingApi: api,
+ axiosInstance: { post: api.post },
+ getOrganizationOnboarding: api.getOrganizationOnboarding,
+ }),
}))
vi.mock('@/hooks/useOrganizations', () => ({ useOrganizations: () => ({ refreshOrganizations: vi.fn() }) }))
vi.mock('@/components/first-run/FirstBoxAtmosphere', () => ({
@@ -75,6 +81,7 @@ beforeEach(() => {
api.getPlanTrialEligibility.mockResolvedValue([{ name: pro.name, eligible: true, durationSeconds: 259_200 }])
api.listAllPaymentMethods.mockResolvedValue([])
api.listPlans.mockResolvedValue([pro])
+ api.post.mockResolvedValue({})
api.getUsagePrices.mockResolvedValue({ schemaVersion: 1, currency: 'USD', prices: [] })
api.upgradePlan.mockResolvedValueOnce(setupUrl).mockResolvedValue(undefined)
location = new URL(window.location.href)
@@ -115,12 +122,14 @@ async function visit(path: string) {
<StrictMode>
<QueryClientProvider client={client}>
<MemoryRouter initialEntries={[path]}>
- <Routes>
- <Route path={RoutePath.BILLING_PLAN_CHANGE} element={<BillingPlanChange />} />
- <Route path={RoutePath.BILLING} element={<Billing />} />
- <Route path={RoutePath.WELCOME} element={<FirstBoxWelcome />} />
- <Route path={RoutePath.QUICKSTART} element={<h1>Quickstart</h1>} />
- </Routes>
+ <ConsoleTrackerFixture organizationId={viewer.organizationId}>
+ <Routes>
+ <Route path={RoutePath.BILLING_PLAN_CHANGE} element={<BillingPlanChange />} />
+ <Route path={RoutePath.BILLING} element={<Billing />} />
+ <Route path={RoutePath.WELCOME} element={<FirstBoxWelcome />} />
+ <Route path={RoutePath.QUICKSTART} element={<h1>Quickstart</h1>} />
+ </Routes>
+ </ConsoleTrackerFixture>
</MemoryRouter>
</QueryClientProvider>
</StrictMode>,
@@ -287,9 +296,9 @@ it('opens ordinary Billing with a connected card without submitting an upgrade',
const welcomeProgressKey = 'boxlite:welcome:user-1:org-1'
-async function chooseWelcomePlan() {
+async function chooseWelcomePlan(name = 'Pro') {
await visit(RoutePath.WELCOME)
- const choose = () => [...host.querySelectorAll('button')].find((button) => button.textContent === 'Choose Pro')
+ const choose = () => [...host.querySelectorAll('button')].find((button) => button.textContent === 'Choose ' + name)
await eventually(() => {
expect(choose()).toBeDefined()
expect(host.textContent).toContain('3 days free')
@@ -324,6 +333,29 @@ async function expectWelcomeCompleted() {
expect(JSON.parse(localStorage.getItem(welcomeProgressKey)!)).toMatchObject({ completedAt: expect.any(Number) })
}
+it.each([
+ ['Starter', 'choose_starter_click', 'starter_sub_click'],
+ ['Team', 'choose_team_click', 'team_sub_click'],
+])('reports Welcome %s choice and subscription under the active organization', async (name, choose, subscribe) => {
+ api.listPlans.mockResolvedValue([{ ...pro, name }])
+ api.getPlanTrialEligibility.mockResolvedValue([{ name, eligible: true, durationSeconds: 259_200 }])
+ await chooseWelcomePlan(name)
+ await subscribeFromWelcome()
+ const onboarding = api.post.mock.calls.filter(([, body]) => body.event === 'console_onboarding_step')
+ expect(onboarding).toEqual([
+ [
+ '/analytics/organizations/org-1/console-events',
+ expect.objectContaining({ action: choose, page: RoutePath.WELCOME }),
+ expect.any(Object),
+ ],
+ [
+ '/analytics/organizations/org-1/console-events',
+ expect.objectContaining({ action: subscribe, page: RoutePath.BILLING_PLAN_CHANGE }),
+ expect.any(Object),
+ ],
+ ])
+})
+
it('Welcome subscription confirms the paid terms before card setup and submits exactly once after verification', async () => {
api.listPlans.mockResolvedValue([{ ...pro, priceMonthlyCents: 14_925 }])
api.upgradePlan.mockReset().mockImplementation(async () => {
diff --git a/apps/shared/console-analytics.ts b/apps/shared/console-analytics.ts
index 47169516e..335fa0946 100644
--- a/apps/shared/console-analytics.ts
+++ b/apps/shared/console-analytics.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
import { RoutePath } from './console-routes'
+import { ONBOARDING_USE_CASES } from './onboarding-use-cases'
export const consolePages = Object.values(RoutePath).filter((page) => page.startsWith('/dashboard/'))
export const consoleActions = [
@@ -37,6 +38,88 @@ export const consoleActions = [
'view_custom_domains',
'view_managed_domains',
]
+export const consoleEventNames = ['$pageview', 'console_control_click', 'console_onboarding_step'] as const
+
+type OnboardingInteraction = { page: RoutePath; control?: string; selections?: readonly string[] }
+
+const welcomeStep = { page: RoutePath.WELCOME }
+const welcomeClick = { ...welcomeStep, control: 'button' }
+const subscriptionClick = { page: RoutePath.BILLING_PLAN_CHANGE, control: 'button' }
+const quickstartClick = { page: RoutePath.QUICKSTART, control: 'button' }
+
+const onboardingInteractions: Readonly<Record<string, OnboardingInteraction>> = {
+ org_create_started: welcomeStep,
+ org_name_submit_click: welcomeClick,
+ use_case_submit_click: welcomeClick,
+ welcome_back_to_org_click: welcomeClick,
+ welcome_back_to_use_case_click: welcomeClick,
+ check_card_status_click: welcomeClick,
+ explore_boxlite_click: welcomeClick,
+ start_quickstart_click: welcomeClick,
+ use_case_selected: { ...welcomeStep, selections: ONBOARDING_USE_CASES },
+ choose_starter_click: welcomeClick,
+ choose_team_click: welcomeClick,
+ starter_sub_click: subscriptionClick,
+ team_sub_click: subscriptionClick,
+ verify_card_click: welcomeClick,
+ redeem_click: welcomeClick,
+ quickstart_code_copied: quickstartClick,
+ quickstart_template_create_click: quickstartClick,
+ quickstart_prompt_prepared: quickstartClick,
+ quickstart_prompt_copied: quickstartClick,
+ quickstart_deploy_mode_selected: { ...quickstartClick, selections: ['sdk_cli', 'console', 'prompt'] },
+ quickstart_sdk_tab_selected: {
+ ...quickstartClick,
+ control: 'tab',
+ selections: ['python', 'typescript', 'go', 'rust', 'c', 'cli', 'rest'],
+ },
+ quickstart_template_selected: {
+ ...quickstartClick,
+ selections: [
+ 'python',
+ 'node',
+ 'go',
+ 'rust',
+ 'linux',
+ 'uv',
+ 'bun',
+ 'maven',
+ 'gcc',
+ 'browserless',
+ 'crawl4ai',
+ 'lightpanda',
+ 'jupyter',
+ 'scipy',
+ 'r',
+ 'gotenberg',
+ 'tika',
+ 'ocr',
+ 'pandoc',
+ 'ffmpeg',
+ 'qdrant',
+ 'pgvector',
+ 'valkey',
+ 'wiremock',
+ 'k6',
+ ],
+ },
+}
+export const onboardingActions = Object.keys(onboardingInteractions)
+
+export function validOnboardingInteraction({
+ page,
+ action,
+ control,
+ selection,
+}: Pick<ConsoleInteraction, 'page' | 'action' | 'control' | 'selection'>): boolean {
+ if (!action || !Object.hasOwn(onboardingInteractions, action)) return false
+ const expected = onboardingInteractions[action]
+ if (expected.page !== page || expected.control !== control) return false
+ return expected.selections
+ ? selection !== undefined && expected.selections.includes(selection)
+ : selection === undefined
+}
+
export const billingTabs = ['overview', 'plans', 'usage', 'wallet']
export const consoleControls = ['a', 'button', 'menuitem', 'tab']
export const analyticsNoticeVersion = 1
@@ -44,11 +127,12 @@ export const analyticsNoticeVersion = 1
export type AnalyticsPreference = { allowed: boolean | null; version: number; decidedAt: string | null }
export type ConsoleInteraction = {
- event: '$pageview' | 'console_control_click'
+ event: (typeof consoleEventNames)[number]
page: RoutePath
occurredAt: string
control?: string
destination?: RoutePath
action?: string
+ selection?: string
billingTab?: string
}
diff --git a/apps/shared/onboarding-use-cases.ts b/apps/shared/onboarding-use-cases.ts
new file mode 100644
index 000000000..77bc02e3b
--- /dev/null
+++ b/apps/shared/onboarding-use-cases.ts
@@ -0,0 +1,11 @@
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+
+export const ONBOARDING_USE_CASES = [
+ 'coding-agent',
+ 'code-execution',
+ 'browser-agent',
+ 'long-running-agent',
+ 'application-deployments',
+ 'reinforcement-learning',
+ 'exploring',
+] as const