Skip to content

Fix autumn implementation and posthog errors#61

Merged
Jackson57279 merged 2 commits intomainfrom
cursor/fix-autumn-implementation-and-posthog-errors-07b4
Aug 13, 2025
Merged

Fix autumn implementation and posthog errors#61
Jackson57279 merged 2 commits intomainfrom
cursor/fix-autumn-implementation-and-posthog-errors-07b4

Conversation

@Jackson57279
Copy link
Owner

@Jackson57279 Jackson57279 commented Aug 13, 2025

Remove the lingering Autumn.js implementation and correctly configure PostHog to resolve console errors and improve analytics robustness.


Open in Cursor Open in Web

Summary by CodeRabbit

  • New Features

    • Messaging is no longer gated; you can send messages without interruptions or checkout prompts.
  • Bug Fixes

    • Analytics calls are now safely handled to avoid errors (e.g., with ad blockers), preventing disruptions.
  • Chores

    • Removed deprecated billing environment variables from the template.
    • Integrated analytics provider at the app root with environment-based configuration and safer error handling.

Co-authored-by: dogesman098 <dogesman098@gmail.com>
@cursor
Copy link

cursor bot commented Aug 13, 2025

Cursor Agent can help with this pull request. Just @cursor in comments and I'll start working on changes in this branch.
Learn more about Cursor Agents

@vercel
Copy link

vercel bot commented Aug 13, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Project Deployment Preview Comments Updated (UTC)
zapdev Ready Preview Comment Aug 13, 2025 3:34am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 13, 2025

Walkthrough

Removed Autumn billing env vars and related client-side checks, updated a pricing comment, hardened PostHog event capture with try/catch, and integrated PostHogProvider at app root. ChatInterface no longer gates message sending behind a feature flag; flow proceeds directly. No public API signatures changed.

Changes

Cohort / File(s) Summary of changes
Billing/Autumn removal
env-template.txt, src/components/pricing/CustomPricingTable.tsx
Removed AUTUMN env vars and added a comment noting removed billing configs; shortened a comment in pricing table. No runtime logic changes.
Messaging flow (feature gating removed)
src/components/ChatInterface.tsx
Deleted feature flag check, TTL cache, and checkout redirect on disallow. handleSubmit now always sends the message and proceeds with AI/streaming flow.
Analytics/PostHog integration
src/main.tsx, src/hooks/useUsageTracking.ts
Wrapped app with PostHogProvider configured via env; added dev logging and XHR error handler. Guarded posthog.capture with try/catch and existence check to avoid exceptions (e.g., ad blockers).

Sequence Diagram(s)

sequenceDiagram
  participant Browser
  participant PostHogProvider
  participant ClerkProvider
  participant ConvexProvider
  participant App
  participant PostHog

  Browser->>PostHogProvider: Load app (apiKey, options)
  PostHogProvider-->>Browser: Initialize analytics
  PostHogProvider->>ClerkProvider: Render children
  ClerkProvider->>ConvexProvider: Provide auth
  ConvexProvider->>App: Render App

  App->>PostHog: posthog.capture(event)
  Note over App,PostHog: useUsageTracking wraps capture in try/catch
  PostHog-->>App: Success or throws
  App-->>Browser: On error, warn (no crash)
Loading
sequenceDiagram
  autonumber
  participant User
  participant ChatUI as ChatInterface
  participant Backend as AI/Stream
  Note over ChatUI: Old flow (removed)
  User->>ChatUI: Submit message
  ChatUI->>ChatUI: Check feature flag + TTL cache
  alt Not allowed
    ChatUI->>User: Toast + redirect to checkout
    ChatUI--xBackend: Do not send
  else Allowed
    ChatUI->>Backend: Send message
    Backend-->>ChatUI: Stream response
  end

  Note over ChatUI: New flow
  User->>ChatUI: Submit message
  ChatUI->>Backend: Send message (no gating)
  Backend-->>ChatUI: Stream response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

