Skip to content

feat(analytics): Adds analytics dashboard #358

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 20, 2025
Merged

Conversation

msukkari
Copy link
Contributor

@msukkari msukkari commented Jun 19, 2025

analytics_demo.mp4
  • Removes API based query audit events in favor of UI based audit events. More accurate and less spammy
  • Enables audit logging by default

Summary by CodeRabbit

  • New Features

    • Introduced an analytics dashboard with interactive charts and a cost savings calculator for enterprise users.
    • Added a new "Analytics" section to the settings navigation and documentation.
    • Implemented entitlement checks to control access to analytics features.
  • Enhancements

    • Improved audit logging for user actions such as code search and code navigation.
    • Added new database indexes to optimize analytics queries.
  • Bug Fixes

    • Updated audit log action names for clarity and consistency.
  • Documentation

    • Added and updated documentation for analytics features, audit log actions, and environment variable defaults.
  • Chores

    • Added scripts and tools for generating and testing analytics data.
    • Updated dependencies and internal configuration for analytics support.

@msukkari msukkari requested a review from brendan-kellam June 19, 2025 23:54
Copy link

coderabbitai bot commented Jun 19, 2025

Walkthrough

This update introduces an analytics dashboard feature, including backend data aggregation, frontend visualization, and supporting documentation. It adds audit logging for key user actions, updates audit event naming, enables audit logging by default, and provides tools for generating test audit data. Several new UI components and entitlements are also introduced.

Changes

File(s) Change Summary
CHANGELOG.md Added entry for analytics dashboard feature under "Unreleased".
docs/docs.json, docs/docs/features/analytics.mdx Added Analytics documentation page and updated navigation.
docs/docs/configuration/audit-logs.mdx Renamed audit actions, updated audit action types table in documentation.
docs/docs/configuration/environment-variables.mdx, packages/web/src/env.mjs Changed default for SOURCEBOT_EE_AUDIT_LOGGING_ENABLED from false to true in docs and config.
packages/db/prisma/migrations/.../migration.sql, packages/db/prisma/schema.prisma Added new indexes to Audit table/model for optimized analytics queries.
packages/db/tools/scriptRunner.ts, packages/db/tools/scripts/inject-audit-data.ts Added script to inject realistic audit data for analytics testing.
packages/shared/src/entitlements.ts Added "analytics" entitlement to relevant plans.
packages/web/package.json Added "date-fns", "recharts" dependencies; upgraded "lucide-react".
packages/web/src/app/[domain]/browse/[...]/pureCodePreviewPanel.tsx Added audit logging for code navigation actions.
packages/web/src/app/[domain]/components/searchBar/searchBar.tsx Added audit logging for code search submissions.
packages/web/src/app/[domain]/settings/analytics/page.tsx New analytics dashboard page with entitlement check.
packages/web/src/app/[domain]/settings/layout.tsx Added "Analytics" to sidebar navigation.
packages/web/src/auth.ts Simplified signIn event handler parameter list.
packages/web/src/components/ui/chart.tsx New chart UI component module for analytics dashboard (with theming, tooltips, legends).
packages/web/src/ee/features/analytics/actions.ts New server-side analytics data aggregation function with authorization.
packages/web/src/ee/features/analytics/analyticsContent.tsx New analytics dashboard UI: charts, savings calculator, interactive inputs.
packages/web/src/ee/features/analytics/analyticsEntitlementMessage.tsx New UI component for users lacking analytics entitlement.
packages/web/src/ee/features/analytics/types.ts New TypeScript schema/types for analytics data.
packages/web/src/ee/features/audit/actions.ts Added createAuditAction for secure audit event creation.
packages/web/src/features/search/fileSourceApi.ts, .../listReposApi.ts, .../searchApi.ts Removed audit logging from file source, repo listing, and search APIs.
packages/web/src/app/[domain]/search/components/codePreviewPanel/codePreview.tsx Added audit logging for code navigation actions.
packages/web/src/ee/features/audit/factory.ts Added entitlement check to audit service initialization.
packages/web/src/initialize.ts Removed entitlement validation function for audit logging.
packages/web/src/lib/newsData.ts Added news item for analytics dashboard feature.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant WebApp
    participant AuditClient
    participant Backend
    participant DB

    User->>WebApp: Performs code search/navigation
    WebApp->>AuditClient: createAuditClient(action, metadata, domain)
    AuditClient->>Backend: Auth & org check, create audit event
    Backend->>DB: Insert audit record
    WebApp->>Backend: Request analytics data (if on dashboard)
    Backend->>DB: Aggregate audit logs by period/bucket
    DB-->>Backend: Aggregated analytics data
    Backend-->>WebApp: Analytics data
    WebApp-->>User: Render analytics dashboard/charts
