Skip to content
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

fix[PdfHighlight]: broken ui issues in safari #28

Merged
merged 5 commits into from
Oct 17, 2024

Conversation

ArslanSaleem
Copy link
Collaborator

@ArslanSaleem ArslanSaleem commented Oct 17, 2024

Summary by CodeRabbit

  • New Features

    • Updated ChatReferenceDrawer to conditionally determine the file_url based on the drawer's open state.
    • Enhanced HighlightPdfViewer for better compatibility with environments lacking Promise.withResolvers.
  • Improvements

    • Simplified markdown rendering in ChatBubble and MessageWithReferences by removing GitHub Flavored Markdown support.
    • Adjusted highlight dimension calculations in HighlightPdfViewer for improved accuracy based on device pixel ratio.
    • Updated Webpack configuration for better handling of worker files in the application.
  • Bug Fixes

    • Improved error logging in ChatReferenceDrawer to only log when the drawer is open.
    • Adjusted task processing logic to account for failed steps in the queue system.

@ArslanSaleem ArslanSaleem requested a review from gventuri October 17, 2024 14:07
Copy link
Contributor

coderabbitai bot commented Oct 17, 2024

Walkthrough

The changes in this pull request involve modifications to several components in the frontend application. The ChatReferenceDrawer component now conditionally assigns the file_url based on the isOpen state. The ChatBubble and MessageWithReferences components have removed the remarkGfm plugin from the ReactMarkdown component, simplifying markdown rendering. Additionally, the HighlightPdfViewer component includes a polyfill for Promise.withResolvers and updates the PDF worker loading mechanism. The backend processing logic has also been enhanced to account for failed tasks in the queue.

Changes

File Path Change Summary
frontend/src/components/ChatReferenceDrawer.tsx Updated logic for file_url assignment based on isOpen state; nested error logging for missing filename.
frontend/src/components/ui/ChatBubble.tsx Removed remarkGfm plugin from ReactMarkdown; retained only rehypeSanitize; conditionally rendered references prop.
frontend/src/components/ui/MessageWithReferences.tsx Removed remarkGfm plugin from ReactMarkdown in renderMessageParts; overall functionality preserved.
frontend/src/ee/components/HighlightPdfViewer.tsx Added polyfill for Promise.withResolvers; updated PDF worker loading mechanism; useEffect hook modified for compatibility.
frontend/next.config.mjs Added webpack function to modify Webpack config for .mjs files, excluding pdf.worker.min.mjs.
backend/app/processing/process_queue.py Updated process_task and process_step_task functions to handle ProcessStepStatus.FAILED in task processing logic.

Possibly related PRs

Suggested reviewers

  • gventuri

🐰 In the drawer, the logic now flows,
With file_url set when the drawer shows.
Markdown simplified, no more GitHub flair,
Just clean and clear, with nary a care.
PDFs now load with a promise so bright,
Hopping along, everything feels just right! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between dc398a7 and bd77305.

📒 Files selected for processing (2)
  • frontend/next.config.mjs (1 hunks)
  • frontend/src/ee/components/HighlightPdfViewer.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • frontend/next.config.mjs
  • frontend/src/ee/components/HighlightPdfViewer.tsx

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

@codecov-commenter
Copy link

codecov-commenter commented Oct 17, 2024

Codecov Report

Attention: Patch coverage is 0% with 1 line in your changes missing coverage. Please review.

Project coverage is 54.09%. Comparing base (b82c6e3) to head (bd77305).

Files with missing lines Patch % Lines
backend/app/processing/process_queue.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@               Coverage Diff               @@
##           release/v0.2.3      #28   +/-   ##
===============================================
  Coverage           54.09%   54.09%           
===============================================
  Files                  37       37           
  Lines                1806     1806           
===============================================
  Hits                  977      977           
  Misses                829      829           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

🧹 Outside diff range and nitpick comments (2)
frontend/src/components/ChatReferenceDrawer.tsx (1)

29-31: Fix indentation for better readability

The error logging block seems to be incorrectly indented. To improve code readability and maintain consistent style, please adjust the indentation.

Apply this diff to fix the indentation:

   if (isOpen) {
     file_url =
       project_id && filename
         ? `${BASE_STORAGE_URL}/${project_id}/${filename}`
         : null;
-    if (!filename) {
-      console.error("Filename is required to display the reference");
-    }
+    if (!filename) {
+      console.error("Filename is required to display the reference");
+    }
   }
frontend/src/ee/components/HighlightPdfViewer.tsx (1)

41-57: LGTM! Consider adding a version check for the polyfill.

