Skip to content

Conversation

@jackshen310
Copy link
Collaborator

@jackshen310 jackshen310 commented Jan 7, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved screen sharing functionality in the realtime API
    • Added checks for video support to prevent unnecessary device error messages
  • New Features

    • Enhanced control over video sources during screen sharing
    • Asynchronous error handling for video input device selection in the header component
  • Chores

    • Updated package version for @coze/realtime-api from 1.0.3-beta.6 to 1.0.3-beta.7
  • Tests

    • Expanded mock functionality for screen management and video source configuration in tests

@coderabbitai
Copy link

coderabbitai bot commented Jan 7, 2025

Walkthrough

The pull request introduces a patch for the @coze/realtime-api package, specifically addressing a bug related to screen sharing functionality. Enhancements are made to the EngineClient class in client.ts, focusing on video handling, including the introduction of a new type, VideoSourceType. Changes also include improved error handling in the Header component for video input device selection and updates to the mock engine for testing purposes. The package version is incremented from 1.0.3-beta.6 to 1.0.3-beta.7.

Changes

File Change Summary
packages/realtime-api/src/client.ts - Imported VideoSourceType from @volcengine/rtc
- Enhanced setVideoInputDevice method for screen sharing
- Improved changeVideoState method with explicit video source type handling
common/changes/@coze/realtime-api/... - Added metadata for the package change (multiple entries)
examples/realtime-console/src/pages/main/header.tsx - Updated handleVideoInputDeviceChange to be asynchronous with error handling
packages/realtime-api/package.json - Version updated from 1.0.3-beta.6 to 1.0.3-beta.7
packages/realtime-api/test/client.spec.ts - Added methods unpublishScreen, publishScreen, setVideoSourceType to mockEngine
- Added constant VIDEO_SOURCE_TYPE_INTERNAL to VideoSourceType

Possibly related PRs

Suggested reviewers

  • jsongo

Poem

🐰 In a world of screens, we hop and play,
Video streams dance in a bright array,
With types defined, our captures are clear,
Sharing the magic, we spread the cheer!
CodeRabbit's code, a joyful delight,
Streaming together, everything feels right! 🎥✨


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/realtime-api/src/client.ts (1)

315-320: Extract duplicated screen sharing setup logic.

The screen sharing initialization logic is duplicated between setVideoInputDevice and changeVideoState. Consider extracting it into a reusable method.

Example refactor:

+ private async initializeScreenSharing() {
+   try {
+     this.engine.setVideoSourceType(
+       StreamIndex.STREAM_INDEX_SCREEN,
+       VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL,
+     );
+     await this.engine.startScreenCapture(this._videoConfig?.screenConfig);
+     await this.engine.publishScreen(MediaType.AUDIO_AND_VIDEO);
+   } catch (e) {
+     await this.engine.stopScreenCapture().catch(console.error);
+     throw e;
+   }
+ }

Then use it in both places:

// In setVideoInputDevice
if (isAutoCapture) {
  await this.initializeScreenSharing();
}

// In changeVideoState
if (isVideoOn && this._streamIndex !== StreamIndex.STREAM_INDEX_MAIN) {
  await this.initializeScreenSharing();
}
🛑 Comments failed to post (1)
packages/realtime-api/src/client.ts (1)

229-234: 🛠️ Refactor suggestion

Add error handling for screen sharing initialization.

While the screen sharing setup logic is correct, it lacks proper error handling. If screen capture fails, the publish operation might still be attempted, potentially leaving the system in an inconsistent state.

Consider wrapping the operations in a try-catch block:

-        this.engine.setVideoSourceType(
-          StreamIndex.STREAM_INDEX_SCREEN,
-          VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL,
-        );
-        await this.engine.startScreenCapture(this._videoConfig?.screenConfig);
-        await this.engine.publishScreen(MediaType.AUDIO_AND_VIDEO);
+        try {
+          this.engine.setVideoSourceType(
+            StreamIndex.STREAM_INDEX_SCREEN,
+            VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL,
+          );
+          await this.engine.startScreenCapture(this._videoConfig?.screenConfig);
+          await this.engine.publishScreen(MediaType.AUDIO_AND_VIDEO);
+        } catch (e) {
+          // Cleanup on failure
+          await this.engine.stopScreenCapture().catch(console.error);
+          throw e;
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        try {
          this.engine.setVideoSourceType(
            StreamIndex.STREAM_INDEX_SCREEN,
            VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL,
          );
          await this.engine.startScreenCapture(this._videoConfig?.screenConfig);
          await this.engine.publishScreen(MediaType.AUDIO_AND_VIDEO);
        } catch (e) {
          // Cleanup on failure
          await this.engine.stopScreenCapture().catch(console.error);
          throw e;
        }

@codecov
Copy link

codecov bot commented Jan 7, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

@@            Coverage Diff             @@
##             main      #75      +/-   ##
==========================================
+ Coverage   91.75%   92.50%   +0.75%     
==========================================
  Files         115       46      -69     
  Lines        5325     2349    -2976     
  Branches     1081      426     -655     
==========================================
- Hits         4886     2173    -2713     
+ Misses        431      175     -256     
+ Partials        8        1       -7     
Components Coverage Δ
coze-js 92.81% <ø> (ø)
realtime-api 91.78% <100.00%> (+0.13%) ⬆️
Files with missing lines Coverage Δ
packages/realtime-api/src/client.ts 88.06% <100.00%> (+0.38%) ⬆️

... and 69 files with indirect coverage changes

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

🧹 Nitpick comments (1)
examples/realtime-console/src/pages/main/header.tsx (1)

286-293: Enhanced error handling for video device changes.

The function is now properly handling asynchronous device changes and provides user feedback through error messages.

Consider adding a loading state while the device change is in progress:

 const handleVideoInputDeviceChange = async (value: string) => {
+  const prevDeviceId = videoInputDeviceId;
   try {
+    setIsChangingDevice(true);
     setVideoInputDeviceId(value);
     await clientRef.current?.setVideoInputDevice(value);
   } catch (error) {
     message.error(`Failed to set video input device: ${error}`);
+    setVideoInputDeviceId(prevDeviceId);
     console.error(error);
+  } finally {
+    setIsChangingDevice(false);
   }
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b791012 and 0f310e4.

📒 Files selected for processing (7)
  • common/changes/@coze/realtime-api/feat-realtime-api_2025-01-07-08-19.json (1 hunks)
  • common/changes/@coze/realtime-api/feat-realtime-api_2025-01-07-08-27.json (1 hunks)
  • common/changes/@coze/realtime-api/feat-realtime-api_2025-01-08-06-20.json (1 hunks)
  • examples/realtime-console/src/pages/main/header.tsx (1 hunks)
  • packages/realtime-api/package.json (1 hunks)
  • packages/realtime-api/src/client.ts (4 hunks)
  • packages/realtime-api/test/client.spec.ts (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • common/changes/@coze/realtime-api/feat-realtime-api_2025-01-07-08-27.json
  • packages/realtime-api/package.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • common/changes/@coze/realtime-api/feat-realtime-api_2025-01-07-08-19.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node.js v20 (ubuntu-latest)
🔇 Additional comments (5)
packages/realtime-api/src/client.ts (3)

315-320: Consistent video source type handling during state changes.

The changes ensure consistent video source type configuration when enabling screen sharing, matching the initialization sequence in setVideoInputDevice.


327-327: Added proper cleanup for screen sharing.

Added explicit unpublishing of screen video stream during cleanup, preventing potential resource leaks.


229-234: Improved screen sharing initialization sequence.

The changes properly initialize screen sharing by setting the video source type before starting screen capture and publishing. This fixes potential synchronization issues in the screen sharing setup.

Let's verify the screen sharing initialization sequence:

✅ Verification successful

Screen sharing initialization sequence is properly implemented.

The initialization sequence (setVideoSourceType → startScreenCapture → publishScreen) is consistently implemented across the codebase, with proper test coverage validating the behavior. No other instances require similar fixes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any other screen sharing initialization patterns that might need similar fixes

# Search for screen capture initialization patterns
ast-grep --pattern 'startScreenCapture($$$)'

# Search for screen publishing patterns
ast-grep --pattern 'publishScreen($$$)'

Length of output: 88


Script:

#!/bin/bash
# Search for screen-related patterns with proper TypeScript syntax
ast-grep -l ts --pattern 'class $_ {
  $$$
  startScreenCapture($$$) {
    $$$
  }
  $$$
}'

ast-grep -l ts --pattern 'class $_ {
  $$$
  setVideoSourceType($$$) {
    $$$
  }
  $$$
}'

# Use ripgrep for broader context
rg "startScreenCapture|publishScreen|setVideoSourceType" -A 2 -B 2

Length of output: 3828

packages/realtime-api/test/client.spec.ts (1)

31-33: Added comprehensive test coverage for screen sharing.

The mock engine now includes all necessary methods for testing screen sharing functionality, along with the required VideoSourceType constant.

Let's verify the test coverage:

Also applies to: 58-60

✅ Verification successful

Screen sharing test coverage is comprehensive and well-implemented

The test suite includes thorough coverage of screen sharing functionality:

  • Screen share device selection and validation
  • Screen capture lifecycle (start/stop)
  • Stream management and player integration
  • Error handling and edge cases
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all screen sharing related methods are properly tested

# Search for screen sharing related test cases
rg -A 5 'describe.*screen'

Length of output: 28


Script:

#!/bin/bash
# Search for usage of screen sharing related methods in test files
echo "=== Searching for screen sharing method usage ==="
rg "unpublishScreen|publishScreen|setVideoSourceType" --type ts

echo -e "\n=== Searching for VideoSourceType imports ==="
rg "VideoSourceType" --type ts

echo -e "\n=== Looking for test files containing these methods ==="
fd -e spec.ts -e test.ts --exec grep -l "unpublishScreen\|publishScreen\|setVideoSourceType" {}

Length of output: 1763


Script:

#!/bin/bash
# Get the content of the test file focusing on screen sharing related tests
echo "=== Content of client.spec.ts ==="
rg -B 5 -A 10 "unpublishScreen|publishScreen|setVideoSourceType|VideoSourceType" packages/realtime-api/test/client.spec.ts

Length of output: 1038


Script:

#!/bin/bash
# Get the complete content of the test file to find test cases
echo "=== Complete test file content ==="
cat packages/realtime-api/test/client.spec.ts

Length of output: 12935

common/changes/@coze/realtime-api/feat-realtime-api_2025-01-08-06-20.json (1)

1-11: Appropriate version bump for bug fix.

The patch version bump and change description accurately reflect the nature of the changes.

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

🧹 Nitpick comments (1)
packages/realtime-api/src/client.ts (1)

315-327: Improve error handling for screen sharing cleanup.

Consider wrapping the screen sharing operations in try-catch blocks to ensure proper cleanup even if an operation fails. This is particularly important for the unpublishScreen call.

 if (isVideoOn) {
   if (this._streamIndex === StreamIndex.STREAM_INDEX_MAIN) {
     await this.engine.startVideoCapture();
   } else {
+    try {
       this.engine.setVideoSourceType(
         StreamIndex.STREAM_INDEX_SCREEN,
         VideoSourceType.VIDEO_SOURCE_TYPE_INTERNAL,
       );
       await this.engine.startScreenCapture(this._videoConfig?.screenConfig);
       await this.engine.publishScreen(MediaType.VIDEO);
+    } catch (error) {
+      // Ensure cleanup if any operation fails
+      await this.engine.stopScreenCapture().catch(console.error);
+      throw error;
+    }
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f310e4 and dee8bd5.

📒 Files selected for processing (5)
  • common/changes/@coze/realtime-api/feat-realtime-api_2025-01-08-06-20.json (1 hunks)
  • common/changes/@coze/realtime-api/feat-realtime-api_2025-01-08-06-32.json (1 hunks)
  • examples/realtime-console/src/pages/main/header.tsx (1 hunks)
  • packages/realtime-api/src/client.ts (4 hunks)
  • packages/realtime-api/test/client.spec.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • common/changes/@coze/realtime-api/feat-realtime-api_2025-01-08-06-20.json
  • examples/realtime-console/src/pages/main/header.tsx
  • packages/realtime-api/test/client.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Node.js v20 (ubuntu-latest)
🔇 Additional comments (4)
common/changes/@coze/realtime-api/feat-realtime-api_2025-01-08-06-32.json (1)

1-11: LGTM! Changelog entry is appropriate.

The patch version increment and description accurately reflect the bug fix nature of the changes.

packages/realtime-api/src/client.ts (3)

10-10: LGTM! Required import for screen sharing functionality.

The VideoSourceType import is necessary for the screen sharing enhancements.


Line range hint 264-269: LGTM! Improved error handling for video device checks.

The addition of the video support check before throwing the device error prevents unnecessary errors when video is not supported. This change aligns well with the patch description.


229-234: Consider potential race condition in screen capture initialization.

While the changes fix the screen sharing bug by setting the correct video source type, there's a potential race condition between setVideoSourceType and startScreenCapture. Consider combining these operations or ensuring proper synchronization.

Run this script to check if there are any reported issues related to screen capture timing:

@jsongo jsongo added this pull request to the merge queue Jan 8, 2025
Merged via the queue into coze-dev:main with commit 8245f21 Jan 8, 2025
8 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