Loading

Possibly related PRs

Poem

In the warren where data hops and leaps,
A dashboard blooms where insight sleeps.
With charts and logs, the numbers dance,
Rabbits track each user’s glance.
Entitlements checked, savings in view—
Analytics now, for me and you!
🐇📊✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

@msukkari msukkari changed the title Adds analytics dashboard feat(analytics): Adds analytics dashboard Jun 19, 2025
Copy link

@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: 5

🧹 Nitpick comments (9)
packages/web/src/components/ui/chart.tsx (1)

70-101: Consider sanitizing color values before CSS injection.

While the risk is minimal since you're only injecting CSS custom properties from configuration, it's good practice to validate color values before using dangerouslySetInnerHTML. This prevents potential CSS injection if the configuration is ever sourced from user input.

Consider adding color validation:

 const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
   const colorConfig = Object.entries(config).filter(
     ([, config]) => config.theme || config.color
   )
 
   if (!colorConfig.length) {
     return null
   }
 
+  // Validate color values to prevent CSS injection
+  const isValidColor = (color: string) => {
+    // Allow hex colors, rgb/rgba, hsl/hsla, and CSS color names
+    const colorRegex = /^(#[0-9A-Fa-f]{3,8}|rgb\(|rgba\(|hsl\(|hsla\(|[a-zA-Z]+)[\s\S]*$/;
+    return colorRegex.test(color);
+  };
+
   return (
     <style
       dangerouslySetInnerHTML={{
         __html: Object.entries(THEMES)
           .map(
             ([theme, prefix]) => `
 ${prefix} [data-chart=${id}] {
 ${colorConfig
   .map(([key, itemConfig]) => {
     const color =
       itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
       itemConfig.color
-    return color ? `  --color-${key}: ${color};` : null
+    return color && isValidColor(color) ? `  --color-${key}: ${color};` : null
   })
   .join("\n")}
 }
 `
           )
           .join("\n"),
       }}
     />
   )
 }
packages/web/src/app/[domain]/components/searchBar/searchBar.tsx (1)

208-214: Consider error handling for audit logging.

The audit logging implementation looks correct with proper action naming and metadata. However, consider whether audit logging failures should be handled gracefully to avoid impacting the search experience.

Since createAuditClient appears to be a fire-and-forget operation, consider wrapping it in a try-catch to prevent any potential errors from affecting the search submission:

+        try {
             createAuditClient({
                 action: "user.performed_code_search",
                 metadata: {
                     message: query,
                 },
             }, domain)
+        } catch (error) {
+            // Log error but don't block search functionality
+            console.error('Failed to create audit log:', error);
+        }
packages/web/src/app/[domain]/settings/analytics/page.tsx (1)

11-19: Consider loading state for entitlement check.

The entitlement-based conditional rendering is well implemented. However, consider handling the loading state while the entitlement check is in progress to improve user experience.

Consider adding a loading state:

 function AnalyticsPageContent() {
-  const hasAnalyticsEntitlement = useHasEntitlement("analytics");
+  const { hasEntitlement: hasAnalyticsEntitlement, isLoading } = useHasEntitlement("analytics");

+  if (isLoading) {
+    return <div>Loading...</div>; // Or your preferred loading component
+  }
+
   if (!hasAnalyticsEntitlement) {
     return <AnalyticsEntitlementMessage />;
   }

   return <AnalyticsContent />;
 }

Note: This assumes the useHasEntitlement hook supports a loading state. If it doesn't, you may need to check its implementation or handle loading differently.

docs/docs/features/analytics.mdx (1)

17-17: Consider more concise wording.

As suggested by the style checker, consider replacing "in order to" with "to" for more concise writing.

-This dashboard is backed by [audit log](/docs/configuration/audit-logs) events. Please ensure you have audit logging enabled in order to see these insights.
+This dashboard is backed by [audit log](/docs/configuration/audit-logs) events. Please ensure you have audit logging enabled to see these insights.
packages/db/tools/scripts/inject-audit-data.ts (1)

30-34: Consider validating action names against a source of truth.

The hardcoded action names could become out of sync with the actual system if action names change elsewhere in the codebase.

Consider importing action constants from a shared location or adding validation:

+import { AUDIT_ACTIONS } from '../../../shared/auditActions'; // if such constants exist
+
-        const actions = [
-            'user.performed_code_search',
-            'user.performed_find_references', 
-            'user.performed_goto_definition'
-        ];
+        const actions = [
+            AUDIT_ACTIONS.CODE_SEARCH,
+            AUDIT_ACTIONS.FIND_REFERENCES,
+            AUDIT_ACTIONS.GOTO_DEFINITION
+        ];
packages/web/src/ee/features/analytics/actions.ts (1)

23-98: Consider query performance optimization.

This complex query with multiple CTEs and generate_series calls could be expensive for large datasets or wide date ranges.

Consider these optimizations:

  1. Add query timeout handling
  2. Consider pagination for very large date ranges
  3. Add database indexes on timestamp and orgId columns (if not already present)
  4. Consider caching results for frequently accessed data
+      // Consider adding query optimization
+      const queryTimeout = 30000; // 30 seconds
+      
       const rows = await prisma.$queryRaw<AnalyticsResponse>`
+      SET statement_timeout = ${queryTimeout};
       WITH core AS (
packages/web/src/ee/features/analytics/analyticsContent.tsx (3)

171-182: Consider extracting savings calculation logic to a utility function.

The savings calculation logic here is duplicated in the main component (lines 369-374). Consider extracting this to a shared utility function to maintain DRY principles.

Create a utility function:

export function calculateSavings(
  totalOperations: number,
  avgMinutesSaved: number,
  avgSalary: number
): number {
  const totalMinutesSaved = totalOperations * avgMinutesSaved
  const hourlyRate = avgSalary / (40 * 52) // 40 hours/week, 52 weeks/year
  const hourlySavings = (totalMinutesSaved / 60) * hourlyRate
  return Math.round(hourlySavings * 100) / 100
}

309-309: Use Array.from for cleaner array generation.

Replace the hardcoded array with a more idiomatic approach:

-{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((i) => (
+{Array.from({ length: 10 }, (_, i) => i + 1).map((i) => (

369-374: Good implementation, but consider reusing the savings calculation utility.

As mentioned earlier, this calculation logic duplicates what's in the SavingsChart component. Once you extract the utility function, use it here as well.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 10f9f6b and 7364268.

⛔ Files ignored due to path filters (6)
  • docs/images/analytics_demo.mp4 is excluded by !**/*.mp4
  • docs/images/code_nav_chart.png is excluded by !**/*.png
  • docs/images/code_search_chart.png is excluded by !**/*.png
  • docs/images/cost_savings_chart.png is excluded by !**/*.png
  • docs/images/dau_chart.png is excluded by !**/*.png
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (26)
  • CHANGELOG.md (1 hunks)
  • docs/docs.json (1 hunks)
  • docs/docs/configuration/audit-logs.mdx (4 hunks)
  • docs/docs/configuration/environment-variables.mdx (1 hunks)
  • docs/docs/features/analytics.mdx (1 hunks)
  • packages/db/prisma/migrations/20250619231843_add_audit_indexes/migration.sql (1 hunks)
  • packages/db/prisma/schema.prisma (1 hunks)
  • packages/db/tools/scriptRunner.ts (2 hunks)
  • packages/db/tools/scripts/inject-audit-data.ts (1 hunks)
  • packages/shared/src/entitlements.ts (1 hunks)
  • packages/web/package.json (3 hunks)
  • packages/web/src/app/[domain]/browse/[...path]/components/pureCodePreviewPanel.tsx (5 hunks)
  • packages/web/src/app/[domain]/components/searchBar/searchBar.tsx (2 hunks)
  • packages/web/src/app/[domain]/settings/analytics/page.tsx (1 hunks)
  • packages/web/src/app/[domain]/settings/layout.tsx (1 hunks)
  • packages/web/src/auth.ts (1 hunks)
  • packages/web/src/components/ui/chart.tsx (1 hunks)
  • packages/web/src/ee/features/analytics/actions.ts (1 hunks)
  • packages/web/src/ee/features/analytics/analyticsContent.tsx (1 hunks)
  • packages/web/src/ee/features/analytics/analyticsEntitlementMessage.tsx (1 hunks)
  • packages/web/src/ee/features/analytics/types.ts (1 hunks)
  • packages/web/src/ee/features/audit/actions.ts (2 hunks)
  • packages/web/src/env.mjs (1 hunks)
  • packages/web/src/features/search/fileSourceApi.ts (1 hunks)
  • packages/web/src/features/search/listReposApi.ts (1 hunks)
  • packages/web/src/features/search/searchApi.ts (1 hunks)
🧰 Additional context used
🪛 LanguageTool
CHANGELOG.md

[duplication] ~10-~10: Possible typo: you repeated a word.
Context: ...pec/v2.0.0.html). ## [Unreleased] ### Added - Added analytics dashboard. [#358](https://git...

(ENGLISH_WORD_REPEAT_RULE)

docs/docs/features/analytics.mdx

[style] ~17-~17: Consider a more concise word here.
Context: ...e ensure you have audit logging enabled in order to see these insights. <video autoPlay ...

(IN_ORDER_TO_PREMIUM)

🪛 Biome (1.9.4)
packages/web/src/components/ui/chart.tsx

[error] 81-81: Avoid passing content using the dangerouslySetInnerHTML prop.

Setting content using code can expose users to cross-site scripting (XSS) attacks

(lint/security/noDangerouslySetInnerHtml)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (29)
packages/web/package.json (1)

114-114: LGTM! Appropriate dependencies for the analytics dashboard.

The added dependencies (date-fns and recharts) and the updated lucide-react version are suitable choices for implementing the analytics feature. These are well-maintained libraries with good community support.

Also applies to: 123-123, 142-142

packages/web/src/features/search/listReposApi.ts (1)

8-10: Audit logging correctly removed from API layer.

The removal of audit service imports and logging calls aligns with the PR objective of replacing API-based query audit events with UI-based audit events. The core functionality remains intact.

packages/web/src/components/ui/chart.tsx (1)

1-366: Well-structured chart component with excellent theming support!

This is a comprehensive chart wrapper that provides:

  • Theme-aware styling with CSS custom properties
  • Custom tooltip and legend components with flexible configuration
  • Proper TypeScript typing throughout
  • Clean separation of concerns

The implementation follows React best practices and provides a good abstraction over Recharts.

CHANGELOG.md (1)

10-12: Changelog entry properly documents the new feature.

The analytics dashboard addition is correctly documented in the "Unreleased" section following the Keep a Changelog format.

packages/web/src/app/[domain]/settings/layout.tsx (1)

88-91: Consider adding entitlement gating for the Analytics navigation item.

The Analytics feature appears to require entitlement checks based on the PR summary mentioning "entitlement gating". Should this navigation item be conditionally rendered based on the user's analytics entitlement?

#!/bin/bash
# Description: Check if analytics entitlement is being used elsewhere in the codebase

# Search for analytics entitlement usage
rg -A 3 "analytics.*entitlement|entitlement.*analytics" --type ts --type tsx

# Search for the analytics page implementation to see if it has entitlement checks
fd -e tsx -e ts "analytics" --exec grep -l "entitlement" {} \;

# Check the specific analytics page file
cat packages/web/src/app/[domain]/settings/analytics/page.tsx 2>/dev/null || echo "Analytics page file not found"
docs/docs.json (1)

39-39: LGTM! Analytics documentation properly integrated.

The analytics documentation page is correctly added to the Features navigation section, maintaining consistency with the existing structure.

docs/docs/configuration/environment-variables.mdx (1)

42-42: ```shell
#!/bin/bash

List all occurrences of the environment variable across the repository

rg -n "SOURCEBOT_EE_AUDIT_LOGGING_ENABLED"

Check for default assignments in JSON, YAML, TS, or JS config/schema files

rg -n '"SOURCEBOT_EE_AUDIT_LOGGING_ENABLED".*default' -t json -t yaml -t ts -t js

Check for any hardcoded assignments in .env or shell scripts

rg -n '^SOURCEBOT_EE_AUDIT_LOGGING_ENABLED='


</details>
<details>
<summary>packages/db/prisma/migrations/20250619231843_add_audit_indexes/migration.sql (1)</summary>

`1-5`: **LGTM! Well-designed indexes for analytics queries.**

The composite indexes are properly structured for analytics use cases:
- `idx_audit_core_actions_full` supports efficient org-scoped queries with time filtering
- `idx_audit_actor_time_full` enables user-specific time-series analytics

Column ordering follows best practices with high-cardinality fields first.

</details>
<details>
<summary>packages/db/tools/scriptRunner.ts (2)</summary>

`4-4`: **Clean script integration following established patterns.**

The audit data injection script is properly imported and follows the existing code structure.

---

`14-14`: **Script registration completed correctly.**

The inject-audit-data script is properly registered in the scripts registry, maintaining consistency with existing script entries.

</details>
<details>
<summary>packages/shared/src/entitlements.ts (2)</summary>

`41-41`: **Analytics entitlement properly added to the system.**

The new analytics entitlement is correctly added to the entitlements array, following the established pattern.

---

`48-49`: **Enterprise plans correctly configured with analytics access.**

Both self-hosted enterprise plans (regular and unlimited) properly include the analytics entitlement, maintaining the enterprise feature distinction while excluding cloud and OSS plans appropriately.

</details>
<details>
<summary>packages/web/src/features/search/searchApi.ts (1)</summary>

`129-129`: **Good practice: Unused parameter naming.**

Renaming `apiKeyHash` to `_apiKeyHash` clearly indicates the parameter is unused after removing audit logging from the API level. This follows the convention of prefixing unused parameters with an underscore.

</details>
<details>
<summary>packages/web/src/app/[domain]/components/searchBar/searchBar.tsx (1)</summary>

`46-46`: **LGTM: Proper import of audit client.**

The import statement correctly brings in the `createAuditClient` function for audit logging.

</details>
<details>
<summary>packages/web/src/app/[domain]/settings/analytics/page.tsx (1)</summary>

`7-9`: **Good component structure.**

The default export pattern is clean and follows React conventions.

</details>
<details>
<summary>packages/web/src/auth.ts (1)</summary>

`144-159`: **LGTM: Parameter cleanup in signIn handler.**

Removing the unused `account` parameter simplifies the function signature while maintaining the audit logging functionality. The audit logging implementation correctly handles user authentication events.

Note: The TODO comment on line 152 suggests the organization ID handling may need attention for multi-tenant scenarios.

</details>
<details>
<summary>packages/web/src/features/search/fileSourceApi.ts (1)</summary>

`15-16`: **LGTM - Clean removal of audit logging from API route.**

The changes correctly remove audit logging dependencies from the file source API. The underscore prefix on `_apiKeyHash` properly indicates an unused parameter, and removing the `org` parameter is consistent with no longer needing it for audit logging.

</details>
<details>
<summary>packages/db/prisma/schema.prisma (1)</summary>

`249-253`: **Well-designed indexes for analytics performance.**

The new audit indexes are properly structured for analytics queries:
- `idx_audit_core_actions_full` efficiently supports org-scoped time-series analytics
- `idx_audit_actor_time_full` enables fast user-specific activity queries

The descriptive comments and clear naming convention make the intent obvious.

</details>
<details>
<summary>docs/docs/configuration/audit-logs.mdx (2)</summary>

`43-43`: **Documentation accurately reflects the new audit action naming.**

The updated action names from `"query.code_search"` to `"user.performed_code_search"` properly reflect the shift to UI-based audit logging and provide clearer semantic meaning.



Also applies to: 57-57, 71-71

---

`119-121`: **Audit action types table correctly updated.**

The new entries for `user.performed_code_search`, `user.performed_find_references`, and `user.performed_goto_definition` with consistent actor/target types properly document the new audit actions.

</details>
<details>
<summary>packages/web/src/ee/features/analytics/analyticsEntitlementMessage.tsx (1)</summary>

`1-47`: **Well-implemented enterprise feature gating component.**

The component follows React and accessibility best practices:
- Proper use of semantic HTML and design system components
- External link includes security attributes (`rel="noopener"`)
- Clear, user-friendly messaging about enterprise features
- Responsive design with appropriate styling

The implementation effectively guides users toward requesting trial access.

</details>
<details>
<summary>packages/web/src/app/[domain]/browse/[...path]/components/pureCodePreviewPanel.tsx (3)</summary>

`20-21`: **Proper imports and setup for UI-based audit logging.**

The imports and domain hook usage are correctly implemented to support the new audit logging approach.



Also applies to: 45-45

---

`140-145`: **Audit logging correctly implemented for find references action.**

The audit event creation follows the proper pattern:
- Uses the new `user.performed_find_references` action name
- Includes meaningful metadata with the symbol name
- Properly scoped to the current domain
- Dependency array correctly updated to include domain



Also applies to: 157-157

---

`164-169`: **Audit logging correctly implemented for goto definition action.**

The audit event creation is consistent with the find references implementation:
- Uses the proper `user.performed_goto_definition` action name  
- Includes symbol name in metadata for traceability
- Properly integrated with domain context
- Dependency array correctly maintains domain reference



Also applies to: 198-198

</details>
<details>
<summary>packages/web/src/ee/features/analytics/types.ts (1)</summary>

`1-10`: **Well-structured schema definition.**

The Zod schema effectively validates analytics response data with appropriate types for time-based analytics. The period enum, date bucket, and numeric metrics are correctly defined.

</details>
<details>
<summary>packages/web/src/ee/features/analytics/analyticsContent.tsx (4)</summary>

`1-1`: **LGTM!**

Correct use of the "use client" directive for this interactive dashboard component.

---

`29-153`: **Well-implemented chart component with proper theming and formatting.**

The AnalyticsChart component demonstrates good practices:
- Proper UTC to local date conversion for display
- Clean value formatting with K/M abbreviations
- Comprehensive tooltip implementation
- Good use of gradients and theming

---

`519-519`: **Safe type assertions given the data filtering context.**

The type assertions for period are safe here because the data has already been filtered by period type (day/week/month).




Also applies to: 536-536

---

`595-596`: **Good UX with comprehensive operation count display.**

Excellent user experience touch showing the total number of operations that the savings calculation is based on. The use of `toLocaleString()` for number formatting is a nice detail.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Copy link

@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: 0

♻️ Duplicate comments (2)
CHANGELOG.md (1)

16-17: Addresses previous feedback: Audit logging default change documented.

This entry correctly addresses the previous review comment about documenting that audit logs are now enabled by default.

docs/docs/configuration/audit-logs.mdx (1)

15-16: Addresses previous feedback but fix phrase repetition.

This correctly addresses the previous review comment about updating the section since audit logs are now enabled by default. However, there's a phrase repetition issue to fix.

-## Enabling/Disabling Audit Logs
-Audit logs are enabled by default and can be controlled with the `SOURCEBOT_EE_AUDIT_LOGGING_ENABLED` [environment variable](/docs/configuration/environment-variables).
+## Enabling/Disabling Audit Logs
+Audit logging is enabled by default and can be controlled with the `SOURCEBOT_EE_AUDIT_LOGGING_ENABLED` [environment variable](/docs/configuration/environment-variables).
🧹 Nitpick comments (1)
docs/docs/features/analytics.mdx (1)

17-17: Minor style improvement: Consider more concise phrasing.

Consider replacing "in order to see" with "to see" for more concise writing.

-This dashboard is backed by [audit log](/docs/configuration/audit-logs) events. Please ensure you have audit logging enabled in order to see these insights.
+This dashboard is backed by [audit log](/docs/configuration/audit-logs) events. Please ensure you have audit logging enabled to see these insights.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ac9b6b4 and 3176230.

📒 Files selected for processing (11)
  • CHANGELOG.md (1 hunks)
  • docs/docs/configuration/audit-logs.mdx (5 hunks)
  • docs/docs/features/analytics.mdx (1 hunks)
  • packages/web/src/app/[domain]/browse/[...path]/components/pureCodePreviewPanel.tsx (5 hunks)
  • packages/web/src/app/[domain]/components/searchBar/searchBar.tsx (2 hunks)
  • packages/web/src/app/[domain]/search/components/codePreviewPanel/codePreview.tsx (5 hunks)
  • packages/web/src/ee/features/analytics/analyticsContent.tsx (1 hunks)
  • packages/web/src/ee/features/analytics/analyticsEntitlementMessage.tsx (1 hunks)
  • packages/web/src/ee/features/audit/actions.ts (2 hunks)
  • packages/web/src/ee/features/audit/factory.ts (1 hunks)
  • packages/web/src/initialize.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • packages/web/src/initialize.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/web/src/ee/features/analytics/analyticsContent.tsx
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/web/src/app/[domain]/components/searchBar/searchBar.tsx
  • packages/web/src/ee/features/analytics/analyticsEntitlementMessage.tsx
  • packages/web/src/ee/features/audit/actions.ts
  • packages/web/src/app/[domain]/browse/[...path]/components/pureCodePreviewPanel.tsx
🧰 Additional context used
🪛 LanguageTool
CHANGELOG.md

[duplication] ~10-~10: Possible typo: you repeated a word.
Context: ...pec/v2.0.0.html). ## [Unreleased] ### Added - Added analytics dashboard. [#358](https://git...

(ENGLISH_WORD_REPEAT_RULE)


[duplication] ~13-~13: Possible typo: you repeated a word.
Context: ...//pull/358) ### Fixed - Fixed issue where invites appeared to be crea...

(ENGLISH_WORD_REPEAT_RULE)

docs/docs/configuration/audit-logs.mdx

[grammar] ~15-~15: This phrase is duplicated. You should probably use “Audit Logs” only once.
Context: ...ebot deployment. ## Enabling/Disabling Audit Logs Audit logs are enabled by default and can be contr...

(PHRASE_REPETITION)

docs/docs/features/analytics.mdx

[style] ~17-~17: Consider a more concise word here.
Context: ...e ensure you have audit logging enabled in order to see these insights. <video autoPlay ...

(IN_ORDER_TO_PREMIUM)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (11)
packages/web/src/app/[domain]/search/components/codePreviewPanel/codePreview.tsx (5)

24-25: LGTM: Proper audit logging imports added.

The imports for audit logging functionality are correctly added and align with the PR's objective to track user interactions for analytics.


56-56: LGTM: Domain context properly retrieved.

The useDomain hook is correctly used to get the current domain context for audit logging.


123-128: LGTM: Audit logging for goto definition action.

The audit logging implementation correctly captures the goto definition action with appropriate metadata. The action name follows the standardized "user.performed_*" convention mentioned in the documentation.


167-172: LGTM: Audit logging for find references action.

The audit logging implementation correctly captures the find references action with appropriate metadata, consistent with the goto definition implementation.


163-163: LGTM: Dependencies correctly updated.

The dependency arrays for both callbacks properly include the domain parameter to ensure the callbacks are recreated when the domain changes.

Also applies to: 190-190

packages/web/src/ee/features/audit/factory.ts (2)

4-4: LGTM: Appropriate entitlement import added.

The hasEntitlement import is correctly added to support the new entitlement-based audit logging enablement.


10-11: LGTM: Enhanced audit logging enablement logic.

The updated logic correctly combines both environment variable check and entitlement verification, following security best practices. This ensures audit logging is only enabled when both configuration is set and the organization has the appropriate entitlement.

CHANGELOG.md (1)

10-11: LGTM: Analytics dashboard feature properly documented.

The changelog entry correctly documents the addition of the analytics dashboard feature with appropriate PR reference.

docs/docs/features/analytics.mdx (1)

1-51: LGTM: Comprehensive analytics feature documentation.

The documentation provides excellent coverage of the analytics dashboard features, including clear descriptions of metrics, visual examples, and proper license key requirements. The structure and content align well with the PR's analytics dashboard implementation.

docs/docs/configuration/audit-logs.mdx (2)

43-43: LGTM: Updated audit action names in examples.

The example responses correctly use the new "user.performed_code_search" action name, consistent with the new audit action naming convention.

Also applies to: 57-57, 71-71


119-121: LGTM: Updated audit action types table.

The audit action types table correctly reflects the new "user.performed_*" action naming convention, replacing the previous generic approach with more specific user interaction tracking.

@msukkari msukkari merged commit 4bb93c9 into main Jun 20, 2025
6 checks passed
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