The changes look good and improve compatibility:

  1. The Promise.withResolvers polyfill ensures the method is available across different environments.
  2. The update to pdfjs.GlobalWorkerOptions.workerSrc improves module compatibility.

Consider adding a version check before applying the polyfill:

if (typeof Promise.withResolvers === "undefined") {
  if (!Promise.prototype.hasOwnProperty('withResolvers')) {
    // Apply the polyfill
  }
}

This ensures we don't override any native implementations in future browser versions.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b82c6e3 and f82f0f2.

📒 Files selected for processing (4)
  • frontend/src/components/ChatReferenceDrawer.tsx (1 hunks)
  • frontend/src/components/ui/ChatBubble.tsx (1 hunks)
  • frontend/src/components/ui/MessageWithReferences.tsx (0 hunks)
  • frontend/src/ee/components/HighlightPdfViewer.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • frontend/src/components/ui/MessageWithReferences.tsx
🧰 Additional context used
🔇 Additional comments (3)
frontend/src/components/ChatReferenceDrawer.tsx (1)

23-31: Improved performance and logical structure. LGTM!

The changes enhance the component's efficiency by:

  1. Calculating file_url only when the drawer is open.
  2. Logging errors for missing filename only when relevant.

This optimization is particularly beneficial in scenarios with numerous chat references.

frontend/src/components/ui/ChatBubble.tsx (1)

134-136: Simplified markdown rendering: Verify impact and browser compatibility

The removal of remarkPlugins from the ReactMarkdown component simplifies the markdown rendering process. However, this change might affect the rendering of GitHub Flavored Markdown (GFM) features such as tables, task lists, or autolinks.

  1. Could you please clarify the reason for removing GFM support? Is this related to the "broken ui issues in safari" mentioned in the PR title?
  2. Have you verified that all required markdown features are still rendering correctly without the remarkGfm plugin?
  3. Please ensure to test the markdown rendering across different browsers, especially Safari, to confirm that this change resolves the reported UI issues without introducing new problems.

To help verify the impact of this change, you can run the following script to check for usage of GFM-specific features in your markdown content:

This script will help identify if there are any GFM-specific features in your markdown content that might be affected by the removal of the remarkGfm plugin.

✅ Verification successful

Removal of remarkGfm Verified: No Impact on Markdown Features Detected

The executed verification script did not find any GitHub Flavored Markdown (GFM) features such as tables, task lists, autolinks, or strikethrough in the markdown content. This indicates that the removal of the remarkGfm plugin does not adversely affect markdown rendering within the application.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential GFM features in markdown content that might be affected by the removal of remarkGfm

# Test: Search for GFM-specific features in markdown files
echo "Searching for potential GFM features in markdown content:"
echo "1. Tables:"
rg '^\|.*\|$' --type md
echo "2. Task Lists:"
rg '^\s*- \[ \]' --type md
echo "3. Autolinks:"
rg '<http' --type md
echo "4. Strikethrough:"
rg '~~.*~~' --type md

# Note: This script checks markdown files, but you should also verify any dynamically generated markdown content in your application.

Length of output: 378

frontend/src/ee/components/HighlightPdfViewer.tsx (1)

Line range hint 1-457: Overall, these changes enhance compatibility without altering core functionality.

The modifications to the HighlightPdfViewer component focus on improving compatibility and modernizing the PDF.js worker loading process. These changes:

  1. Ensure Promise.withResolvers is available across different environments.
  2. Update the PDF.js worker source to use ES modules, potentially improving performance and compatibility with modern bundlers.

The core functionality of PDF rendering and highlighting remains intact, with these changes likely improving the component's robustness across different environments.

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

🧹 Outside diff range and nitpick comments (4)
frontend/next.config.mjs (1)

15-23: LGTM! Consider adding a comment explaining the purpose of this Webpack configuration.

The added webpack function correctly modifies the Webpack configuration to handle .mjs files while excluding pdf.worker.min.mjs. This change is likely addressing module processing issues, particularly for PDF-related functionality, which aligns with the PR's objective of fixing UI issues in Safari.

To improve code maintainability, consider adding a brief comment explaining why this configuration is necessary. For example:

webpack(config) {
  // Handle .mjs files correctly while excluding pdf.worker.min.mjs
  // This fixes module processing issues, particularly for PDF functionality in Safari
  config.module.rules.push({
    // ... (rest of the configuration)
  });

  return config;
},
backend/app/processing/process_queue.py (3)

139-141: Clarify exception message when no process steps are found

Currently, if process_steps is empty, the code raises an exception with the message "No process found!":

if not process_steps:
    raise Exception("No process found!")

This might be misleading because the process exists, but there are no associated process steps. This exception message could be clearer.

Suggested Improvement:

Update the exception message to more accurately reflect the situation:

if not process_steps:
-    raise Exception("No process found!")
+    raise Exception("No process steps found for the given process ID!")

Line range hint 148-165: Potential threading issues with shared mutable data structures

The lists summaries and failed_docs are being shared and modified across multiple threads without any synchronization:

failed_docs = []
summaries = []

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    futures = [
        executor.submit(
            process_step_task,
            process.id,
            process_step.id,
            summaries,
            failed_docs,
            api_key,
        )
        for process_step in ready_process_steps
    ]

Within process_step_task, these lists are modified:

  • summaries.append(data["summary"])
  • failed_docs.append(process_step.asset.id)

Modifying shared mutable objects across threads without synchronization can lead to race conditions and inconsistent state.

Suggested Fix:

Use thread-safe data structures or synchronization mechanisms. Here are two possible approaches:

Option 1: Use Thread-Safe Queues

from queue import Queue

failed_docs = Queue()
summaries = Queue()

# Modify `process_step_task` to work with Queues
def process_step_task(..., summaries_queue, failed_docs_queue, ...):
    ...
    summaries_queue.put(data["summary"])
    ...
    failed_docs_queue.put(process_step.asset.id)

Option 2: Use Locks to Synchronize Access

from threading import Lock

failed_docs_lock = Lock()
summaries_lock = Lock()
failed_docs = []
summaries = []

def process_step_task(..., summaries_lock, failed_docs_lock, ...):
    ...
    with summaries_lock:
        summaries.append(data["summary"])
    ...
    with failed_docs_lock:
        failed_docs.append(process_step.asset.id)

You'll need to pass the locks to the process_step_task function and ensure that all access to the shared lists is properly synchronized.


Potential Sensitive Data Exposure Confirmed

Exception messages are being stored directly in the database, which could expose sensitive information. Consider sanitizing exception messages before storage or logging only non-sensitive summaries.

🔗 Analysis chain

Line range hint 215-216: Potential sensitive data exposure in exception messages

Storing raw exception messages in the database could expose sensitive information if the exceptions contain confidential data:

process.message = str(e)

Ensure that the exception messages do not include sensitive information before storing them. Consider sanitizing the messages or logging only non-sensitive summaries.

Run the following script to identify where exception messages are stored:

Review these instances to confirm that no sensitive data is being stored.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for all instances where exception messages are stored in the database.

rg --type py "process\.message\s*=" -A 2

Length of output: 224

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f82f0f2 and 03057f1.

📒 Files selected for processing (3)
  • backend/app/processing/process_queue.py (1 hunks)
  • frontend/next.config.mjs (1 hunks)
  • frontend/src/ee/components/HighlightPdfViewer.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/ee/components/HighlightPdfViewer.tsx
🧰 Additional context used

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

🧹 Outside diff range and nitpick comments (1)
frontend/next.config.mjs (1)

Line range hint 1-1: Consider keeping the type annotation for nextConfig

The AI summary mentions that the type annotation for nextConfig has been removed. While this isn't visible in the provided code snippet, it's worth addressing.

/** @type {import('next').NextConfig} */

Keeping this type annotation can be beneficial for the following reasons:

  1. It provides better type checking and autocompletion in TypeScript-aware editors.
  2. It helps catch potential configuration errors early in the development process.
  3. It serves as documentation for other developers working on the project.

Unless there's a specific reason for removing it, consider adding the type annotation back.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 995f118 and dc398a7.

📒 Files selected for processing (1)
  • frontend/next.config.mjs (1 hunks)
🧰 Additional context used
🔇 Additional comments (1)
frontend/next.config.mjs (1)

14-20: LGTM: Web Worker support added

The addition of the webpack configuration to handle .worker.js files is a good improvement. This change allows the application to use Web Workers, which can significantly enhance performance by offloading heavy computations from the main thread.

A few points to consider:

  1. Ensure that the worker-loader package is added to the project dependencies.
  2. Be aware that this configuration will increase the bundle size slightly, as it includes the worker-loader.
  3. Make sure to test the Web Worker functionality across different browsers to ensure compatibility.

@gventuri gventuri merged commit f16810c into release/v0.2.3 Oct 17, 2024
5 checks passed
@gventuri gventuri deleted the fix/cross_browser_issues branch October 17, 2024 21:36
gventuri pushed a commit that referenced this pull request Oct 20, 2024
* fix: broken ui issues in safari

* fix[pdfHighlight]: build and pdf highlight issues resolved

* fix: build issues on github

* fix: build issues

* fix: build issues
This was referenced Oct 20, 2024
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.

3 participants