I thump with delight at tidy logs,
Autumn leaves raked from env bogs.
PostHog sniffs, but if it sneezes—fine!
Our chat now hops a cleaner line.
Two ears up high, I ship and grin,
Less gate, more chat—let streams begin! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cursor/fix-autumn-implementation-and-posthog-errors-07b4

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@claude
Copy link

claude bot commented Aug 13, 2025

Claude finished @otdoges's task —— View job


Pull Request Review

Reviewing PR #61: "Fix autumn implementation and posthog errors"

Todo List:

  • Read and analyze all changed files
  • Review Autumn.js removal completeness
  • Evaluate PostHog configuration changes
  • Check for security and performance issues
  • Assess test coverage implications
  • Provide comprehensive feedback

Code Review Analysis

I've thoroughly analyzed all the changed files in this PR. Here's my comprehensive review:

Positive Changes

  1. Autumn.js Removal - Properly cleaned up from environment template
  2. PostHog Configuration - Improved error handling with graceful degradation for ad blockers
  3. Security Improvements - Good error handling in usage tracking hook

⚠️ Issues Found

Critical Issue: Missing Function Reference

File: src/components/ChatInterface.tsx:502 and src/components/ChatInterface.tsx:633

The code calls refetchCustomer() function that doesn't exist:

await refetchCustomer(); // Line 502 and 633

This will cause runtime errors. This function was likely part of the removed Autumn billing system but wasn't properly cleaned up.

Recommendation: Remove these calls or replace with proper Convex data refetching if needed.

🔍 Other Issues

PostHog Error Handling (src/main.tsx:66-69)

on_xhr_error: (failedRequest: any) => {
  console.warn('PostHog request blocked (likely by ad blocker)', failedRequest);
}
  • Good approach for handling blocked requests
  • Consider limiting console output in production

Usage Tracking TODO Comments (src/hooks/useUsageTracking.ts:62-66)

// TODO: Send to Convex database via TRPC
// await trpc.polar.recordUsage.mutate({
//   eventName: event.eventName,
//   metadata: event.metadata,
// });
  • Multiple TODOs referencing "polar" (old billing system)
  • These should be updated or removed entirely

Environment Template (env-template.txt)

  • Properly removed Autumn/Polar configurations
  • Clean and well-organized

🏗️ Architecture & Performance

  1. PostHog Integration: Well-implemented with proper error boundaries
  2. Usage Tracking: Good localStorage backup strategy for offline support
  3. Code Structure: Clean separation of concerns maintained

🔒 Security Assessment

  1. Input Sanitization: Proper XSS protection in ChatInterface
  2. Authentication: Proper auth checks in pricing component
  3. Error Handling: Good Sentry integration for error tracking

📊 Test Coverage

The changes appear to be configuration and cleanup-focused. Consider adding tests for:

  • PostHog error handling scenarios
  • Usage tracking functionality
  • Missing function error cases

Required Fixes Before Merge

  1. Fix Critical Issue: Remove refetchCustomer() calls or implement proper replacement
  2. Clean up TODO comments: Update or remove references to old billing system
  3. Consider production logging: Reduce console output for PostHog errors in production

Recommendations

  1. Run the application to ensure no runtime errors after Autumn removal
  2. Test PostHog tracking with ad blockers to verify graceful degradation
  3. Update any remaining references to old billing systems

Overall, this is a solid cleanup PR that properly removes the Autumn implementation and improves PostHog error handling, but needs the critical missing function issue resolved before merging.


@Jackson57279 Jackson57279 marked this pull request as ready for review August 13, 2025 03:33
@Jackson57279
Copy link
Owner Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 13, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
@claude
Copy link

claude bot commented Aug 13, 2025

Claude finished @otdoges's task —— View job


Pull Request Review

Reviewing PR #61: "Fix autumn implementation and posthog errors"

Todo List:

  • Read and analyze all changed files
  • Review Autumn.js removal completeness
  • Evaluate PostHog configuration changes
  • Check for security and performance issues
  • Address code scanning alerts about 'any' types
  • Assess test coverage implications
  • Provide comprehensive feedback

