• Skip to main content
  • Skip to navigation
  • Skip to search
    Petunia™
    FeaturesPricingIntegrationsAboutContact
    Log inStart free trialSign up
    Loading
    Petunia™

    Reimagining customer communication for the modern business.

    Product

    • Features
    • Pricing
    • Integrations
    • Roadmap
    • What's New

    Resources

    • Help Center
    • Documentation
    • Guides
    • API Reference
    • Community
    • Support

    Company

    • About Us
    • Careers
    • Blog
    • Press
    • Contact

    © 2026 Gray Group International LLC. All rights reserved.·
    Made by gardenpatch 🌱

    Privacy PolicyTerms of ServiceCookie PolicyData Processing Agreement

    Petunia™ is a trademark of Gray Group International LLC. The Petunia name, brand, product design, and content are proprietary. Unauthorized use, imitation, or copying is prohibited.

    Documentation

    ONBOARDING

    docs/features/ONBOARDING.md
    Docs homeGuidesSupport
    Quick links
    Start here
    How the docs are organized.
    Environment setup
    Configure env + run locally.
    Unified Inbox
    Inbox concepts & behavior.
    Voice setup
    Providers, Twilio, testing.
    Pricing model
    Source-of-truth pricing.
    Operations runbook
    How to operate safely.

    Onboarding Experience - Feature Documentation

    Owner: Casey Nguyen Version: 0.5.0

    OwnerLast verifiedNext verification dueLast CI run IDCoverage %Open risks
    Casey Nguyen2025-12-052026-01-04ci.yml#219298.0 (jest coverage for onboarding hooks)Voice onboarding sandbox not load-tested; Supabase demo seed only; hydration regression risk without Cypress reruns

    Verification

    • CI jobs: ci.yml API + Cypress (last run: ci.yml#2192)
    • Commands (seeded demo portal; never use production tenants):
      • pnpm test:api --config jest.config.api.cjs --runTestsByPath tests/app/api/onboarding/complete/route.test.ts tests/app/api/onboarding/resume/route.test.ts tests/app/api/onboarding/availability/route.test.ts
      • pnpm test -- --runTestsByPath tests/lib/hooks/onboarding/useOnboardingState.test.ts tests/lib/hooks/onboarding/useOnboardingAvailability.test.ts
      • pnpm cypress:run --spec "cypress/e2e/onboarding/onboarding-flow.cy.ts","cypress/e2e/onboarding/onboarding-hydration.cy.ts"
      • pnpm db:health
    • Test suites + environment:
      • tests/app/api/onboarding/complete/route.test.ts, .../resume/route.test.ts, .../availability/route.test.ts (CI seeded demo DB; Supabase mocked)
      • tests/lib/hooks/onboarding/useOnboardingState.test.ts, useOnboardingAvailability.test.ts (unit coverage driving 98% lines)
      • cypress/e2e/onboarding/onboarding-flow.cy.ts, onboarding-hydration.cy.ts (staging demo portal; avoids real clients)
    • Next verification due: 2026-01-04

    1. Problem / Job-to-Be-Done

    The Problem

    New users who sign up for Petunia face a cold start problem:

    • They don't know what the platform can do for them
    • They need to configure their business profile before getting value
    • Traditional form-based onboarding is tedious and has high abandonment rates
    • If something breaks during onboarding, users get stuck and leave forever

    Why It Matters

    Business Impact:

    • First impressions determine whether a user becomes a paying customer
    • Onboarding completion rate directly correlates with conversion to paid plans
    • Users who complete onboarding are 3-5x more likely to activate features

    User Pain Points:

    • "I signed up but don't know what to do next"
    • "The setup process is too long"
    • "I got an error and now I'm stuck"
    • "I don't have time to fill out forms"

    Job-to-Be-Done

    "When I sign up for a business tool, I want to get started quickly with minimal friction, so that I can see value without investing significant time upfront."


    2. Solution Overview

    Summary

    A multi-modal, AI-powered onboarding experience that feels like a conversation with a helpful assistant named Petunia. Users choose their preferred interaction style (voice call, browser voice, or text chat), and Petunia extracts their business information naturally through conversation.

    Outcome

    Users complete business profile setup in 2-3 minutes through natural conversation, with their Company, Portal, and preferences automatically created. They arrive at their dashboard ready to use the platform.

    Key User Flows

    ┌─────────────────────────────────────────────────────────────────┐
    │                      USER JOURNEY                                │
    ├─────────────────────────────────────────────────────────────────┤
    │  1. Signup complete → Cookie set → Redirect to /onboarding      │
    │  2. Welcome animation plays (personalized greeting)             │
    │  3. User selects mode: Voice Call | Browser Voice | Text Chat   │
    │  4. Petunia asks: name, business name, industry                 │
    │  5. Summary screen shows extracted data (editable)              │
    │  6. User confirms → Database records created                    │
    │  7. Redirect to /dashboard?from=onboarding                      │
    └─────────────────────────────────────────────────────────────────┘
    

    Key Flow Notes

    • Voice Call: Retell calls user's phone, AI conducts conversation
    • Browser Voice: Cartesia WebSocket for real-time mic + TTS
    • Text Chat: Sequential state machine with progress indicators (collect name → business → industry)
    • Quick Setup: 3-step form fallback when AI unavailable
    • Emergency Skip: Always available - users are never stuck
    • Session Replay: Sentry captures all onboarding sessions for debugging

    3. Scope

    What's Included (v0.4.0)

    • Three interaction modes (voice call, browser voice, text chat)
    • Welcome animation with time-based personalization
    • AI-powered natural conversation
    • Smart data extraction from conversation
    • Editable summary screen before confirmation
    • Database transaction (Company, Portal, User creation)
    • Supabase user_metadata sync
    • Vector database storage (Upstash, Pinecone)
    • Graceful degradation to Quick Setup
    • Emergency skip fallback
    • Resume interrupted onboarding
    • Service availability health checks
    • Mobile-optimized UI
    • Orphan Supabase user cleanup via cron job
    • Partial signup recovery during signin
    • Unit tests for feature flag and authentication guards

    What's Explicitly Out of Scope

    • Video onboarding option
    • Multi-language support
    • Team member onboarding (only business owner)
    • Integration setup during onboarding (happens post-onboarding)
    • Custom branding for white-label
    • Onboarding analytics dashboard
    • A/B testing different flows

    4. Acceptance Criteria (Gherkin)

    Voice Call Mode

    GIVEN a new user has completed signup
      AND they have a valid phone number
      AND Retell API is available
    WHEN they select "Voice Call" mode and enter their phone number
    THEN Petunia should call their phone within 10 seconds
      AND conduct a natural conversation to collect business info
      AND display a summary screen when the call ends
      AND create their Company and Portal on confirmation
    

    Browser Voice Mode

    GIVEN a new user has completed signup
      AND they grant microphone permission
      AND Cartesia API is available
    WHEN they select "Browser Voice" mode
    THEN a WebSocket connection should be established
      AND they can speak naturally to Petunia
      AND Petunia responds with synthesized speech
      AND business info is extracted and shown in summary
    

    Text Chat Mode

    GIVEN a new user has completed signup
      AND Anthropic or OpenAI API is available
    WHEN they select "Text Chat" mode
    THEN they should see a progress indicator (Step 1 of 3)
      AND Petunia asks for their name first
      AND after name is collected, Petunia asks for business name (Step 2)
      AND after business name, Petunia asks for industry (Step 3)
      AND the progress bar fills as each step completes
      AND summary screen shows all extracted data
    

    Graceful Degradation

    GIVEN a new user is in onboarding
      AND all AI services become unavailable
    WHEN the system detects service unavailability
    THEN the user should see a non-blocking notification
      AND be offered the Quick Setup form
      AND still be able to complete onboarding
    

    Emergency Skip

    GIVEN a new user is stuck in onboarding
      AND they click "Skip for now" or the emergency fallback triggers
    WHEN the emergency completion runs
    THEN completion cookies should be set
      AND the user should be redirected to dashboard
      AND they should NOT be redirected back to onboarding
    

    Session Recovery

    GIVEN a user started onboarding but didn't complete
      AND they return to /onboarding
    WHEN the page loads
    THEN their previous progress should be restored
      AND they should see a prompt to resume or start fresh
    

    5. Dependencies & Risks

    Dependencies

    DependencyTypeRequiredFallback
    Retell APIExternalNoBrowser voice or text
    Cartesia APIExternalNoText chat
    Anthropic APIExternalNoOpenAI
    OpenAI APIExternalNoQuick Setup form
    Supabase AuthInternalYesNone (auth required)
    PostgreSQLInternalYesNone (data storage)
    PineconeExternalNoUpstash
    Upstash VectorExternalNoSkip vector storage

    Risks & Mitigations

    RiskSeverityLikelihoodMitigation
    All AI services downHighLowQuick Setup form fallback
    User stuck in loopCriticalLowEmergency skip, safety timeout
    Session not propagatingMediumMediumVerification retry (10 attempts)
    PID collisionLowVery LowTransaction retry (3 attempts)
    Microphone permission deniedMediumMediumFall back to text mode
    Phone number invalidLowLowValidation + error message
    Database transaction failsHighLowDetailed error codes, retry logic

    Trade-offs Made

    1. Complexity vs. Reliability: Multiple fallback layers add code complexity but ensure users never get stuck
    2. Performance vs. Features: Vector DB storage is async/non-blocking to not slow completion
    3. UX vs. Data Collection: We collect minimal required data (name, business, industry) to reduce friction

    6. Technical Approach

    Architecture

    ┌─────────────────────────────────────────────────────────────────┐
    │                         CLIENT LAYER                             │
    ├─────────────────────────────────────────────────────────────────┤
    │  app/(client)/onboarding/page.tsx        Main orchestrator      │
    │  components/onboarding/                   UI components          │
    │  lib/hooks/onboarding/                    State management       │
    └─────────────────────────────────────────────────────────────────┘
                                  │
                                  ▼
    ┌─────────────────────────────────────────────────────────────────┐
    │                          API LAYER                               │
    ├─────────────────────────────────────────────────────────────────┤
    │  /api/onboarding/init          Session initialization           │
    │  /api/onboarding/availability  Service health checks            │
    │  /api/onboarding/complete      Database transaction             │
    │  /api/chat/onboarding          Streaming AI conversation        │
    │  /api/voice/onboarding         Voice call initiation            │
    └─────────────────────────────────────────────────────────────────┘
                                  │
                                  ▼
    ┌─────────────────────────────────────────────────────────────────┐
    │                       SERVICE LAYER                              │
    ├─────────────────────────────────────────────────────────────────┤
    │  Retell API          Phone calls                                │
    │  Cartesia API        Browser voice (WebSocket)                  │
    │  Anthropic API       Text conversation                          │
    │  Supabase Auth       User metadata                              │
    │  PostgreSQL          Company, Portal, User records              │
    │  Pinecone/Upstash    Vector embeddings for AI context           │
    └─────────────────────────────────────────────────────────────────┘
    

    Key Components

    ComponentLocationPurpose
    OnboardingPageapp/(client)/onboarding/page.tsxMain orchestrator
    PetuniaVoiceOnboardingcomponents/onboarding/PetuniaVoiceOnboarding.tsxMulti-mode UI
    WelcomeAnimationcomponents/onboarding/WelcomeAnimation.tsxAnimated intro
    useOnboardingStatelib/hooks/onboarding/useOnboardingState.tsSession/PID management
    useOnboardingAvailabilitylib/hooks/onboarding/useOnboardingAvailability.tsService health
    useBrowserVoicelib/hooks/voice/useBrowserVoice.tsCartesia WebSocket
    completion.tslib/onboarding/completion.tsClient-side completion

    Implementation Notes

    State Management:

    • useOnboardingState consolidates 8+ individual state checks into one hook
    • Safety timeout (2s) forces content display to prevent blank screens
    • PID resolution: URL param → Session storage → API

    Completion Transaction:

    // Atomic transaction creates all required records
    await prisma.$transaction(async (tx) => {
      const company = await tx.company.create({ ... });
      await tx.userCompany.create({ userId, companyId, role: 'OWNER' });
      const portal = await tx.portal.create({ petuniaID: generatePID() });
      await tx.userPortalAccess.create({ userId, portalId, role: 'owner' });
      await tx.user.update({ onboardingCompleted: true });
      await tx.onboardingData.create({ ... });
    });
    

    Fallback Chain:

    Voice Call → Browser Voice → Text Chat → Quick Setup → Emergency Skip
    

    Security Considerations

    AspectImplementation
    AuthenticationSession required for all API routes
    CSRFaddCSRFToken() on form submissions
    Input ValidationvalidateBusinessName(), validateIndustry(), sanitizeInput()
    Phone NumbersServer-side validation before Retell call
    Rate LimitingStandard API rate limits apply
    Data IsolationUser can only access their own onboarding data

    7. Testing Strategy

    Unit Tests

    Test FileCoverageStatus
    tests/app/api/onboarding/init/route.test.tsInit endpoint✅
    tests/app/api/onboarding/availability/route.test.tsHealth checks✅
    tests/app/api/onboarding/complete/route.test.tsCompletion logic11 pass, 11 skip*
    tests/app/api/onboarding/resume/route.test.tsResume flow✅
    tests/lib/onboarding/completion.test.tsClient completion✅
    tests/lib/hooks/onboarding/useOnboardingState.test.tsState hook✅
    tests/components/onboarding/hydration.test.tsxHydration stability✅
    tests/app/onboarding/blank-screen.test.tsxBlank screen prevention✅

    *Skipped Test Coverage (11 tests in route.test.ts)

    Skipped CategoryTestsE2E Coverage
    Company/Portal Creation5onboarding-flow.cy.ts Tests 1-3: Email/Google signup → completion
    Supabase Metadata Update3onboarding-flow.cy.ts Test 1: Full auth flow verification
    Request Body Handling2onboarding-flow.cy.ts Tests 1-3: Various input scenarios
    PID Retry Success1Production monitoring (Sentry orphan-cleanup-hourly)

    Technical note: The route uses prisma.$transaction(async (tx) => {...}) callback pattern. Jest can mock rejection paths (mockRejectedValue) but cannot execute the callback to return success values. Error paths (11 tests) are fully covered.

    Integration Tests

    ScenarioStatus
    Auth → Onboarding → Dashboard flowCovered
    Supabase metadata syncCovered
    Cookie/localStorage persistenceCovered

    E2E Tests (Cypress)

    Test FileCoverage
    cypress/e2e/onboarding/onboarding-flow.cy.tsFull user journey: signup → onboarding → dashboard
    cypress/e2e/onboarding/onboarding-hydration.cy.tsHydration stability, localStorage persistence

    Cron Jobs

    CronSchedulePurpose
    /api/cron/orphan-cleanupEvery 6 hoursCleanup orphaned Supabase users from failed signups

    Orphan cleanup is monitored by Sentry: orphan-cleanup-hourly

    Manual Testing Required

    ScenarioStatus
    Voice call mode end-to-end⏳ Pending
    Browser voice mode end-to-end⏳ Pending
    Text chat mode end-to-end⏳ Pending
    Graceful degradation (kill APIs)⏳ Pending
    Emergency skip from each mode⏳ Pending
    Resume after browser close⏳ Pending

    Performance Tests

    MetricTargetStatus
    Page load time< 2sNot measured
    Time to interactive< 3sNot measured
    Completion API response< 500msNot measured

    Security Tests

    TestStatus
    CSRF token validation✅ Implemented
    Input sanitization✅ Implemented
    Auth required on all endpoints✅ Implemented
    No PII in logs✅ Verified

    8. Metrics & Success Criteria

    Primary KPI

    Onboarding Completion Rate

    • Target: > 85% of users who start onboarding complete it
    • Current: Not measured (pending analytics)

    Secondary Metrics

    MetricTargetNotes
    Time to Complete< 3 minutesFrom landing on /onboarding to dashboard
    Mode Selection DistributionTrackWhich modes users prefer
    Fallback Usage Rate< 10%How often Quick Setup is used
    Emergency Skip Rate< 2%How often users need to skip
    Resume RateTrackHow many users return to complete
    Drop-off PointsIdentifyWhere users abandon

    Service Level Objectives (SLOs)

    SLOTarget
    Onboarding page availability99.9%
    Completion API success rate99.5%
    Voice service availability95% (fallbacks available)
    Time to first content< 2 seconds

    9. Rollout & Release Plan

    Feature Flag

    // lib/config/flags.ts
    ONBOARDING: toBoolean(process.env['FEATURE_ONBOARDING'], true),
    
    • Flag Name: FEATURE_ONBOARDING
    • Default: true (enabled)
    • Can be disabled per-environment

    Rollout Phases

    PhaseAudienceStatus
    1. DevelopmentInternal team✅ Complete
    2. StagingQA testers✅ Complete
    3. BetaFirst 50 users⏳ Pending manual testing
    4. General AvailabilityAll users⏳ Pending beta feedback

    Migration Considerations

    • Existing users (pre-onboarding): Already have onboarding_completed=true via migration
    • New users: Go through full onboarding flow
    • No data migration required

    Release Notes Draft

    ## New: Personalized Onboarding Experience
    
    Meet Petunia, your AI assistant! New users can now set up their business through:
    - **Voice Call**: Get a call from Petunia on your phone
    - **Browser Voice**: Talk through your computer's microphone
    - **Text Chat**: Have a conversation via chat
    
    All methods extract your business info automatically - no forms to fill out!
    

    10. Observability & Monitoring

    Sentry Session Replay

    Session replay is enabled for /onboarding route via SentryReplayProvider:

    // app/(client)/onboarding/layout.tsx
    <SentryReplayProvider enableReplay context="onboarding">
      {children}
    </SentryReplayProvider>
    

    Features:

    • Session replay is captured based on the global Sentry sampling config (production is sampled; sessions with errors are captured at a higher rate)
    • Privacy-first: all text and inputs are masked
    • Tagged with replay_context: "onboarding" for filtering
    • Breadcrumbs provide timeline of key events
    • Welcome animation pauses heavy background cloud animations while the full-screen overlay is visible (reduces jank in replays and on-device)

    How to find the onboarding replay in Sentry:

    • Filter Replays by tag replay_context:onboarding
    • Look for breadcrumbs like Welcome animation phase changed to confirm timing
    • To force the welcome animation to show again, load onboarding with ?force_welcome=true

    Sentry Breadcrumbs

    EventCategoryLevel
    Welcome animation enteredonboardinginfo
    Welcome animation phase changedonboardinginfo
    Welcome animation skippedonboardinginfo
    Welcome animation completedonboardinginfo
    Mode changedonboardinginfo
    Voice call initiatedonboardinginfo
    Voice call completedonboardinginfo
    Voice call failedonboardingwarning
    Text data extractedonboardinginfo
    Text mode completeonboardinginfo
    AI marked complete prematurelyonboardingwarning

    Logs

    LoggerLocationLevel
    onboarding-state-hookClientINFO, DEBUG
    onboarding-complete-apiServerINFO, ERROR
    onboarding-availabilityServerINFO, WARN
    use-onboarding-availabilityClientINFO, ERROR

    Key Log Events:

    • Onboarding completion started
    • Portal init successful
    • Voice service health check failed
    • Emergency completion triggered
    • Session verification succeeded/failed

    Metrics to Track

    MetricTypeTags
    onboarding.startedCountermode, user_id
    onboarding.completedCountermode, duration
    onboarding.abandonedCountermode, step
    onboarding.fallback_usedCounterfrom_mode, to_mode
    onboarding.emergency_skipCounterreason
    onboarding.api_latencyHistogramendpoint

    Alerts

    AlertConditionSeverity
    High emergency skip rate> 5% in 1 hourWarning
    Completion API errors> 5% error rateCritical
    All voice services down0 availableWarning
    Completion rate drop< 50% in 1 hourCritical

    Dashboards

    Proposed Panels:

    1. Completion funnel by mode
    2. Drop-off by step
    3. API latency percentiles
    4. Fallback usage over time
    5. Error rate by endpoint

    11. Documentation

    Technical Specs

    DocumentLocation
    This feature docdocs/features/ONBOARDING.md
    QA Verification Checklistdocs/QA/ONBOARDING_CHECKLIST.md
    Voice environment setupdocs/VOICE_ENV_VARIABLES.md
    Auth + onboarding flowdocs/AUTHENTICATION_ONBOARDING_GUIDE.md

    Related PRs

    PRDescription
    eb9a49303Pass userName to WelcomeAnimation
    5bf29fbb5Complete signup-onboarding integration overhaul
    892c44ec0Add onboarding flow E2E tests
    8c00c48bcAdd welcome animation personalization
    1e18a564cAdd in-browser voice mode
    17d0953cdAdd availability awareness, quick setup validation
    e77b9cad2Wire streaming API, resume persistence
    f5b96c3edAdd APIs, hooks, analytics, tests

    Runbooks

    User Stuck in Onboarding Loop:

    1. Check onboarding_completed cookie exists
    2. Verify Supabase user_metadata.onboardingCompleted = true
    3. Check User table onboardingCompleted = true
    4. If all true but still looping, clear cookies and try again

    Voice Services Down:

    1. Check /api/onboarding/availability response
    2. Verify API keys in environment variables
    3. Check external service status pages
    4. Users should auto-fallback to Quick Setup

    12. Architecture Deep-Dive

    API Routes (12 endpoints)

    RouteMethodPurposeRuntime
    /api/onboarding/initGETInitialize session, get/create PIDNode.js
    /api/onboarding/availabilityGETCheck voice/text service healthNode.js
    /api/onboarding/ai/processPOSTProcess AI conversation turnNode.js
    /api/onboarding/ai/ttsPOSTGenerate text-to-speech audioNode.js
    /api/onboarding/businessPOSTSave business profile dataNode.js
    /api/onboarding/completePOSTComplete onboarding, create portalNode.js
    /api/onboarding/dataGET/POSTGet/save onboarding progressNode.js
    /api/onboarding/progressGET/POSTTrack step progressNode.js
    /api/onboarding/resumeGETResume interrupted onboardingNode.js
    /api/onboarding/enhancePOSTAI-enhance business dataNode.js
    /api/chat/onboardingPOSTStreaming chat for text modeNode.js
    /api/voice/onboardingPOSTVoice call initiationNode.js

    Hooks

    useOnboardingState

    interface OnboardingStateResult {
      mounted: boolean;
      canShowContent: boolean;
      isNewUser: boolean;
      pidResult: { pid: string | null; source: 'url' | 'session' | 'api' | 'none' };
      session: any;
      authLoading: boolean;
      sessionHydrated: boolean;
      initCompleted: boolean;
      initError: InitError | null;
      shouldShowVoiceOnboarding: boolean;
      shouldShowLoading: boolean;
      isForceShowingContent: boolean;
      retryInit: () => void;
      forceShowContent: () => void;
    }
    

    useOnboardingAvailability

    interface UseOnboardingAvailabilityReturn {
      voice: ModeAvailability;
      text: ModeAvailability;
      quickSetup: ModeAvailability;
      isLoading: boolean;
      error: string | null;
      lastChecked: Date | null;
      refresh: () => Promise<void>;
      isAnyModeAvailable: boolean;
      preferredMode: 'voice' | 'text' | 'quick-setup';
    }
    

    Data Collected

    interface OnboardingData {
      userName?: string;
      businessName?: string;
      industry?: string;
      businessSize?: string;
      location?: string;
      phoneNumber?: string;
      priorities?: string[];
      onboardingMethod?: 'voice-call' | 'voice-browser' | 'text' | 'quick-setup' | 'skipped';
      isVoiceOnboarding?: boolean;
    }
    

    Completion Transaction

    The /api/onboarding/complete endpoint performs an atomic transaction:

    1. Company: Create if not exists, link user as OWNER
    2. Portal: Create with unique 9-digit PID
    3. UserPreference: Set default portal
    4. User: Mark onboardingCompleted = true
    5. OnboardingData: Store for analytics
    6. CompanySettings: Configure based on priorities
    7. AutoresponderSettings: Enable based on mode used

    Post-transaction (async):

    • Update Supabase user_metadata
    • Store in Upstash Vector
    • Store in Pinecone with real embeddings

    13. Environment Variables

    Required

    VariablePurpose
    CARTESIA_API_KEYBrowser voice mode
    RETELL_API_KEYVoice call mode
    ANTHROPIC_API_KEYText chat (primary)

    Optional

    VariablePurposeDefault
    ELEVENLABS_API_KEYTTS fallback-
    OPENAI_API_KEYText fallback-
    CARTESIA_VOICE_IDVoice IDPetunia's voice
    NEXT_PUBLIC_RETELL_AGENT_IDAgent ID-
    FEATURE_ONBOARDINGFeature flagtrue

    14. Troubleshooting

    Common Issues

    IssueCauseSolution
    Blank screenSession not readySafety timeout forces content after 2s
    Voice mode unavailableAPI key missingSet CARTESIA_API_KEY or RETELL_API_KEY
    Text mode not respondingAPI key missingSet ANTHROPIC_API_KEY or OPENAI_API_KEY
    Redirect loop after completionMetadata not syncedClear cookies, verify Supabase metadata
    PID collision errorRare (1 in 900M)Auto-retry 3 times

    Debug Commands

    # Check availability endpoint
    curl -X GET http://localhost:3000/api/onboarding/availability \
      -H "Cookie: <session_cookie>"
    
    # Check init endpoint
    curl -X GET http://localhost:3000/api/onboarding/init \
      -H "Cookie: <session_cookie>"
    

    15. File Reference

    Core Files

    FileLinesPurpose
    app/(client)/onboarding/page.tsx~320Main page
    app/(client)/onboarding/layout.tsx~145Layout with Sentry replay
    components/onboarding/PetuniaVoiceOnboarding.tsx~2300Multi-mode UI with state machine
    components/onboarding/WelcomeAnimation.tsx~465Animated intro with breadcrumbs
    lib/onboarding/completion.ts~450Completion logic
    lib/hooks/onboarding/useOnboardingState.ts~550State hook
    lib/providers/SentryReplayProvider.tsx~80Session replay provider
    app/api/onboarding/complete/route.ts~620Completion API

    All Related Files

    app/(client)/onboarding/
    ├── page.tsx
    ├── layout.tsx
    └── error.tsx
    
    components/onboarding/
    ├── PetuniaVoiceOnboarding.tsx
    ├── WelcomeAnimation.tsx
    ├── CloudBackground.tsx
    ├── OnboardingErrorFallback.tsx
    └── index.ts
    
    lib/onboarding/
    ├── types.ts
    ├── completion.ts
    ├── validation.ts
    ├── conversation.ts
    ├── ai-engine.ts
    ├── persist.ts
    └── ...
    
    lib/hooks/onboarding/
    ├── useOnboardingState.ts
    └── useOnboardingAvailability.ts
    
    lib/providers/
    └── SentryReplayProvider.tsx
    
    app/api/onboarding/
    ├── init/route.ts
    ├── availability/route.ts
    ├── complete/route.ts
    ├── resume/route.ts
    ├── ai/process/route.ts
    ├── ai/tts/route.ts
    ├── business/route.ts
    ├── data/route.ts
    ├── progress/route.ts
    └── enhance/route.ts
    
    tests/
    ├── app/api/onboarding/...
    ├── lib/onboarding/...
    ├── lib/hooks/onboarding/...
    └── components/onboarding/...
    
    cypress/e2e/onboarding/
    ├── onboarding-flow.cy.ts
    └── onboarding-hydration.cy.ts
    

    16. Completion Checklist

    Implementation

    • Three interaction modes (voice call, browser voice, text)
    • Welcome animation with personalization
    • AI-powered conversation
    • Smart data extraction
    • Editable summary screen
    • Database transaction
    • Supabase metadata sync
    • Vector DB storage
    • Graceful degradation
    • Emergency skip
    • Resume persistence
    • Service health checks
    • Mobile-optimized UI

    Testing

    • Unit tests (101 passing)
    • E2E test files created
    • Manual E2E: Voice call mode
    • Manual E2E: Browser voice mode
    • Manual E2E: Text chat mode
    • Manual E2E: Graceful degradation
    • Manual E2E: Emergency skip
    • Manual E2E: Resume flow

    Documentation

    • Feature spec complete
    • Environment variables documented
    • Troubleshooting guide
    • File reference

    Observability

    • Logging implemented
    • Sentry session replay enabled
    • Sentry breadcrumbs instrumented
    • Custom metrics collection
    • Alert configuration
    • Dashboard creation

    Version History

    VersionDateChanges
    0.5.02025-12-05Production hardening: text chat state machine with progress indicators, voice call timer fixes (no-answer/busy handling), Sentry session replay for all onboarding sessions, comprehensive breadcrumb instrumentation
    0.4.42025-12-04UX fixes: text mode completion validation, call status accuracy, summary validation, CloudBackground memoization, quick setup background, Sentry instrumentation
    0.4.32025-12-03Clarified test coverage (11 pass/11 skip), added cron docs, verification checklist
    0.4.22025-12-03Orphan cleanup cron with Sentry monitoring, partial signup recovery
    0.4.12025-12-03Cartesia voice onboarding, elegant cloud background UI
    0.4.02025-12-03Complete signup-onboarding overhaul (error recovery, session handling)
    0.3.92025-12-03Added periodic API availability check with auto-recovery
    0.3.82025-12-02Added in-browser voice mode (Cartesia WebSocket)
    0.3.72025-12-02Added input validation to quick setup
    0.3.62025-12-02Wired streaming API, availability hook, resume persistence
    0.3.52025-12-02Added inline editing for summary cards
    0.3.42025-12-01Added call duration display, call status polling
    0.3.32025-11-30Added summary screen, smart fallback responses
    0.3.22025-11-28Added welcome animation personalization
    0.3.12025-11-27Initial voice modes implementation
    0.3.02025-11-25Major architecture overhaul
    On this page
    Verification1. Problem / Job-to-Be-DoneThe ProblemWhy It MattersJob-to-Be-Done2. Solution OverviewSummaryOutcomeKey User FlowsKey Flow Notes3. ScopeWhat's Included (v0.4.0)What's Explicitly Out of Scope4. Acceptance Criteria (Gherkin)Voice Call ModeBrowser Voice ModeText Chat ModeGraceful DegradationEmergency SkipSession Recovery5. Dependencies & RisksDependenciesRisks & MitigationsTrade-offs Made6. Technical ApproachArchitectureKey ComponentsImplementation NotesSecurity Considerations7. Testing StrategyUnit TestsIntegration Tests