Summary

This PR successfully removes the Autumn.js billing implementation and improves PostHog configuration. The changes are well-structured and address the stated goals effectively.

Detailed Review

Autumn.js Removal - Complete and Clean

The PR successfully removes Autumn.js references:

  • env-template.txt:39 - Properly documented removal with clear comment
  • Code cleanup - No remaining Autumn.js imports or function calls found
  • Partial references - Only safe commented-out TODO references in useUsageTracking.ts:63-66 remain, which is appropriate for future implementation

PostHog Configuration - Well Improved

Excellent PostHog error handling improvements in src/main.tsx:59-71:

  • Graceful fallback - Proper api_host fallback to default PostHog endpoint
  • Ad-blocker resilience - Added on_xhr_error handler for blocked requests
  • Development optimization - Disabled session recording in dev mode
  • Error boundaries - Wrapped in try-catch with Sentry integration

⚠️ Code Scanning Alert - Type Safety Issue

Critical: The code scanning alert about any types in src/main.tsx appears to be from previous code. However, I found one any usage that should be addressed:

src/components/pricing/CustomPricingTable.tsx:220

let errorData: any = null;

Recommendation: Replace with proper typing:

let errorData: { message?: string; [key: string]: unknown } | null = null;

Security & Performance Assessment

Security Strengths:

  • Proper error handling prevents information leakage
  • PostHog configuration includes security considerations
  • Authentication checks remain intact

Performance Improvements:

  • PostHog optimizations reduce overhead
  • Better error handling prevents unnecessary retries

Test Coverage Analysis

The existing test suite (src/lib/__tests__/ai-production.test.ts) provides good coverage for:

  • AI functionality and error handling
  • Cost tracking and monitoring
  • Circuit breaker patterns
  • API key validation

Test Impact: The PostHog changes don't break existing functionality and maintain backward compatibility.

Recommendations

High Priority

  1. Fix any type usage in CustomPricingTable.tsx:220 - Replace with proper interface
  2. Verify PostHog keys are properly configured in production environment

Medium Priority

  1. Add PostHog tests - Consider adding tests for PostHog error handling scenarios
  2. Monitor ad-blocker impact - Track how many users are affected by PostHog blocking

Low Priority

  1. Documentation update - Consider updating setup docs to reflect Autumn.js removal
  2. Environment cleanup - Remove any Autumn.js related environment variables from deployment configs

Overall Assessment

Rating: ✅ Approved with Minor Suggestions

This is a solid PR that successfully accomplishes its goals. The Autumn.js removal is clean and complete, and the PostHog improvements add robustness. The only significant issue is the remaining any type usage which should be addressed for type safety.

The changes maintain system stability while improving error handling and user experience. Well done! 🎉


Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (4)
env-template.txt (1)

39-39: Clarify which variables were removed for future readers.

Spell out the exact vars removed to prevent confusion for integrators glancing at the template.

Apply this diff:

-# Removed Polar and Autumn billing configurations
+# Removed Polar and Autumn billing configurations (previously: AUTUMN_SECRET_KEY, VITE_AUTUMN_BACKEND_URL, VITE_AUTUMN_PRODUCT_PRO_ID)
src/hooks/useUsageTracking.ts (1)

58-60: Reduce noisy warnings in production.

Gate the warning behind a dev check to keep prod consoles clean.

Apply this diff:

-      } catch (posthogError) {
-        // PostHog might be blocked by ad blockers - fail silently
-        console.warn('PostHog tracking failed (likely blocked by ad blocker):', posthogError);
-      }
+      } catch (posthogError) {
+        // PostHog might be blocked by ad blockers - fail silently
+        if (import.meta.env.DEV) {
+          console.warn('PostHog tracking failed (likely blocked by ad blocker):', posthogError);
+        }
+      }
src/main.tsx (2)

5-7: PostHog imports look correct. Consider also importing the config type.

Typing your options object helps catch typos in option names.

Apply this diff:

-import { PostHogProvider } from 'posthog-js/react'
+import { PostHogProvider } from 'posthog-js/react'
 import * as Sentry from '@sentry/react'
-import type { PostHog } from 'posthog-js';
+import type { PostHog, PostHogConfig } from 'posthog-js';

59-71: Type the PostHog options for stricter safety and typo detection.

Prevents silent misconfigurations (aligns with the project’s strict TS stance).

Apply this diff:

-// Initialize PostHog with proper error handling
-const posthogOptions = {
+// Initialize PostHog with proper error handling
+const posthogOptions: Partial<PostHogConfig> = {
   api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST || 'https://app.posthog.com',
   capture_pageview: false, // Disable automatic pageview capture for better control
   disable_session_recording: import.meta.env.MODE === 'development',
   loaded: (posthog: PostHog) => {
     if (import.meta.env.MODE === 'development') console.log('PostHog loaded');
   },
   on_xhr_error: (failedRequest: unknown) => {
     // Gracefully handle blocked requests (ad blockers, etc.)
     console.warn('PostHog request blocked (likely by ad blocker)', failedRequest);
   }
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2cf4d54 and 33aecc8.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • env-template.txt (1 hunks)
  • src/components/ChatInterface.tsx (0 hunks)
  • src/components/pricing/CustomPricingTable.tsx (1 hunks)
  • src/hooks/useUsageTracking.ts (1 hunks)
  • src/main.tsx (2 hunks)
💤 Files with no reviewable changes (1)
  • src/components/ChatInterface.tsx
🧰 Additional context used
🧠 Learnings (4)
📚 Learning: 2025-08-09T23:03:40.158Z
Learnt from: CR
PR: otdoges/zapdev#0
File: .cursor/rules/typescript-standards.mdc:0-0
Timestamp: 2025-08-09T23:03:40.158Z
Learning: Applies to **/*.{ts,tsx} : NEVER use `any` type - use proper TypeScript types

Applied to files:

  • src/main.tsx
📚 Learning: 2025-08-12T03:04:41.034Z
Learnt from: CR
PR: otdoges/zapdev#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-12T03:04:41.034Z
Learning: Applies to **/*.{ts,tsx} : Avoid using `any` and maintain strict type safety in TypeScript code

Applied to files:

  • src/main.tsx
📚 Learning: 2025-08-09T23:03:33.406Z
Learnt from: CR
PR: otdoges/zapdev#0
File: .cursor/rules/project-overview.mdc:0-0
Timestamp: 2025-08-09T23:03:33.406Z
Learning: Applies to **/*.{ts,tsx} : Strict TypeScript must be used with no 'any' types allowed

Applied to files:

  • src/main.tsx
📚 Learning: 2025-08-09T23:02:50.239Z
Learnt from: CR
PR: otdoges/zapdev#0
File: .cursor/rules/authentication-patterns.mdc:0-0
Timestamp: 2025-08-09T23:02:50.239Z
Learning: Applies to **/useAuth.@(ts|tsx) : Use the provided `useAuth` hook pattern for integrating Clerk and Convex authentication, including syncing Clerk user data to Convex and returning the correct authentication state.

Applied to files:

  • src/main.tsx
🧬 Code Graph Analysis (1)
src/main.tsx (2)
src/lib/convex.ts (1)
  • convex (9-9)
src/hooks/useAuth.ts (1)
  • useAuth (16-46)
🔇 Additional comments (2)
env-template.txt (1)

39-39: No remaining references to removed environment variables found.

I ran the provided ripgrep scan against AUTUMN_SECRET_KEY, VITE_AUTUMN_BACKEND_URL, and VITE_AUTUMN_PRODUCT_PRO_ID and found zero matches in the codebase. Runtime code no longer depends on these vars.

src/hooks/useUsageTracking.ts (1)

48-60: Hardened PostHog capture with guarded try/catch—LGTM.

This prevents analytics failures (e.g., ad blockers) from bubbling up and breaking UX. Good safety net around a non-critical path.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants